开发者

Is it possible to make this code shorter?

I have javascript code:

var newPositions = new Array(count);
                for (var i = 0; i < count; i++) {
                    newPositions[i] = i;
                }

Is it possible to init this array from 0 to count more quickly(in one-line I mean)?

upd: count is a number that may differ in execution time

upd2: dont think about algorithm, only way to write this code in one-line. As @Martin Jespersen suggest and using somebody deleted answer:

for (var i = 0, newPositions = []; i < count; newP开发者_JS百科ositions[i] = i++) 


for (var i = 0,newPositions=[]; i < count; i++) {
  newPositions[i] = i;
}


No, there is not a way to optimize that any more :)


That's about as 'easy' as it gets to do what you want; the only potential optimisation is to turn the array initialisation into a function, like so:

function range(count) {
    var countArray = new Array(count);
    for(var i = 0; i < count; i++) {
        countArray[i] = i;
    }
    return countArray;
}

Then assign it to your variable:

var newPositions = range(count);

Only an optimisation if you needed to do that a reasonable number of times, to account for the additional time spent coding the function. If it's being done once then it's about as good as it's going to get.

As a sort of aside, the code you have initialises newPositions from 0 to count-1, rather than 0 to count, due to the way your for loop is set up. Change i < count to i <= count in your for loop if you want to include the value of count in your array.


If count is always a known number, then the syntax for creating a javascript array in 1 line is

var myArray = [0,1,2,3,4,5,6,7]; //assuming count was 8


The smart-ass answer would be:

for (var i = 0; i < count; i++) newPositions[i] = i;

But a better answer (or question) would be: Why is this array useful to you at all? The array is holding values that can be easily calculated on the fly. With more information we can give you a better answer.


Not much easier i'm afraid unless you alwasy use the same count as in Jamiec's answer.

var newPositions = [];
while(count-- > 0)
     newPositions[count] = count;

This is a little shorter but the same code except it changes cout so maybe use a temp var fpor that instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜