如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
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;
此解决方案将需要一系列输入, 并将通过输入查找要删除的值。 这将在整个输入数组中循环, 结果将是第二个已经删除了特定索引的数组整数组。 然后将整数组复制到输入数组中 。
其他回答
非就地解决办法
arr.slice(0,i).concat(arr.slice(i+1));
arr = [10, 20, 30, 40, 50] (i) = 2;// 位置删除(从0开始) ; r = ar. selice (0, i). concat (arr. slice (i+1)); 控制台.log(r);
我建议删除一个使用删除和过滤的阵列项目:
var arr = [1,2,3,4,5,5,5,6,7,8,9];删除ar[5];rr = arr.filter(职能(项目){返回项目!=未定义;});//结果:[1、2,3,4,5,6,6,7,7,8,9];删除ar[5];ar = arr.filter(职能(项目){返回项目);//结果:[1、2,3,4,6,6,6,7,7,8,9] 控制台。
因此,我们只能删除一个特定的数组项目,而不是所有具有相同价值的项目。
使用数组过滤法 :
let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)
function array_remove(arr, index) {
for (let i = index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr.length -= 1;
return arr;
}
my_arr = ['A', 'B', 'C', 'D'];
console.log(array_remove(my_arr, 0));
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
Array. prototype. removeTrounds = 函数( array, val) { { 数组. (raryTrounds, index) {如果 (rayTroups = val) { 数组. splice( index, 1);} 返回数组;} var DummyAray = [1、2、 3、4、 5、 6]; 控制台.log (DummyArray. removeTround (DummyArray, 3) );