如果两个值都不存在,我如何推入数组?下面是我的数组:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
如果我尝试使用name: "tom"
或text: "tasty"
再次推入数组,我不希望发生任何事情……但是如果这两个都不存在,那么我想让它变成.push()
我该怎么做呢?
发布于 2010-01-01 19:12:31
您可以使用自定义方法扩展Array原型:
// 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;
});
发布于 2016-06-09 21:16:33
使用Array.findIndex
函数很容易做到这一点,该函数接受一个函数作为参数:
var arrayObj = [{name:"bull", text: "sour"},
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob");
// here you can check specific property for an object whether it exist in your array or not
index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
发布于 2012-10-14 07:02:08
http://api.jquery.com/jQuery.unique/
var cleanArray = $.unique(clutteredArray);
您可能也会对makeArray感兴趣
前面的例子最好的说法是在推流之前检查它是否存在。我在事后看到它还声明你可以将它声明为原型的一部分(我猜这是aka类扩展),所以下面没有什么大的改进。
除了我不确定indexOf是不是比inArray更快?可能吧。
Array.prototype.pushUnique = function (item){
if(this.indexOf(item) == -1) {
//if(jQuery.inArray(item, this) == -1) {
this.push(item);
return true;
}
return false;
}
https://stackoverflow.com/questions/1988349
复制相似问题