是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
非破坏性拆卸:
function removeArrayValue(array, value)
{
var thisArray = array.slice(0); // copy the array so method is non-destructive
var idx = thisArray.indexOf(value); // initialise idx
while(idx != -1)
{
thisArray.splice(idx, 1); // chop out element at idx
idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
}
return thisArray;
}
其他回答
你可以像这样使用indexOf方法:
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
注意:对于IE8及以下版本,您需要对其进行填充
Var数组= [1,2,3,4] Var项= 3 var index = array.indexOf(item); 数组中。拼接(指数(1); console.log(数组)
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]
请不要使用带有delete的变体-它会在数组中留下一个洞,因为它不会在删除的项之后重新索引元素。
> Array.prototype.remove=function(v){
... delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]
一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:
/**
* @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;
}
我使用了投票最多的选项,并创建了一个函数,该函数将使用另一个不需要的单词数组清理一个单词数组:
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)