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

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

问题描述

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

<预><代码>[{名称:汤姆",文字:美味"},{名称:汤姆",文字:美味"},{名称:汤姆",文字:美味"},{名称:汤姆",文字:美味"},{名称:汤姆",文字:美味"}]

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

我该怎么做?

解决方案

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

//使用比较器函数检查数组中是否存在元素//比较器:函数(currentElement)Array.prototype.inArray = 函数(比较器){for(var i=0; i < this.length; i++) {if(comparer(this[i])) 返回真;}返回假;};//如果数组不存在,则使用比较器将其添加到数组中//功能Array.prototype.pushIfNotExist = 函数(元素,比较器){如果(!this.inArray(比较器)){this.push(元素);}};var array = [{ name: "tom", text: "tasty" }];var element = { name: "tom", text: "tasty" };array.pushIfNotExist(元素,函数(e){返回 e.name === element.name &&e.text === element.text;});

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" }
]

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()

How can I do this?

解决方案

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天全站免登陆