tasty

Array.push() if does not exist?

匿名 (未验证) 提交于 2019-12-03 02:11:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: 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? 回答1: You could extend the Array prototype with a custom method: // check if an element exists in array using a