1

I recently came across the following piece of sample code:

function range(upto) {
  var result = [];
  for (var i = 0; i <= upto; i++) {
    result[i] = i;
  }
  return result;
}

and I'm confused as to why:

result[i] = i;

as opposed to:

i = result[i];

Isn't 'i' the variable and 'result[i]' the value?

4

3 回答 3

2

这填充了数组:

result[0] = 0 // sets the first cell of the array to the value 0
result[1] = 1
etc.

这个函数返回

[0, 1, 2, ... upto]

更多关于 JavaScript 中的数组

于 2013-09-07T20:10:38.077 回答
1

result[i] = i;

将 的值赋给 的ii- 个元素result

因此,result[0]变成0result[1]变成1等等。

于 2013-09-07T20:11:08.193 回答
0
  • result[i] = i;表示您正在将值分配给数组i的索引。iresult

  • i = result[i];表示您正在将i-th数组索引的值分配给result变量i

而已。

于 2013-09-07T20:13:13.647 回答