简洁js代码片段

  1. 空值合并运算符(??)
    如果没有定义左侧返回右侧,有,返回左侧
	 let may;
     if(may) {
    
    
       	console.log(may)
      } else {
    
    
      	console.log('123')
     }
 
   console.log(may ?? 'Nothing found')

2.可选链(?.)
在未定义属性时使用可选链运算符,undefined将返回而不是错误。这可以防止代码崩溃

const student = {
    
    
    name: '哈哈',
    age: '20',
    address: {
    
    
      state: 'aaa'
    }
  }
 console.log(student && student.address && student.address.ZIPCode)
 console.log(student?.address?.ZIPCode)

3.交换变量,通过解构赋值交换变量

let x = 1;
let y = 2;
[ x, y ] = [y, x ]

4.使用&&运算符,检查是否为真

var isReady = true 
function doSomething() {
    
    
   console.log('yes')
 }
 
 if(isReady) {
    
    
   doSomething ()
 }
 
 isReady && doSomething ()

5.指数运算符

Math.pow(4,2)  // 16
Math.pow(2,3)  // 8

4**2  // 16
2**3  // 8

6.Math.floor()简写 ,可以使用~~运算符

Math.floor(2.4)  // 2
~~2.4  // 2

7.将对象的值收集到数组中
用Object.values() 将对象的所有值收集到一个新数组中

const info = {
    
     name: "Matt", country: "Finland", age: 35 };

let data = [];
for (let key in info) {
    
    
  data.push(info[key]);
}

const data = Object.values(info);

文章来自于Vue中文社区公众号,记录以便查询

猜你喜欢

转载自blog.csdn.net/ccyolo/article/details/119409694