js用解构来定义变量并赋值

解构数组

var [a,b]=[1,2];

a //1

b //2

-------------

var [a,b]=[1,2,3,4];

a //1

b //2

----------------

var [a,,b]=[1,2,3,4];

a //1

b //3

-----------------

var a,b;

[a=3,b=2]=[1]; //默认值

a //1

b //2

-----------------

var [a, ...b] = [1,2,3,4]

a //1

b // [2,3,4]

----------------

应用

function parseProtocol(url) { 
  var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
  if (!parsedURL) {
    return false;
  }
  console.log(parsedURL); // ["https://test/page", "https", "test", "page"]

  var [, protocol, fullhost, fullpath] = parsedURL;
  return protocol;
}

console.log(parseProtocol('https://test/page')); // "https"

  

 

解构对象

var o = {p: 42, q: true};
var {p: foo, q: bar} = o;// 将o的p值赋给变量foo,将o的q值赋值给变量bar。var {p: foo, q: bar} = o;等价于({p: foo, q: bar} = o);

let {t=4, m=true} = {t:5};//这样就定义了两个变量t和m,并各自带有默认值。
let {t:val1=4, m: val2=true} = {t:5};

  

给函数的参数赋默认值:

function render({position ={x:0,y:0},color="red",display=true}){
console.log(position,color,display);
}

render({position:{x:20,y:30}, color:"green"});


解构数组内的对象:

const props = [
  { id: 1, name: 'Fizz'},
  { id: 2, name: 'Buzz'},
  { id: 3, name: 'FizzBuzz'}
];
const [,, { name }] = props;
console.log(name); // "FizzBuzz"

  

解构结构复杂的对象:

const metadata = {
  title: 'Scratchpad',
  translations: [
    {
      locale: 'de',
      localization_tags: [],
      last_edit: '2014-04-14T08:43:37',
      url: '/de/docs/Tools/Scratchpad',
      title: 'JavaScript-Umgebung'
    }
  ],
  url: '/en-US/docs/Tools/Scratchpad'
};

let {
  title: englishTitle, // rename
  translations: [
    {
       title: localeTitle, // rename
    },
  ],
} = metadata;

console.log(englishTitle); // "Scratchpad"
console.log(localeTitle);  // "JavaScript-Umgebung"

  

 refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

posted @ 2019-04-10 11:33  被爱浸润的智慧体  阅读(599)  评论(0编辑  收藏  举报