Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

javascript - Array.push()如果不存在?(Array.push() if does not exist?)

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

(如果我尝试再次使用name: "tom"text: "tasty"将其推入数组,那么我什么都不想发生……但是,如果这两个都不存在,那么我希望它执行.push())

How can I do this?

(我怎样才能做到这一点?)

  ask by tarnfeld translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf() and if it doesn't then just push the item into the array:

(对于字符串数组(而不是对象数组),您可以通过调用.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) 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...