[ES6]变量解构赋值

变量的解构赋值

以前做法

 var a = 1;
 var b = 2;
 var c = 3;
 var a = 1,b = 2,c = 3;

1.数组的解构赋值

let [a,b,c] = [1,2,3];
let [a,b,c] = [,123,]; //undefined 123 undefined

给默认值:
let [a=111,b,c] = [,123,]; //111 123 undefined

2. 对象的解构赋值

let {foo,bar} = {foo : 'hello',bar : 'hi'};
let {foo,bar} = {bar : 'hi',foo : 'hello'};

// 对象属性别名
//(如果有了别名,那么原来的名字就无效了)

let {foo:abc,bar} = {bar : 'hi',foo : 'nihao'};
 console.log(abc,bar);

// 对象的解构赋值指定默认值

let {foo:abc='hello',bar} = {bar : 'hi'};
console.log(abc,bar);

//将内置对象Math的属性和对应的名称进行绑定;绑定后random()形式调用

let {cos,sin,random} = Math;
 console.log(typeof cos); //function
 console.log(typeof sin); //function
 console.log(typeof random); //function

3.字符串的解构赋值

let [a,b,c,d,e] = "hello";
console.log(a,b,c,d,e); // h e l l o

console.log(“hello”.length);
//获取字符串的长度,利用对象

let {length} = "hi";
console.log(length);  //2

猜你喜欢

转载自blog.csdn.net/weixin_43843847/article/details/89598749