如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
使用 indexof, 可以用 spolice 从数组中找到一个特定的数字索引, 从数组中删除一个特定的索引 。
const 数组 = [1,2,3,4,5,6,6,7,7,8,9,0]; const 指数 = 数组.indexof(5); /// 找到具体数字的索引 if( index != -1) { 数组.splice( index, 1); // 使用 index world. log( 数组) 删除数字 ;
删除全部事件 。 @ info: whatsthis
数组数组 = [1、2、3、4、4、5、1、7、8、9、9、2、3、4、5、6] 数组 = 数组. filter( number_@ number!=5); 控制台. log( 数组) ;
使用 join 和 share let 数组 = [1、2、3、4、5、1、7、8、9、2、3、4、5、6] 数组 = 数组 。 来自 (array.join ("-" -").split ("-5 -").join (" -").split ("-").split ("-"), number) 控制台.log (ray) 的 数组 。
其他回答
我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。
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();
}
您可以使用 lodash _. pull( 调和数组)、 _. pullAt( 调和数组) 或 _. 。 (不变换数组)
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
创建新阵列 :
var my_array = new Array();
添加元素到此数组 :
my_array.push("element1");
函数索引of (返回指数或 -1 未找到时) :
var indexOf = function(needle)
{
if (typeof Array.prototype.indexOf === 'function') // Newer browsers
{
indexOf = Array.prototype.indexOf;
}
else // Older browsers
{
indexOf = function(needle)
{
var index = -1;
for (var i = 0; i < this.length; i++)
{
if (this[i] === needle)
{
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
检查此元素的索引( 使用 Firefox 和 Internet Explorer 8 (及以后) 测试) :
var index = indexOf.call(my_array, "element1");
从数组中删除位于索引处的 1 元素
my_array.splice(index, 1);
使用数组过滤法 :
let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)
咖啡:
my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value