如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
使用数组过滤过滤器方法 :
let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)
其他回答
const newArray = oldArray.filter(item => item !== removeItem);
var index,
input = [1,2,3],
indexToRemove = 1;
integers = [];
for (index in input) {
if (input.hasOwnProperty(index)) {
if (index !== indexToRemove) {
integers.push(result);
}
}
}
input = integers;
此解决方案将需要一系列输入, 并将通过输入查找要删除的值。 这将在整个输入数组中循环, 结果将是第二个已经删除了特定索引的数组整数组。 然后将整数组复制到输入数组中 。
我对基底 JavaScript 阵列进行了相当高效的扩展:
Array.prototype.drop = function(k) {
var valueIndex = this.indexOf(k);
while(valueIndex > -1) {
this.removeAt(valueIndex);
valueIndex = this.indexOf(k);
}
};
使用使用jj 查询. grep ():
var y = [1, 2, 3, 9, 4]
var removeItem = 9;
y = jQuery.grep(y, function(value) {
return value != removeItem;
});
console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
有个朋友有问题因特网探索者 8并告诉我他做了什么。我告诉他这是错的,他告诉我他在这里得到了答案。当前的顶级答案不会在所有浏览器(例如因特网探索者8号)中都有效,它只会消除项目首次出现的情况。
function removeAllInstances(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === item) arr.splice(i, 1);
}
}
它会从数组向后循环( 因为随着项目被删除, 指数和长度会变化) , 如果找到的话, 它会删除它。 它会在所有浏览器中发挥作用 。