JavaScript “new Array(n)” and “Array.prototype.map” weirdness

后端 未结 14 2067
粉色の甜心
粉色の甜心 2020-11-22 02:40

I\'ve observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2

When I fire up Firebug:

14条回答
  •  离开以前
    2020-11-22 03:17

    Here's a simple utility method as a workaround:

    Simple mapFor

    function mapFor(toExclusive, callback) {
        callback = callback || function(){};
        var arr = [];
        for (var i = 0; i < toExclusive; i++) {
            arr.push(callback(i));
        }
        return arr;
    };
    
    var arr = mapFor(3, function(i){ return i; });
    console.log(arr); // [0, 1, 2]
    arr = mapFor(3);
    console.log(arr); // [undefined, undefined, undefined]

    Complete Example

    Here's a more complete example (with sanity checks) which also allows specifying an optional starting index:

    function mapFor() {
    var from, toExclusive, callback;
    if (arguments.length == 3) {
        from = arguments[0];
        toExclusive = arguments[1];
        callback = arguments[2];
    } else if (arguments.length == 2) {
        if (typeof arguments[1] === 'function') {
            from = 0;
            toExclusive = arguments[0];
            callback = arguments[1];
        } else {
            from = arguments[0];
            toExclusive = arguments[1];
        }
    } else if (arguments.length == 1) {
        from = 0;
        toExclusive = arguments[0];
    }
    
    callback = callback || function () {};
    
    var arr = [];
    for (; from < toExclusive; from++) {
        arr.push(callback(from));
    }
    return arr;
    }
    
    var arr = mapFor(1, 3, function (i) { return i; });
    console.log(arr); // [1, 2]
    arr = mapFor(1, 3);
    console.log(arr); // [undefined, undefined]
    arr = mapFor(3);
    console.log(arr); // [undefined, undefined, undefined]

    Counting Down

    Manipulating the index passed to the callback allows counting backwards:

    var count = 3;
    var arr = arrayUtil.mapFor(count, function (i) {
        return count - 1 - i;
    });
    // arr = [2, 1, 0]
    

提交回复
热议问题