Javascript Ruby的类似地图的方法

时间:2015-03-26 11:37:22

标签: javascript arrays

JavaScript中是否有Ruby类似地图的语法?例如在Ruby我可以写:

res = [[1,2,3],[4,5,6],[7,8,9]]
res = res.map { |x| x[1..2] } 
# res == [[2, 3], [5, 6], [8, 9]]

是否有任何功能在JavaScript中有效?

2 个答案:

答案 0 :(得分:3)

你可以查看Underscore.js Map帮助函数(还有MapObject帮助器,类似于map,但可以使用对象): http://underscorejs.org/#map

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
_.map([[1, 2], [3, 4]], _.first);
=> [1, 3]

如果失败,您可以尝试ES6地图对象:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var kvArray = [["key1", "value1"], ["key2", "value2"]];

// Use the regular Map constructor to transform a 2D key-value Array into a map
var myMap = new Map(kvArray);

myMap.get("key1"); // returns "value1"

// Use the spread operator to transform a map into a 2D key-value Array.
alert(uneval([...myMap])); // Will show you exactly the same Array as kvArray

// Or use the spread operator on the keys or values iterator to get 
// an array of only the keys or values
alert(uneval([...myMap.keys()])); // Will show ["key1", "key2"]

如果你决定使用ES6,你还需要一个像Babel这样的转发器。

希望有所帮助。

答案 1 :(得分:2)

您可以使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

对于不支持Array map方法的浏览器,这里有另一种实现方式:

if (!Array.prototype.map) {
    Array.prototype.map = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var res = new Array(len);
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                res[i] = fun.call(thisp, this[i], i, this);
            }
        }

        return res;
    };
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill

相关问题