在本文中,您将了解如何检查对象值是否存在,如果不存在,则使用 javascript 将新对象添加到数组中。在 javascript 中,几乎每个变量都是一个对象。对象可以是字符串、数字、布尔值等,也可以是键值对。
javascript 中的数组是一种特殊的变量,可以容纳多个项目。可以使用关键字“const”初始化数组。
示例 1在此示例中,我们使用 .some() 函数检查对象是否存在。
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'));
说明第 1 步 - 定义一个数组“inputarray”并向其中添加键值对值。
第 2 步 - 定义一个函数“checkname”,它将字符串作为参数。
第 3 步 - 在函数中,使用函数 some() 检查给定值是否存在于数组中。
第 4 步 - 显示布尔值作为结果。
示例 2在此示例中,我们通过使用 push() 函数将对象推送到数组末尾,将对象值添加到数组中。
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)
说明第 1 步 - 定义一个数组“inputarray”并向其中添加键值对值。
第 2 步 - 定义一个函数“addobject”,它将字符串作为参数。
第3步 - 在函数中,使用函数array.push将对象推送到数组的最后一个位置。
第 4 步 - 将数组显示为结果。
以上就是如何使用 javascript 检查对象值是否存在而不向数组添加新对象?的详细内容。
