繁体   English   中英

表达式JavaScript的奇怪行为

[英]Weird behavior with expressions JavaScript

有人可以向我解释为什么会这样吗? 如果有人知道这个行为名称,请编辑标题。

使用此代码:

 const arr = ['RIPA'], varB = "RIPB";
let _params;
_params && Array.isArray(_params) ? arr.push(..._params) : 
arr.push(_params);

_params && console.log("I will never appear");
varB && console.log("I will appear");

arr.push(varB);
console.log('array',arr);
console.log("Type of the _params --> ", typeof _params);

输出:

array [ 'RIPA', undefined, 'RIPB' ]
Type of the _params -->  undefined

jsBIN: https ://jsbin.com/bawepasivo/edit js,console
repl.it: https://repl.it/GaHX

如果undefined _params ,如果&&表达式返回第一个false和最后一个_params值,则执行第二个表达式的可能性如何。

 false  && false                  ? never executed       : _params is undefined
_params && Array.isArray(_params) ? arr.push(..._params) : arr.push(_params);

另一种方式:

if (_params && Array.isArray(_params)) { // (false && false) === false
    arr.push(..._params); // it will be never executed
} else {
    arr.push(_params); // _params is undefined
}

你的表达式执行如下:

(_params && Array.isArray(_params)) ? arr.push(..._params) : arr.push(_params);

但你的意思可能就是:

_params && (Array.isArray(_params) ? arr.push(..._params) : arr.push(_params));

你只需要添加括号。

let _params; // undefined

_params && Array.isArray(_params) ? false ,所以被调用的代码是arr.push(_params); ,导致arr.push(undefined);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM