是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]
其他回答
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;
}
你要的是滤镜
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
这将允许你做以下事情:
var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']
这一点在其他地方也有注意到:https://stackoverflow.com/a/20827100/293492
这样看看:
delete this.arrayName[this.arrayName.indexOf(value)];
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
我使用了投票最多的选项,并创建了一个函数,该函数将使用另一个不需要的单词数组清理一个单词数组:
function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
$.each(unwantedTermsArray, function( index, value ) {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
});
return array;
}
要使用,请执行以下操作:
var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];
cleanArrayOfSpecificTerms(splitTerms,notInclude)