开发者

For jQuery purist - simple array filling?

  • What is the best way to do loops in JavaScript
    • http://blogs.oracle.com/greimer/entry/best_way_to_code_a
    • http://api.jquery.com/jQuery.each/
    • http://api.jquery.com/each/

I still for my own education want to see an elegant jQuery version of a construct like this - Note th开发者_StackOverflow中文版e image filenames are 1 based and not 0 based :

var nofImages = 10; // user defined
var slideShowArray = new Array(nofImages); // cannot use [nofImages] of course
for (var i=0, n=slideShowArray.length;i<n;i++) {
  slideShowArray[i]="/images/image"+(i+1)+".jpg";
}

or perhaps according to the above mentioned articles it should be

var nofImages = 10; // user defined
var slideShowArray = [];
for (i=nofImages;i>0;i--) {
  slideShowArray[(i-1)]="/images/image"+i+".jpg";
}

Thanks


var slideShowArray = $.map(new Array(10), function(i,j) {
    return '/images/image'+(j+1)+'.jpg';
});

In Javascript 1.8 you will be able to do this more elegantly:

var slideShowArray = $.map(new Array(10), function(i,j) '/images/image'+(j+1)+'.jpg');

or even

$.range = function(first,last,step) {
    step = step || 1;
    if (typeof last == undefined) {
        last = first;
        first = 0;
    }
    return $.map(Array((first-last)/step), function(i,j) {
        return j*step + first;
    });
}

var slideShowArray = ['/images/image'+i+'.jpg' for (i in $.range(1,10))];


Trying to be a jquery purist you might want to try the .map() method.

var noOfImages = 10;
var slideShowArray = [];
slideShowArray[noOfImages - 1] = ""; // set initial size
slideShowArray = $.map(slideShowArray, function(element, index) {
  return "/images/image"+index+".jpg"
});

But I think this would be simpler:

var noOfImages = 10;
var slideShowArray = [];
for(var i = 0; i < noOfImages; i++) 
  slideShowArray.push("/images/image"+i+".jpg");

(Note that your examples are a bit broken - setting the array to [noOfImages] sets the length to 1.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜