如何从数组中删除一个特定值? 类似 :

array.remove(value);

我必须使用核心核心核心JavaScript。 不允许框架 。


当前回答

有许多方法可以删除指定元素从 JavaScript 阵列中得出的。 以下是我研究中可以想到的五种最佳方法。

1. 直接使用“ splice () ” 方法

在以下代码段,从数组中删除特定预定位置的元素。

  • 语法 :数组_ name. spice( begin_ index, 数字_ elements_ remove ) ; 数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组数组, remove;
  • 应用程序 :

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log("Original array: " + arr);

var removed = arr.splice(4, 2);

console.log("Modified array: " + arr);

console.log("Elements removed: " + removed);

2. 使用“ splice() () ” 方法用“ valice () ” 方法用“ value () ” 删除元素

在以下代码段的以下代码段中,如果条件在用于循环。

var arr = [1, 2, 6, 3, 2, 6, 7, 8, 9, 10];

console.log("Original array: " + arr);

for (var i = 0; i < arr.length; i++) {

  if (arr[i] === 6) {

    var removed = arr.splice(i, 1);
    i--;
  }

}

console.log("Modified array: " + arr); // 6 is removed
console.log("Removed elements: " + removed);

3. 使用“过滤器()”方法删除按值选择的元素

与使用“ spice() () ” 方法的执行类似, 但它没有改变现有的数组, 而是创造了新的元素阵列, 从而删除了不想要的元素 。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var filtered = array.filter(function(value, index, arr) {
  return value != 6 ;
});

console.log("Original array: "+array);

console.log("New array created: "+filtered); // 6 is removed

4. 在“ Lodash” JavaScript 库中使用“ remove () ” 方法

在下面的代码段中, JavaScript 库里有叫作“ Lodash ” 的删除() 方法。 这个方法也与过滤方法相似 。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + array);

var removeElement = _.remove(array, function(n) {
  return n === 6;
});

console.log("Modified array: " + array);
console.log("Removed elements: " + removeElement); // 6 is removed
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

5. 制作自定义除去方法

JavaScript没有本地的“ array. remove” 方法, 但我们可以创建一种使用以上方法的方法, 用于在以下代码片段中执行 。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function arrayRemove(arr, value) {

  return arr.filter(function(element) {
    return element != value;
  });
}

console.log("Original array: " + array);
console.log("Modified array: " + arrayRemove(array, 6)); // 6 is removed

最后方法(第5项)更适合解决上述问题。

其他回答

更现代一点ECMAScript 2015(原称和谐或ES6)方法。

const items = [1, 2, 3, 4];
const index = 2;

然后:

items.filter((x, i) => i !== index);

弹出 :

[1, 2, 4]

您可以使用贝贝以及 a 和 a多元填充服务以确保在浏览器之间得到很好的支持。

如果元素存在多个实例,您可以进行后回循环,以确保不破坏索引。

var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];

/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
  if (myArray[i] == myElement) myArray.splice(i, 1);
}
console.log(myArray);

根据索引删除

函数返回在索引中没有元素的数组副本 :

/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
      return array.filter(function(elem, _index){
          return index != _index;
    });
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));

$> [ 1, 4, 5, 6, 7 ]

以值删除

函数返回没有值的数组副本。

/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
      return array.filter(function(elem, _index){
          return value != elem;
    });
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));

$> [ 1, 3, 4, 6, 7]

创建新阵列 :

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);

Vanilla JavaScript(ES5.1) - (ES5.1) -已经到位版本版本

浏览器支持 :因特网探索者 9或以后(或以后(详细浏览器支持)

/**
 * Removes all occurences of the item from the array.
 *
 * Modifies the array “in place”, i.e. the array passed as an argument
 * is modified as opposed to creating a new array. Also returns the modified
 * array for your convenience.
 */
function removeInPlace(array, item) {
    var foundIndex, fromIndex;

    // Look for the item (the item can have multiple indices)
    fromIndex = array.length - 1;
    foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item (in place)
        array.splice(foundIndex, 1);

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex);
    }

    // Return the modified array
    return array;
}

Vanilla JavaScript(ES5.1) - (ES5.1) -不可变版本版本

浏览器支持: 与原版的香草 JavaScript 相同

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    var arrayCopy;

    arrayCopy = array.slice();

    return removeInPlace(arrayCopy, item);
}

香草ES6 -不可变版本版本

浏览器支持: Chrome 46, 边缘 12, Firefox 16, Opera 37, Safari 8 ()详细浏览器支持)

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    // Copy the array
    array = [...array];

    // Look for the item (the item can have multiple indices)
    let fromIndex = array.length - 1;
    let foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item by generating a new array without it
        array = [
            ...array.slice(0, foundIndex),
            ...array.slice(foundIndex + 1),
        ];

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex)
    }

    // Return the new array
    return array;
}