在JavaScript的数组中删除特定元素? [英] Remove a particular element from an array in JavaScript?

查看:173
本文介绍了在JavaScript的数组中删除特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数,我使用了 .push()方法添加到阵列。

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

有一个简单的方法来从一个数组中移除特定的元素?东西等效像 array.remove(INT);

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

我要使用的核心的JavaScript的 - 的没有的框架允许

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

推荐答案

首先,找到首页元素的要删除:

First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(5);

注:对indexOf 浏览器的支持是有限的的;它不是在Internet&NBSP支持; Explorer 7和8

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

然后用<一个删除href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\"><$c$c>splice:

if (index > -1) {
    array.splice(index, 1);
}

的第二个参数拼接是元素去除的数量。需要注意的是拼接修改数组到位,并返回一个包含已被删除的元素的数组。

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.

如果您在不受支持的浏览器需要的indexOf ,请尝试以下填充工具。有关这方面的更多信息<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill\"><$c$c>polyfill这里

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

这篇关于在JavaScript的数组中删除特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆