<分区>
var a =(3,4,7);
console.log(a); // Output is 7
您能否解释一下我们如何获得输出 7?
标签 javascript
<分区>
var a =(3,4,7);
console.log(a); // Output is 7
您能否解释一下我们如何获得输出 7?
最佳答案
它叫做逗号运算符。通过将右边的表达式括在括号中,我们创建了一个组,并对它的每个操作数求值并返回最后一个值。
来自 MDN
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
逗号运算符在您想要编写缩小器并需要缩小代码时很有用。
例如,
print = () => console.log('add')
add_proc = (a,b) => a + b
function add(a, b){
if(a && b){
print();
return add_proc(a,b)
}
else
{
return 0
}
}
console.log(add(1,2));
可以使用 comma operator
缩小,如下所示:
print = () => console.log('add')
add_proc = (a,b) => a + b
add = (a, b)=> a && b ?(print(),add_proc(a, b)):0
console.log(add(1,2));
关于JavaScript 变量 : var a =(3, 4,7);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50287304/