如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
您只需要按元素或索引过滤 :
var num = [5, 6, 5, 4, 5, 1, 5];
var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5
console.log(result1);
console.log(result2);
其他回答
const array = [1,2,3,4,5,6,7,8,9,0];
const index = array.indexOf(5);
// find Index of specific number
if(index != -1){
array.splice(index, 1); // remove number using index
}
console.log(array);
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6];
array = array.filter(number=> number !== 5);
console.log(array);
使用合并和拆分
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6]
array = Array.from(array.join("-").split("-5-").join("-").split("-"),Number)
console.log(array)
删除上次发生或所有发生, 还是第一次发生 ?
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Remove this line to remove all occurrences
}
}
或
var array = [2, 5, 9, 5];
// Remove first occurrence
for (var i = 0; array.length; i++) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Do not remove this line
}
}
我喜欢这个组合的版本, 以其值来去除元素, 使用$.inArray
:
$(document).ready(function(){
var arr = ["C#","Ruby","PHP","C","C++"];
var itemtoRemove = "PHP";
arr.splice($.inArray(itemtoRemove, arr),1);
});
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');
console.log(fruits);
// -> ['apple', 'carrot', 'orange']