开发者

in Javascript what does - valuesLength = (values.length , undefined); - do?

I am using GWT and the translated javascript has this functionality in several places

valuesLength = (values.length , undefined);

I assumed that it was a set to undefined开发者_开发百科 if object does exist but when debugging in the browser although values object exist and length has a value valuesLength always equals undefined.


Its because the comma operator evaluates its operands left to right and returns the value of rightmost operand.

(values.length , undefined)
               ^^                  // will output undefined

MDN reference (not working right now)

If the objective is to have check for object's existence, the right way to do that is

var valuesLength;
if(values && values.length) {
  valuesLength = values.length;
}
// else valuesLength will be undefined by default


"The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand."

http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

This code would appear to serve no purpose since values.length is only a property. If it were a method, then it could have side effects.

Most people don't use the comma operator because it creates confusing code. I suspect this is just an example of what is essentially a compiler producing weird code because its optimizer isn't perfect.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜