开发者

JavaScript setting variables?

Can someone explain the second line of this function? is it setting two variables to = 0 at one time? i.e. var i = 0 and var res = 0? If so, is it necessary to set 开发者_开发技巧var i = 0 considering that it does that in for(i = 0 ... etc

function sumOnSteroids () {
    var i, res = 0;
    var number_of_params = arguments.length;
    for (i = o; i < number_of_params; i++) {
        res += arguments[i];
    }
    return res;
}


No, the value of i will be undefined, the initializer only applies to "res" in that case. To assign the value you'd need:

var i = 0,
    res = 0;


It is setting two variables at once with the var keyword being applied to both, scoping them. Without the var, they would be properties of window (essentially globals).

The first one (i) would be undefined and the second one (res) would be 0.

This is a powerful pattern because...

  • var should be implicit, but it is not, so we only have to repeat it once.
  • Less typing for you.
  • Better for minifying (smaller file size).
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜