如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
你的问题没有说明顺序或不同的价值是否是一项要求。
如果您不关心顺序, 并且容器中的值不会超过一次, 请使用“ Set ” 。 它会更快, 更简洁 。
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
其他回答
答案已经很多了, 但是因为还没有人用一个衬里来做, 我想我会展示我的方法。 它会利用字符串. split () 函数在创建数组时将删除所有指定字符这一事实。 这里举一个例子 :
var ary = [1、2、3、4、1234、10、4、5、7、3]; out = arry.join (" -" -").split ("-4 -").join (" -").split (" -").split (" -");control.log(out) ;
在此示例中, 所有 4 个的字符都在从数组中移除 。 但是, 必须指出, 包含字符“ - ” 的任何数组都会与此示例产生问题 。 简而言之, 这会导致组合( “ - ” ) 函数不适当地将您的字符串拼凑在一起。 在这种情况下, 上面的扇形中的所有“ - ” 字符串都可以替换为在原始数组中不会使用的任何字符串 。 以下还有一个示例 :
var ary = [1,2,3,4,'-',1234,10,'-',4,5,7,3]; out = ary.join("!@#").split("!@#4!@#").join("!@#").split("!@#"); console.log(out);
创建新阵列 :
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);
ES6且无突变:(2016年10月)
const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ]; output = removeByIndex([33,22,11,44],1) //=> [33,11,44] console.log(output)
如果您必须支持旧版的 Internet Explorer , 我建议使用以下多个填充( 注意: 这不是一个框架 ) 。 这是所有现代阵列方法( JavaScript 1. 8. 5/ ECMAScript 5 Array Extras) 的100%的后向兼容替换, 用于 Internet Explorer 6+, Firefox 1. 5+, Chrome, Safari, & Opera 。
https://github.com/pludude/array-generics https://github.com/pludude/ array-generics https://github.com/plusdude/arary-generics/servics/
我找到了这个博客文章,
9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列
我更喜欢使用过滤器 () :
var filtered_arr = arr.filter(function(ele){
return ele != value;
})