如何在数组中删除一个已存在的值或者将其推入数组中(如果不存在)?

19
如何从数组中删除一个值,如果存在,则将其删除,否则将其推送到数组中? HTML:
...
<button @click="addToOpenedMenuPosition(item.id)"
...

Vue.js:

data: function() { return {
    openedMenuPositionIds: [],
    ...
}

3
你能举例详细说明吗? - Manu
你能详细说明一下吗?因为我们需要知道你的数组保存的是原始值还是对象等等。并且尝试给出一个示例,比如这是我的输入,我想要这样的输出... - pavan kumar
4个回答

30

使用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);

6

我假设元素是唯一的,所以:

很简单。你可以使用.includes()检查它是否在数组中,并使用.indexOf()查找id的索引。然后,你可以使用.splice()删除具有找到的索引的元素,否则只需将其推入数组。

你需要在那里使用return来“停止”函数继续执行:

addToOpenedMenuPosition(id){
   let arr = this.openedMenuPositionIds;
   if(arr.includes(id)){
      arr.splice(arr.indexOf(id), 1);
      return;
   }
   arr.push(id);
}

4
假设您想从仅包含整数ID的openedMenuPositionIds数组中删除item.id,您可以简单地使用数组.indexOf().push().splice()方法来实现此操作,例如:

var example2 = new Vue({
  el: '#example-2',
  data: function() {
    return {
      openedMenuPositionIds: [],
    }
  },
  // define methods under the `methods` object
  methods: {
  
    addToOpenedMenuPosition(id) {

      // Get the index of id in the array
      const index = this.openedMenuPositionIds.indexOf(id);
      if (index > -1) {
        // This means id is present in the array, so remove it
        this.openedMenuPositionIds.splice(index, 1);
      } else {
        // This means id is not present in the array, so add it
        this.openedMenuPositionIds.push(id);
      }
      
      // You can use this to debug purpose
      console.log( this.openedMenuPositionIds )
    }
  }
})


2
通过删除item.id创建一个新数组,但是如果item.id不存在,则不会删除任何内容,我们可以安全地添加item.id。否则,我们将返回已删除item.id的修改后的数组。
const newMenuPositionIds = menuPositionIds.filter(({id}) => id !== item.id);
if(newMenuPositionIds.length === menuPositionIds.length) {
    newMenuPositionIds.push(item.id);
}
return newMenuPositionIds;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接