如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
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) );
其他回答
您可以使用复数来从数组中删除对象或值。
让我们考虑一个长度为5的行距, 值为10,20,30,40,50, 我想从中去掉30的值。
var 数组 = [10,20,30,40,50];如果 (数组. indexof(30) > -1) {数组.spice( 数组. indexof(30), 1);} 控制台. log( 数组); / / [10,20, 40,50]
我对基底 JavaScript 阵列进行了相当高效的扩展:
Array.prototype.drop = function(k) {
var valueIndex = this.indexOf(k);
while(valueIndex > -1) {
this.removeAt(valueIndex);
valueIndex = this.indexOf(k);
}
};
通过我的解决方案, 您可以在纯 JavaScript 的阵列中删除一个或多个项。 不需要另外的 JavaScript 库 。
var myArray = [1,2,3,4,5]; // First array
var removeItem = function(array,value) { // My clear function
if(Array.isArray(value)) { // For multi remove
for(var i = array.length - 1; i >= 0; i--) {
for(var j = value.length - 1; j >= 0; j--) {
if(array[i] === value[j]) {
array.splice(i, 1);
};
}
}
}
else { // For single remove
for(var i = array.length - 1; i >= 0; i--) {
if(array[i] === value) {
array.splice(i, 1);
}
}
}
}
removeItem(myArray,[1,4]); // myArray will be [2,3,5]
这提供了一个前提值, 而不是一个值 。
注:它将更新给定阵列,并返回受影响的行。
用法
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义定义的定义
var helper = {
// Remove and return the first occurrence
remove: function(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array.splice(i, 1);
}
}
},
// Remove and return all occurrences
removeAll: function(array, predicate) {
var removed = [];
for (var i = 0; i < array.length; ) {
if (predicate(array[i])) {
removed.push(array.splice(i, 1));
continue;
}
i++;
}
return removed;
},
};
创建新阵列 :
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);