~Onlooker 2011-04-23 22:17 采纳率: 0%
浏览 1010
已采纳

如何在 JavaScript 中从数组中移除特定的元素?

I have an array of integers, and I'm using the .push() method to add elements to it.

Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);.

I have to use core JavaScript - no frameworks are allowed.

转载于:https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript

  • 写回答

30条回答 默认 最新

  • larry*wei 2011-04-23 22:23
    关注

    Find the index of the array element you want to remove, then remove that index with splice.

    The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

    var array = [2, 5, 9];
    console.log(array)
    var index = array.indexOf(5);
    if (index > -1) {
      array.splice(index, 1);
    }
    // array = [2, 9]
    console.log(array);

    The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


    Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8.

    If you need indexOf in an unsupported browser, try the following polyfill. Find more info about this polyfill here.

    Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
        var a;
        if (null == this) throw new TypeError('"this" is null or not defined');
        var c = Object(this),
            b = c.length >>> 0;
        if (0 === b) return -1;
        a = +e || 0;
        Infinity === Math.abs(a) && (a = 0);
        if (a >= b) return -1;
        for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
            if (a in c && c[a] === d) return a;
            a++
        }
        return -1
    });
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog