admin管理员组文章数量:1333201
In JavaScript (x, x1, x2, …, xn)
always returns xn
.
In Python this code is called tuple and it returns different values.
My question is what is the purpose of this code in JavaScript? Do you have some practical example?
In JavaScript (x, x1, x2, …, xn)
always returns xn
.
In Python this code is called tuple and it returns different values.
My question is what is the purpose of this code in JavaScript? Do you have some practical example?
Share Improve this question edited Sep 9, 2015 at 7:49 vaultah 46.6k12 gold badges119 silver badges144 bronze badges asked Aug 3, 2011 at 14:00 antonjsantonjs 14.3k15 gold badges69 silver badges91 bronze badges3 Answers
Reset to default 10The ma operator evaluates every operand but only returns the result of the last evaluation. It can be used to initialize multiple variable in a for loop.
var str = "Hello, World!";
for(var i = 0, len = str.length; i < len; i++)
console.log(str.charAt(i));
Edit: As pointed out in the ments, this isn't a true example of the ma operator, this is just the var
. You can see this page for actual examples.
http://en.wikipedia/wiki/Comma_operator
Like in C and C++, the ma operator evaluates both the left and right operands, returning the right operand. In terms of practical uses, a, b
can be used in place of a ? b : b
, as well as used as a limited way to fit multiple 'statements' into one statement, such as in the first or third parts of a for
loop.
Note that declaring and/or defining multiple variables with var
, separated by mas, is not a use of the ma operator, even though it uses the ma symbol. The ma operator evaluates to and forms an expression, which can be used as a value as part of a larger expression or statement. var
is a plete statement type that takes the form
var name1 [= value1][, name2 [= value2][, ...]];
The MDC docs has a good example of a practical use for the ma operator:
If a is a 2-dimensional array with 10 elements on a side, the following code uses the ma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:
for (var i = 0, j = 9; i <= 9; i++, j--)
document.writeln("a[" + i + "][" + j + "] = " + a[i][j]);
本文标签:
版权声明:本文标题:The purpose of the comma operator in JavaScript (x, x1, x2, …, xn) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740932717a2309993.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论