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

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

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

我该怎么做呢?


当前回答

我更喜欢使用原生js Array.prototype.some(),即使在jqenv中 文档:w3s some or mdn some

let arr = [
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
];
let oneMore = { name: "tom", text: "tasty" };
!arr.some(i => i.name == oneMore.name && i.text == oneMore.text)
  && arr.push(oneMore);

其他回答

这是一个对象比较的工作函数。在某些情况下,您可能需要比较许多字段。 只需循环数组并使用现有项和新项调用此函数。

 var objectsEqual = function (object1, object2) {
        if(!object1 || !object2)
            return false;
        var result = true;
        var arrayObj1 = _.keys(object1);
        var currentKey = "";
        for (var i = 0; i < arrayObj1.length; i++) {
            currentKey = arrayObj1[i];
            if (object1[currentKey] !== null && object2[currentKey] !== null)
                if (!_.has(object2, currentKey) ||
                    !_.isEqual(object1[currentKey].toUpperCase(), object2[currentKey].toUpperCase()))
                    return false;
        }
        return result;
    };

对于字符串数组(但不是对象数组),你可以通过调用.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(数组)

我的选择是使用.includes()扩展数组。正如@Darrin Dimitrov所建议的原型:

Array.prototype.pushIfNotIncluded = function (element) {
    if (!this.includes(element)) {
      this.push(element);
    }
}

记住include来自es6,在IE上不起作用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

像这样的吗?

var item = "Hello World";
var array = [];
if (array.indexOf(item) === -1) array.push(item);

与对象

var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
    array.push(item)

A是你拥有的对象数组

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