如果两个值都不存在,我如何推入数组?这是我的数组:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()
我该怎么做呢?
推动动态
var a = [
{name:"bull", text: "sour"},
{name: "tom", text: "tasty" },
{name: "Jerry", text: "tasty" }
]
function addItem(item) {
var index = a.findIndex(x => x.name == item.name)
if (index === -1) {
a.push(item);
}else {
console.log("object already exists")
}
}
var item = {name:"bull", text: "sour"};
addItem(item);
用简单的方法
var item = {name:"bull", text: "sour"};
a.findIndex(x => x.name == item.name) == -1 ? a.push(item) : console.log("object already exists")
如果数组只包含基元类型/简单数组
var b = [1, 7, 8, 4, 3];
var newItem = 6;
b.indexOf(newItem) === -1 && b.push(newItem);
这里你有一种方法可以在一行中为两个数组做这件事:
const startArray = [1,2,3,4]
const newArray = [4,5,6]
const result = [...startArray, ...newArray.filter(a => !startArray.includes(a))]
console.log(result);
//Result: [1,2,3,4,5,6]
正是出于这些原因,使用像underscore.js这样的js库。union:计算传入数组的并集:在一个或多个数组中出现的唯一项的列表。
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]