Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - Functional approach to basic array construction

This is my code, acting upon myArray:

var myArray = [];
var i;

for(i = 0; i < 20; i += 1) {
   myArray.push(Math.random());
}

Is there a functional equivalent of the above that does without the dummy variable i?

Favorite answers:

  • while(myArray.push(Math.random()) < 20);
  • $.map(Array(20), Math.random);
  • for(var myArray = []; myArray.push(Math.random()) < 20;);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not in ES5, there's no real functional equivalent to it, as you have to have something which has an amount of 20 to apply map to...

var my20ElementArray = [0,1,2,3,4,5,6,7,8,9,10];
var myArray = my20ElementArray.map(Math.random);

You could create an xrange-like function what is in Python but that would just hide this "unused" variable inside a function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...