如何从Javascript数组中选择非连续元素

How to select non-consecutive elements from a Javascript array?

本文关键字:选择 连续 元素 数组 Javascript      更新时间:2023-09-26

如果我有一个数组,选择非连续元素的简单方法是什么?第二个和第五个元素,例如:

a = ["a","b","c","d","e"]
a.select_elements([1,4]) // should be ["b","e"]

编辑

我刚刚意识到我可以做[1,4].map(function(i) {return a[i]})。有没有一种不那么冗长的方法?

如果您正在寻找使代码看起来更短的东西,您可以扩展Array以使用以下方法:

Array.prototype.select_elements = function(indices) {
    var elements = [];
    for (var i=0; i != indices.length; ++i)
        elements.push(this[indices[i]]);
    return elements;
}

现在你可以调用你想要的方法:

a.select_elements([1,4])
["b", "e"]

创建一个新数组,手动使用元素:

var select_elements = [a[1], a[4]];

或者创建一个从索引构建新数组的函数:

function selectElementsWithIndices(sourceArray, selectIndices)
{
    var result = new Array();
    for ( var i = 0; i < selectIndices; i++ ) {
        var index = selectIndices[i];
        result.push(sourceArray[index]);
    }
    return result;
}
var select_elements = selectElementsWithIndices(a, [1, 4]);

您可以安全地(不会出现在循环中)向所有数组添加一个函数:

Object.defineProperty(Array.prototype, 'get', {
    __proto__: null, 
    value: function() {
        return Array.prototype.slice.call(arguments).map(function(index){ return this[index] }.bind(this)); 
    }
})

用法:

a = [1, 2, 3, 4, 5, 6];
a.get(1, 4);

非可变版本:

Object.defineProperty(Array.prototype, 'get', {
    __proto__: null, 
    value: function(indices) {
        return indices.map(function(index){ return this[index] }.bind(this)); 
    }
})

用法:

a = [1, 2, 3, 4, 5, 6];
a.get([1, 4]);

没有任何内置。您可以这样做:

a.select_elements([a[1], a[4]]);

它构造一个新的数组,使用元素a[1]a[4],然后将其传递给a.select_elements函数。