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

Posted TTLu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于js用解构来定义变量并赋值的主要内容,如果未能解决你的问题,请参考以下文章

箭头函数 解构赋值 立即执行函数 (function() )()

ES6 解构赋值

ES6 变量的解构赋值

3-变量的解构赋值

ES6语法~解构赋值箭头函数

浅谈解构(js)