javascript - 如果存在,如何从数组中删除一个值,如果不存在,如何将其推送到数组?
问题描述
如果存在,如何从数组中删除一个值,如果不存在,如何将其推送到数组?
HTML:
...
<button @click="addToOpenedMenuPosition(item.id)"
...
Vue.js:
data: function() { return {
openedMenuPositionIds: [],
...
}
解决方案
使用js的简单实现
const arr = ["one","two","three"]; //example array
const newId="one"; //new id
if(!arr.includes(newId)){ //checking weather array contain the id
arr.push(newId); //adding to array because value doesnt exists
}else{
arr.splice(arr.indexOf(newId), 1); //deleting
}
console.log(arr);