Array.push() 如果不存在?

新手上路,请多包涵

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

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

我怎样才能做到这一点?

原文由 tarnfeld 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

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

原文由 Darin Dimitrov 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于字符串数组(但不是对象数组),您可以通过调用 .indexOf() 来检查项目是否存在,如果不存在,则只需将项目 入数组:

 var newItem = "NEW_ITEM_TO_ARRAY";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];

array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists");

console.log(array)

原文由 Jiří Zahálka 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题