如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
创建新阵列 :
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);
其他回答
很简单,只要做:
var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];
使用 jQuery 的阵列 :
A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`
注意: 如果元素未找到, 在阵列中返回 - 1 。
更现代的ECMAScript 2015(原称和谐或ES6)方法。
const items = [1, 2, 3, 4];
const index = 2;
然后:
items.filter((x, i) => i !== index);
弹出 :
[1, 2, 4]
您可以使用 Babel 和多填充服务,以确保浏览器之间有很好的支持。
我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。
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();
}
删除上次发生或所有发生, 还是第一次发生 ?
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Remove this line to remove all occurrences
}
}
或
var array = [2, 5, 9, 5];
// Remove first occurrence
for (var i = 0; array.length; i++) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Do not remove this line
}
}