es6学习笔记--解构赋值
昨天学习了es6语法中解构赋值,解构赋值在声明中和函数传参提高了灵活性和便捷性,值得掌握该语法。
let [a,b,c] = [1,2,3]; console.log(a); // 1 console.log(b); // 2 console.log(typeof c); // number console.log(a === 1); // true
let [arr,foo] = [1]; console.log(foo); // undefined
let [x, y] = [1, 2, 3]; console.log(x); // 1 console.log(y); // 2 let [x,[a],y] = [1,[2,3],4]; console.log(a) // 2
let [a,b=2] = [1]; console.log(a) // 1 console.log(b) // 2
let [a,b=2] = [1,3]; console.log(`a的值是${a} b的值是${b}` ) // 1 3
let [a,b=2] = [1,undefined]; console.log(`a的值是${a} b的值是${b}` ) // 1 2
let [a,b=2] = [1,null]; console.log(a) // 1 console.log(null === undefined) // false 严格模式下,null和undefined不等 console.log(b) // null
let x = 1; let y = 2; [x, y] = [y, x]; console.log(`x:${x} y:${y}`) // x:2 y:1
let {b, a, c} = {a: 'peter', b: 'Bob'}; console.log(`a:${a} b:${b} c:${c}`) // peter Bob undefined
const obj = { foo: 'peter', bar: 25 }; let {foo: name, bar: age} = obj; console.log(`name:${name} age:${age}`) // name:peter age:25
{obj} = {obj: 10} // Uncaught SyntaxError: Unexpected token =
({obj} = {obj: 10})
在对象解构赋值中,最常用的就是,函数返回值,有多个时,可以按照返回对象的形式返回。
function foo() { return { foo: 1, bar: 2 }; } let { foo, bar } = foo();
let json = { id: 1, status: 200, data: [123, 456] }; let { id, status, data: number } = json; console.log(id, status, number); // 1, 200, [123, 456]
let [a,b,c,d,e,f] = 'hello'; console.log(`a:${a} b:${b} c:${c} d:${d} e:${e} f:${f}`) // a:h b:e c:l d:l e:o f:undefined console.log(typeof a) // string let [m,n,q,p] = 'w ord'; console.log(`m:${m} n:${n} q:${q} p:${p}`) // m:w n: q:o p:r let {length:len} = 'hello world'; console.log(len) // 12 let [a='H',b,c,d,e,f='W'] = 'hello'; console.log(`a:${a} b:${b} c:${c} d:${d} e:${e} f:${f}`) // a:h b:e c:l d:l e:o f:W
function add([x, y]){ return x + y; } console.log(add([1,2])); // 3
function move({x = 0, y = 0} = {}) { return [x, y]; } console.log(move({x: 1, y: 2})); // [1, 2] console.log(move({x: 1})); // [1, 0] console.log(move({})); // [0, 0] console.log(move()); // [0, 0]
对应的笔记和实例,我放到了GitHub,https://github.com/sqh17/notes
有什么问题请私信或留下评论,一起加油。
参考资料:
阮一峰大大的es6标准入门:http://es6.ruanyifeng.com/