如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
由你决定如何行动。
一种做法是使用splice
从数组中删除项目的方法 :
let array = [1, 2, 3]
array.splice(1, 1);
console.log(array)
// return [1, 3]
但要确保您通过第二个参数,否则最终会删除索引后的全部数组。
第二种办法是使用filter
其好处在于它是不可改变的 这意味着您的主数组不会被操纵 :
const array = [1, 2, 3];
const newArray = array.filter(item => item !== 2)
console.log(newArray)
// return [1, 3]
其他回答
OK,OK, OK, OK, OK, OK, OK, OK, OK,OK, OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,例如,您有下面的数组:
var num = [1, 2, 3, 4, 5];
我们想要删除第4号, 你可以简单地使用下面的代码:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附于原土类似以下的数组函数 :
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
但如果您有下面的数组, 而不是数组中的几个 [5] 呢?
var num = [5, 6, 5, 4, 5, 1, 5];
我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。
[2,3,5].filter(i => ![5].includes(i))
您在数组中有 1 到 9 个, 您想要删除 5 个 。 请使用以下代码 :
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return m !== 5;
});
console.log("new Array, 5 removed", newNumberArray);
如果您想要多个值。例如:- 1,7,8
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return (m !== 1) && (m !== 7) && (m !== 8);
});
console.log("new Array, 1,7 and 8 removed", newNumberArray);
如果您想要删除数组中的数组值。 例如 : [3,4,5]
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];
var newNumberArray = numberArray.filter(m => {
return !removebleArray.includes(m);
});
console.log("new Array, [3,4,5] removed", newNumberArray);
包括支持的浏览器链接链接.
Array.prototype.remove = function(start, end) {
var n = this.slice((end || start) + 1 || this.length);
return this.length = start < 0 ? this.length + start : start,
this.push.apply(this, n)
}
start
和end
可以是负数。在这种情况下,它们会从数组的末尾计数。
如果只有start
中指定,只删除一个元素。
函数返回新数组长度。
z = [0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(2,6);
(8) [0, 1, 7, 8, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(-4,-2);
(7) [0, 1, 2, 3, 4, 5, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(3,-2);
(4) [0, 1, 2, 9]
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']