Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1245
花落未央
花落未央 2020-11-22 05:58

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

30条回答
  •  太阳男子
    2020-11-22 06:20

    This concat version is much faster in my tests on Chrome (2013-03-21). About 200ms for 10,000,000 elements vs 675 for straight init.

    function filledArray(len, value) {
        if (len <= 0) return [];
        var result = [value];
        while (result.length < len/2) {
            result = result.concat(result);
        }
        return result.concat(result.slice(0, len-result.length));
    }
    

    Bonus: if you want to fill your array with Strings, this is a concise way to do it (not quite as fast as concat though):

    function filledArrayString(len, value) {
        return new Array(len+1).join(value).split('');
    }
    

提交回复
热议问题