如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。
function removeElement(idx, arr) {
// Check the index value
if (idx < 0 || idx >= arr.length) {
return;
}
// Shift the elements
for (var i = idx; i > 0; --i) {
arr[i] = arr[i - 1];
}
// Remove the first element in array
arr.shift();
}
其他回答
如果您使用现代浏览器, 您可以使用. 过滤器 。
Array.prototype.remove = function(x){
return this.filter(function(v){
return v !== x;
});
};
var a = ["a","b","c"];
var b = a.remove('a');
这提供了一个前提值, 而不是一个值 。
注:这将更新给定的数组, 并返回受影响的行 。
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
var helper = {
// Remove and return the first occurrence
remove: function(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array.splice(i, 1);
}
}
},
// Remove and return all occurrences
removeAll: function(array, predicate) {
var removed = [];
for (var i = 0; i < array.length; ) {
if (predicate(array[i])) {
removed.push(array.splice(i, 1));
continue;
}
i++;
}
return removed;
},
};
一个非常天真的执行情况如下:
Array.prototype.remove = function(data) {
const dataIdx = this.indexOf(data)
if(dataIdx >= 0) {
this.splice(dataIdx ,1);
}
return this.length;
}
let a = [1,2,3];
// This will change arr a to [1, 3]
a.remove(2);
我从函数返回数组的长度以遵守其他方法,例如Array.prototype.push()
.
spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :
function removeArrayItem(index, array) {
array.splice(index, 1);
return array;
}
let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);
最基本的解决办法是:
array.key = null;