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

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

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

我该怎么做呢?


当前回答

我有这个问题,我做了一个简单的原型,使用它,如果你喜欢它

Array.prototype.findOrPush = function(predicate, fallbackVal) {
    let item = this.find(predicate)
    if(!item){
        item = fallbackVal
        this.push(item)
    }
    return item
}

let arr = [{id: 1}]
let item = arr.findOrPush(e => e.id == 2, {id: 2})
console.log(item) // {id: 2} 

// will not push and just return existing value
arr.findOrPush(e => e.id == 2, {id: 2}) 
conslog.log(arr)  // [{id: 1}, {id: 2}]

其他回答

如果没有结果,可以使用jQuery grep和push: http://api.jquery.com/jQuery.grep/

这基本上是与“扩展原型”解决方案相同的解决方案,但没有扩展(或污染)原型。

我知道这是一个非常老的问题,但如果你使用ES6,你可以使用一个非常小的版本:

[1,2,3].filter(f => f !== 3).concat([3])

非常简单,首先添加一个过滤器,删除项目-如果它已经存在,然后通过concat添加它。

下面是一个更现实的例子:

const myArray = ['hello', 'world']
const newArrayItem

myArray.filter(f => f !== newArrayItem).concat([newArrayItem])

如果你的数组包含对象,你可以像这样调整过滤器函数:

someArray.filter(f => f.some(s => s.id === myId)).concat([{ id: myId }])

像这样的吗?

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)

我建议你使用Set,

集只允许唯一的条目,这将自动解决您的问题。

集合可以这样声明:

const baz = new Set(["Foo","Bar"])

我想我在这里回答太迟了,然而这是我最终想出的一个邮件管理器我写。好的,这就是我需要的。

窗口。ListManager = []; $(' #添加').click(函数(){ / /你的功能 let data =Math.floor(Math.random() * 5) + 1 如果(window.ListManager.includes(数据)){ Console.log("数据存在于列表") 其他}{ window.ListManager.push(数据); } $(' #结果')。text (window.ListManager); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <标题>独特列表< / h1 > < p id = "结果" > < / p > </button> . <button id="add">添加到列表中