开发者社区 问答 正文

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

我怎样才能做到这一点?

展开
收起
保持可爱mmm 2020-01-16 15:44:53 359 分享 版权
1 条回答
写回答
取消 提交回答
  • 您可以使用自定义方法扩展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; }); 问题来源于stack overflow

    2020-01-16 15:45:07
    赞同 展开评论
问答地址: