Array.push() 如果不存在?

2022-08-29 23:43:36

如果两个值都不存在,我该如何推入数组?这是我的数组:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

如果我试图用或再次推入数组,我不希望任何事情发生......但是如果这两个都不存在,那么我希望它name: "tom"text: "tasty".push()

我该怎么做?


答案 1

对于字符串数组(但不是对象数组),您可以通过调用来检查项目是否存在,如果不存在,则只需将项目推送到数组中:.indexOf()

var newItem = "NEW_ITEM_TO_ARRAY";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];

array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists");

console.log(array)

答案 2

使用函数很容易做到,它将函数作为参数:Array.findIndex

var arrayObj = [{name:"bull", text: "sour"},
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob"); 
// here you can check specific property for an object whether it exist in your array or not

index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")