如果每个案例执行多个操作,我可以使用三元运算符吗?
例如,我可以在这里使用它吗?:
if (dwelling) {
dwelling = dwelling[0].nodeValue; //first operation
letterDwelling = dwelling[0].toUpperCase(); //second operation
} else {
dwelling = "";
letterDwelling = "";
}
我只使用了这种允许后续操作的语法:
dwelling = dwelling ? dwelling[0].nodeValue : "";
答案 0 :(得分:2)
为避免使用逗号表示法产生副作用,您可以使用自动调用函数代替可以处理代码的函数:
(foo == bar) ? doSomething() : (function(){
// here you can write all your code
// and even return something useful
})();
答案 1 :(得分:1)
虽然为了可读性和可扩展性,我强烈反对它,但你可以:
dwelling ? (dwelling = dwelling[0].nodeValue, letterDwelling=dwelling[0].toUpperCase()) : (dwelling = letterDwelling = "");
答案 2 :(得分:0)
是的,请参阅:Conditional (ternary) Operator
var dwelling = true;
(dwelling) ? (
dwelling = 'a', //first operation
letterDwelling = 'a' //second operation
) : (
dwelling = 'b',
letterDwelling = 'b'
);
alert(dwelling);