有人能解释一下为什么会出现这种情况吗?如果有人知道这种行为的名字,请编辑标题。
使用以下代码:
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
如果_params
是undefined
,当&&
表达式返回第一个为假的值和最后一个真实值时,执行第二个表达式的可能性有多大。
arr.push(_params)
pushedundefined
inarr
- Mistalis_params && Array.isArray(_params)
求值为false
,所以会调用arr.push(_params);
,从而将undefined
推入arr
中。 - user247702