如果不存在Array.push()? [英] Array.push() if does not exist?

查看:157
本文介绍了如果不存在Array.push()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个值都不存在,我怎样才能进入数组?这是我的数组:

How can I push into an array if neither values exist? Here is my array:

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

如果我尝试使用名称再次推入数组:tom text:tasty,我不希望发生任何事情...但如果这些都没有,那么我想要它 .push()

If I tried to push again into the array with either name: "tom" or text: "tasty", I don't want anything to happen... but if neither of those are there then I want it to .push()

我该怎么做?

推荐答案

您可以使用自定义方法扩展Array原型:

You could extend the Array prototype with a custom method:

// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) { 
    for(var i=0; i < this.length; i++) { 
        if(comparer(this[i])) return true; 
    }
    return false; 
}; 

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function(element, comparer) { 
    if (!this.inArray(comparer)) {
        this.push(element);
    }
}; 

var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) { 
    return e.name === element.name && e.text === element.text; 
});

这篇关于如果不存在Array.push()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆