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

时间:2014-08-31 22:12:54

标签: javascript arrays

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

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

修改

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

4 个答案:

答案 0 :(得分:4)

如果您正在寻找能让您的代码看起来更短的东西,您可以扩展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"]

答案 1 :(得分:3)

手动创建一个新数组:

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

答案 2 :(得分:1)

内置任何东西。你可以这样做:

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

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

答案 3 :(得分:1)

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

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