[js] && || 与 或
&&后执行函数
function test() {
console.log('func')
}
//数组 && 函数
[] && test();//func
[1, 2, 3] && test();//func
//对象 && 函数
//对象必须用括号包裹
//{ }&&test();//error
({}) && test();//func
//{ a: 'a', b:'b' }&&test();//error
({ a: 'a', b: 'b' }) && test();//func
//布尔 && 函数
true && test();//func
false && test();//不执行
//字符串 && 函数
'' && test();//不执行
'abc' && test();//func
'null' && test();//func
'undefined' && test();//func
//数字 && 函数
0 && test();//不执行
1 && test();//func
2 && test();//func
-1 && test();//func
'0' && test();//func
NaN && test();//不执行
//其他 && 函数
null && test();//不执行
undefined && test();//不执行
!false && test();//func
//函数 && 函数
function falseFunc() {
return false;
}
function trueFunc() {
return true;
}
function empty() {
console.log('empty')
}
//是否执行主要看返回值,规则与上面一样,只是对象不需要被()包裹。
falseFunc() && test();//不执行
trueFunc() && test();//func
empty() && test();//没有返回值也不会执行&&后的函数
trueFunc && test();//func 单纯有该函数也可以执行&&后的函数
//变量 && 函数
//是否执行主要看变量值,规则与上面一样,只是对象不需要被()包裹。
let str;
str && test();//不执行
&&后面赋值
括号大法好
//变量
//true && let a= 'a';//error
//true && (let a= 'a');//error
let a;
//true && a= 'a';//error
true && (a = 'a');//a
//true && a = function() { };//error
true && (a = function () { });//function
console.log(a)
//数组
let arr = [];
//true && arr[0]=2;//error
true && (arr[0] = 2);//[2]
true && arr.push(2);//[2]
console.log(arr);
//对象
let obj = {};
//true && obj.a='a';//error
//true && obj['b']='b';//error
//true && (obj.a.b = 'ab');//error
true && obj.a && (obj.a.b = 'ab');//不执行
true && (obj.a = 'a');//a
true && (obj['b'] = 'b');//b
console.log(obj);
//true && this.g='g';//error
true && (this.g = 'g');//g
console.log(this.g);
||
let a;
a = '' || 'a';//a
a = 0 || 1;//1
a = false || true;//true
let b = function () { return true };
let c = function () { return false };
a = c || b;//function c()
a = c() || b();//true
console.log(a)
// ||可认为是设置默认值
//let d = this.e.xx;//error
let d = (this.e || {}).xx;//undefined
d = '' || {};//{}
console.log(d)
用 && 和 || 代替 if else
主要应用场景还是可以替换一些三元运算符。
在较复杂多层的逻辑里,尽量还是不要用,影响可读性。
let a = true;
let b = '';
if (a) {
b = '1';
} else {
b = '2';
}
console.log(b)//1
a == true && (b = '' || 'xx') || (b = 'yy');
console.log(b)//xx
let add_level = 0;
let add_step = 6;
if (add_step == 5) {
add_level = 1;
}
else if (add_step == 10) {
add_level = 2;
}
else if (add_step == 12) {
add_level = 3;
}
else if (add_step == 15) {
add_level = 4;
}
else {
add_level = 0;
}
console.log(add_level)//0
add_step = 15;
add_level = (add_step == 5 && 1) || (add_step == 10 && 2) || (add_step == 12 && 3) || (add_step == 15 && 4) || 0;
console.log(add_level)//4
&& 比较结果
{}&&0 //0
{}&&1 //1
{}&&-1 //-1
{}&&0 //0
[]&&1 //1
[]&&-1 //-1
undefined&&0 //undefined
undefined&&1 //undefined
undefined&&-1 //undefined
0&&0 //0
0&&1 //0
0&&-1 //0
1&&1 //1
1&&-1 //-1
'' && '' //''
'' && undefined //''
'' && 0 //''
'' && 1 //''
0 && [] //0
{} && {} //{}
{} && [] //[]
{} && undefined //undefined
[] && undefined //undefined
[] && '' //''
{} && '' //''