ES6

ES6知识点复习(二)

2022-07-15  本文已影响0人  假笑boys

变量的解构赋值

\color{#FF8C00}{\rm\large{数组的解构赋值}}
  let [a,b,c] = [1,2,3]
  console.log(a,b,c)  // 1,2,3
  let [one,...two] = [12,13,14,15]
  console.log(one,two)  // 12,[13,14,15]
  let [x,y,...z] = ['a']
  console.log(x,y,z)   // a undefined []
  // 对于 set结构,也可以使用数组的解构赋值
  let [first,twos,three] = new Set(['a','b','c'])
  console.log(first)
\color{#FF8C00}{\rm\large{默认值}}
  let [x=1,y=x] = []
  console.log(x,y) 1,1
  let [x=1,y=x] = [2]
  console.log(x,y)  // 2,2
  let [x=1,y=x] = [1,2]
  console.log(x,y)  // 1,2
  let [x=y,y=1] = [];
  console.log(x,y)  //  Cannot access 'y' before initialization  无法在初始化之前使用 
  因为x用y做默认值时,y还没有声明。

\color{#FF8C00}{\rm\large{对象的解构赋值}}
 let { baz } = {foo:'aaa',bar:'bbbb'}
 console.log(baz)  // undefined

  let { foo:baz } = {foo:'justin',bar:'bieber'}
  console.log(baz)
\color{#FF8C00}{\rm\large{对象解构赋值-默认值}}
  var { x=3 } = {}
  console.log(x) // 3
  var {x,y=5} ={x:1}
  console.log(x,y) // 1,5
  var {x:y=3} ={}
  console.log(y) // 3
  var {x:y=3} = {x:5}
  console.log(y) // 5

\color{#FF8C00}{\rm\large{注意点}}
 let x;
 {x} = {x:1}
 console.log(x) //SyntaxError: Unexpected token '=' 
 let x;
 ({x}={x:1}) 
 console.log(1)`

\color{#FF8C00}{\rm\large{字符串的解构赋值}}
const [a,b,c,d,e] = 'justin'
console.log(a,b,c,d,e) // j u s t i 
 
let {length:len} ='justin'
console.log(len) // 6
\color{#FF8C00}{\rm\large{数值和布尔值的解构赋值}}
let {toString:s} = 1234
console.log(s=== Number.prototype.toString)  // true
let {toString: s} = true;
s === Boolean.prototype.toString // true

\color{#FF8C00}{\rm\large{函数参数的解构赋值}}
  function add([x,y]){
    return x+y
  }
  add([1,2]) // 3
  [[1,2],[3,4]].map(([a,b]) => a+b)  // [3,7]
  function move({x, y} = { x: 0, y: 0 }) {
    return [x, y];
  }

  move({x: 3, y: 8}); // [3, 8]
  move({x: 3}); // [3, undefined]
  move({}); // [undefined, undefined]
  move(); // [0, 0]
\color{#FF8C00}{\rm\large{用途}}
  let x =1;
  let y =2;
  [x,y]=[y,x] 
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一个对象

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();
上一篇 下一篇

猜你喜欢

热点阅读