Filling an array by 1~100 without loop in javascript -
i investigating question raised in interview. interviewer ask piece of code fill array 1~100 without traditional loop. of course, couldn't tell him need type 1~100 in code "[1,2,3,4...100]".
i have thought several solutions, 1 of them successes. using mozilla firefox 46.0.1 & firebug.
solution 1(failed)
var filled = new array(100); filled.map(function(val, index){ return index+1; }); // array size 100 , filled undefined not int console.info(filled);
solution 2(failed)
var filled = new array(100); // seems can't go callback function filled.foreach(function(val, index){ val = index+1; }); // it's same solution 1 console.info(filled);
solution 3(failed)
var filled = []; // guess root cause array doesn't initialized. // if insert value index 99, previous 99 values automatically filled undefined. filled[99] = 100; filled.map(function(val, index){ // 100:99 can printed console.info(val + ":" + index); return index+1; }); // array full undefined besides last value. console.info(filled);
solution 4(successed) search stackoverflow , find solution.
var filled = array.apply(null, array(100)) .map(function(val, index) { return index+1; }); console.info(filled);
investigation of solution 4 try change in solution 4 , find truth.
// break chain , doesn't work. it's strange. var filled = array.apply(null, new array(100)); filled.map(function(val, index) { return index+1; }); console.info(filled);
// in opinion, array.apply(null, array(100)) = this.array(undefined, undefined,...,undefined); // so, start test // works var filled = this.array(undefined, undefined, undefined).map(function(val, index) { return index+1; }); console.info(filled); // doesn't work var filled = this.array(undefined, undefined, undefined); filled.map(function(val, index) { return index+1; }); console.info(filled);
according above investigation, firmly trust chain coding key point. so, following code still failed.
var filled = new array(100).map(function(val, index) { return index+1; }); console.info(filled);
i confused situation, please explain it? thank help.
you can make new array defined length , apply array#map
it.
the
map()
method creates new array results of calling provided function on every element in array. [emphasis ns]
most of tries, forgot assign map result.
var filled = array.apply(null, { length: 100 }).map(function (_, i) { return + 1; }); document.write('<pre>' + json.stringify(filled, 0, 4) + '</pre>');
Comments
Post a Comment