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

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

问题描述

我怎么能推高到一个数组中是否存在没有价值?这里是我的JSON数组/对象:

How can i push up into an array if neither values exist? Here is my json array/object:

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

如果我试图再次推入阵列或者的名字:汤姆的文字:好吃的我不想发生什么事......但是,如果这两个时间都不存在,然后我希望它 .push()

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

我怎样才能做到这一点?

How can i do this?

推荐答案

您可以用自定义的方法扩展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; 
});

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

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