简体   繁体   English

按索引删除数组元素

[英]Remove array elements by index

I seem to be having a brain-freeze and am unable to remove JS array elements by index. 我似乎有一个大脑冻结,我无法通过索引删除JS数组元素。 Is there something fundamentally idiotic in the below? 下面有什么根本愚蠢的东西吗?

var els;
[0, 1, 3]
0: 0
1: 1
2: 3


["Colour", "Font", "Icon", "Line 1"]
0: "Colour"
1: "Font"
2: "Icon"
3: "Text"

All I want to do is remove the elements from the array using index positions 0, 1 and 3 (in this example) - however, when I try this using splice, it messes up the indexes. 我想要做的就是使用索引位置0,1和3(在此示例中)从数组中删除元素 - 但是,当我使用splice尝试此操作时,它会混乱索引。

See: 看到:

els.each(function(key, val) {
            console.log(key);
            req-fields.splice(key,1);
        });

Try something like this 尝试这样的事情

function removeIndex(array, index) {
    delete array[index];
    array = array.filter(function(element) {
        return element != undefined
    });
    return array;
}

Example

removeIndex([1,4,7,13,41,16],3);
=> [1,4,7,41,16]

Explanation 说明

To delete an element from an array, you use the delete keyword. 要从数组中删除元素,请使用delete关键字。 This will make the value at that index undefined . 这将使该索引处的值undefined You then need to filter the array, and remove undefined elements. 然后,您需要过滤数组,并删除未定义的元素。

You can adjust the index of the splice for every splicing action. 您可以为每个拼接操作调整拼接的索引。

 var fields = ["Colour", "Font", "Icon", "Line 1"], els = [0, 1, 3]; els.forEach(function (val, i) { fields.splice(val - i, 1); }); document.write('<pre>' + JSON.stringify(fields, 0, 4) + '</pre>'); 

The issue is when you remove element 0, the array gets shifted down by 1 and your other elements are in the wrong positions. 问题是当你删除元素0时,数组向下移动1并且你的其他元素位于错误的位置。 One way to solve this would be to sort your input els array in descending order so it will pop element 3, then 1, then 0. 解决此问题的一种方法是按降序对输入els数组进行排序,使其弹出元素3,然后是1,然后是0。

els.sort(function(a, b){return b-a});

els.each(function(key, val) {
        console.log(key);
        req-fields.splice(key,1);
    });

Variation on Richard Hamilton's. 理查德汉密尔顿的变化。 Note that both of ours will return a new array, not actually modify the original array object. 请注意,我们两个都将返回一个数组,而不是实际修改原始数组对象。

function removeIndexes(array, indexes) {
    return array.filter(function(element, i) {
        return indexes.indexOf(i) === -1;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM