在本文中,您將了解如何檢查對(duì)象值是否存在,如果不存在,則使用 JavaScript 將新對(duì)象添加到數(shù)組中。在 Javascript 中,幾乎每個(gè)變量都是一個(gè)對(duì)象。對(duì)象可以是字符串、數(shù)字、布爾值等,也可以是鍵值對(duì)。
JavaScript 中的數(shù)組是一種特殊的變量,可以容納多個(gè)項(xiàng)目。可以使用關(guān)鍵字“const”初始化數(shù)組。
示例 1
在此示例中,我們使用 .some() 函數(shù)檢查對(duì)象是否存在。
var inputArray = [{ id: 1, name: "JavaScript" }, { id: 2, name: "javascript"}, { id: 3, name: "Scala" }, { id: 4, name: "Java" }] console.log("The input array is defined as: ") console.log(inputArray) function checkName(name) { return inputArray.some(function(check) { return check.name === name; }); } console.log("Does the object JavaScript exist in the array? ") console.log(checkName('JavaScript')); console.log("Does the object HTML exist in the array? ") console.log(checkName('HTML'));
登錄后復(fù)制
說明
第 1 步 – 定義一個(gè)數(shù)組“inputArray”并向其中添加鍵值對(duì)值。
第 2 步 – 定義一個(gè)函數(shù)“checkName”,它將字符串作為參數(shù)。
第 3 步 – 在函數(shù)中,使用函數(shù) some() 檢查給定值是否存在于數(shù)組中。
第 4 步 – 顯示布爾值作為結(jié)果。
示例 2
在此示例中,我們通過使用 push() 函數(shù)將對(duì)象推送到數(shù)組末尾,將對(duì)象值添加到數(shù)組中。
var inputArray = [{ id: 1, name: "JavaScript" }, { id: 2, name: "javascript"}, { id: 3, name: "Scala" }] console.log("The input array is defined as: ") console.log(inputArray) function addObject(name) { inputArray.push({ id: inputArray.length + 1, name: name }); return true; } console.log("Adding Object : Java to the array") addObject("Java") console.log("The array after adding the object is") console.log(inputArray)
登錄后復(fù)制
說明
第 1 步 – 定義一個(gè)數(shù)組“inputArray”并向其中添加鍵值對(duì)值。
第 2 步 – 定義一個(gè)函數(shù)“addObject”,它將字符串作為參數(shù)。
第3步 – 在函數(shù)中,使用函數(shù)array.push將對(duì)象推送到數(shù)組的最后一個(gè)位置。
第 4 步 – 將數(shù)組顯示為結(jié)果。
以上就是如何使用 JavaScript 檢查對(duì)象值是否存在而不向數(shù)組添加新對(duì)象?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!