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

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

如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()

我该怎么做呢?


当前回答

短的例子:

if (typeof(arr[key]) === "undefined") {
  arr.push(key);
}

其他回答

someArray = [{a: 'a1 value', b: {c: "c1 value"},
             {a: 'a2 value', b: {c: "c2 value"}]
newObject = {a: 'a2 value', b: {c: "c2 value"}}

//New object which needs check for duplicity

let isExists = checkForExists(newObject) {
    return someArray.some(function(el) {
        return el.a === newObject.a && el.b.c === newObject.b.c;
    });
}
// write your logic here 
// if isExists is true then already object in an array else you can add

对于字符串数组(但不是对象数组),你可以通过调用.indexOf()来检查一个项是否存在,如果不存在,则将该项推入数组:

var newItem = "NEW_ITEM_TO_ARRAY"; var array = ["OLD_ITEM_1", "OLD_ITEM_2"]; array.indexOf(newItem) === -1 ?array.push(newItem): console.log("此项已存在"); console.log(数组)

正是出于这些原因,使用像underscore.js这样的js库。union:计算传入数组的并集:在一个或多个数组中出现的唯一项的列表。

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

如果你需要一些简单的东西,而不想扩展数组原型:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

A是你拥有的对象数组

a.findIndex(x => x.property=="WhateverPropertyYouWantToMatch") <0 ? 
a.push(objectYouWantToPush) : console.log("response if object exists");