Advanced Application js operator

"||" and "&&" Advanced Usage

&&:从左往右依次判断,当当前值为true则继续,为false则返回此值(是返回未转换为布尔值时的原值哦)
|| : 从左往右依次判断,当当前值为false则继续,为true则返回此值(是返回未转换为布尔值时的原值哦)
// => aaa
var attr = true && 4 && "aaa";

// => 0
var attr = true && 0 && "aaa";

// => 100
var attr = 100 || 12;

// => e
var attr = "e" || "hahaha"

// => hahaha
var attr = "" || "hahaha"
多次判断的赋值
/*
x>=15时 => 4
x>=12时 => 3
x>=10时 => 2
x>=5时 => 1
x<5时 => 0
*/
console.log((x>=15 && 4) || (x>=12 && 3) || (x>=10 && 2) || (x>=5 && 1) || 0);
对象形式的变量合体

/*
x=15 时 => 4
x=12 时 => 3
x=10 时 => 2
x=5 时 => 1
其它 => 0
*/
console.log( {'5':1,'10':2,'12':3,'15':4}[x] || 0 );

用于执行语句
if(a >=5){alert("你好");}
//可以写成: 
a >= 5 && alert("你好");

E.g

假如说现在我们有一个需求:有一个成长速度,
成长速度为5时,显示1个箭头,
成长速度为10时,显示2个箭头,
成长速度为15时,显示3个箭头,
成长速度为20时,显示4个箭头。


var add_level = (add_step==5 && 1) || (add_step==10 && 2) || (add_step==15 && 3) || (add_step==20 && 4) || 0; 

var add_level={'5':1,'10':2,'15':3,'20':4}[add_step] || 0; 



if(a==undefined){
  a = {}
}else{
  a = a;
}
//可以写成
a = a || {};



The elegant rounded

let a = ~~2.33;
let b = 2.33 | 0;
let c = 2.33 >>0;
let d = 2.33 <<0;
let e= 2.33 ^ 0;
console.log(a,b,c,d,e) //2


优雅的将字符串转成数字

let a = '123';
let b = '123,4567';
let c = a *1;
let d = ~~b * 1;
let e = +a;
console.log(typeof a); // String
console.log(typeof b); // String
console.log(typeof c); // Number
console.log(typeof d); // Number
console.log(typeof e); // Number

Reproduced in: https: //www.jianshu.com/p/af60f2416ab8

Guess you like

Origin blog.csdn.net/weixin_34246551/article/details/91230114