是否有从JavaScript数组中删除项的方法?

给定一个数组:

var ary = ['three', 'seven', 'eleven'];

我想做的事情是:

removeItem('seven', ary);

我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。


当前回答

//编辑感谢MarcoCI的建议

试试这个:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

希望这对你有所帮助

其他回答

你可以使用Lodash _来实现这一点。删除功能。

Var array = [' 3 ', ' 7 ', ' 11 ']; Var even = _。删除(数组,函数(e) { 返回e !== 'seven'; }); console.log(均等的); <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script> .js

这样看看:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

在函数中:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');

真的,我不明白为什么不能用

arr = arr.filter(value => value !== 'seven');

或者你可能想使用普通的JS

arr = arr.filter(function(value) { return value !== 'seven' });

ES6路。

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}