1. 程式人生 > >es6學習二:變數的解構賦值

es6學習二:變數的解構賦值

變數的解構賦值:

陣列的解構賦值:

let [a,b,c] = [1,2,3];
// let [a,b,c] = [,123,];
// let [a=111,b,c] = [,123,];
console.log(a,b,c);

// let [a,b,c] = [1,2,3];
let [a,b,c] = [,123,];
// let [a=111,b,c] = [,123,];
console.log(a,b,c);

// let [a,b,c] = [1,2,3];
// let [a,b,c] = [,123,];
let [a=111,b,c] = [,123,];
console.log(a,b,c);

相當於原生js的:

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

物件的解構賦值:

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

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

物件屬性別名(如果有了別名,那麼原來的名字就無效了)

// 物件屬性別名(如果有了別名,那麼原來的名字就無效了)
let {foo:abc,bar} = {bar : 'hi',foo : 'nihao'};
console.log(abc,bar);

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

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

內建物件的解構賦值:

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

字串的解構賦值:

let [a,b,c,d,e,length] = "hello";
console.log(a,b,c,d,e);
console.log(length);

怎麼樣得到字串的長度:

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