【问题标题】:Javascript Zipped Arrays Automatically Indexed or NamedJavascript 压缩数组自动索引或命名
【发布时间】:2014-08-15 15:52:02
【问题描述】:

如何压缩两个或多个数组,然后按名称而不是索引遍历每个元素?在 Python 中,您可以这样做:

for A, B in zip(As, Bs):

但是,在 Javascript 中,我使用的是这样的:

var As = [1,2,3];
var Bs = [4,5,6];
_(As)
.zip(Bs)
.map(function(x) { 
    return {A:x[0], B:x[1]}; // I want x[0] and x[1] mapped to names.
})
.map(function(x) {
    // Now I can use x.A and x.B.
    ...

在 Javascript 中有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript functional-programming underscore.js lodash


    【解决方案1】:

    您可以使用_.object 将数组转换为对象:

    _(zipped).map(function(values) {
        return _.object(['a', 'b'], values);
    });
    

    http://jsfiddle.net/1quhesmq/

    如果您愿意,也可以使用部分应用函数

    _(zipped).map(_.partial(_.object, ['a', 'b']));
    

    http://jsfiddle.net/1quhesmq/6/


    您还可以扩展 Underscore 以概括此行为,例如:

    _.mixin({
      namedzip: function() {
        var zipped = _.zip.apply(null, _.initial(arguments, 1)),
            list = _.last(arguments);
    
        return _(zipped).map(function(values) {
            return _.object(list, values);
        });      
      }
    });
    

    你会打电话给

    _(As).namedzip(Bs, ['a', 'b']);
    

    http://jsfiddle.net/1quhesmq/5/

    【讨论】:

    • 您的第一个示例并不比我所做的更简洁,尽管它确实摆脱了索引。让我考虑扩展选项...
    • 我要感谢你的问题。这就是我最终实现的:_.mixin({nameElements:function() { var list = _.first(arguments); var names = _.rest(arguments); return _(list).map(function(x) { return _.object(names, x); }); }});
    猜你喜欢
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2013-05-19
    • 2022-01-13
    • 2011-09-05
    相关资源
    最近更新 更多