解密ES6 const解构声明 [英] Decypher ES6 const destructuring declaration

查看:129
本文介绍了解密ES6 const解构声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  const {
isFetching,
lastUpdated,
items:posts
} = postsByReddit [selectedReddit] || {
isFetching:true,
items:[]
}

我把它从Redux异步的例子 - https ://github.com/reactjs/redux/blob/master/examples/async/containers/App.js#L81

解决方案

代码只是声明三个常量,如果它们是非空的,从对象的类似命名的属性获取它们,否则从作为默认值的对象文字中获取它们。
我相信你被混淆在对象上,而不是const关键字。



var | let | const {...} = ... 是一个对象解构声明



var | let | const [...] = ... 是一个数组解构声明



两者都是分解右手边并分配给左手边的简单手段。



可以在数组或对象上完成破坏使用不同的括号。
它可以是声明的一部分或作为独立赋值。

  const {isFetching} = obj; //与const isFetching = obj.isFetching相同
var [a,b] = ary; //与var a = ary [0]相同,b = ary [1]
[a] = [1]; //与a = 1

对于对象解构,可以指定属性名称。
对于数组,您可以通过留下空白逗号来跳过元素。
解构也可以形成层次结构并混合使用。

  const {items:posts} = obj; //与const posts = obj.items相同
var [,,c] = ary; //与var c = ary [2]相同
let {foo:[{bar}],bas} = obj; //与let bar = obj.foo [0]相同.bar,bas = obj.bas

当解构 null undefined ,或者在非迭代的数组结构时,它将抛出 TypeError
否则,如果找不到匹配的部分,它的值为 undefined ,除非设置了默认值。

  let {err1} = null; // TypeError 
let [err3] = {}; // TypeError
let [{err2}] = [undefined]; // TypeError

let [no] = []; // undefined
let {body} = {}; // undefined
let {here = this} = {}; //这里===这个

let {valueOf} = 0; //惊喜! valueOf === Number.prototype.valueOf

数组解构可用于任何可迭代对象,例如地图 Set NodeList
当然,这些可迭代对象也可以作为对象被破坏。

  const doc = document; 
let [a0,a1,a2] = doc.querySelectorAll('a'); //获取前三个< a>进入a0,a1,a2
let {0:a,length} = doc.querySelectorAll('a'); //获取第一个< a>和< a>

最后,不要忘记,解构可以在任何声明中使用,而不仅仅是在函数体中:

 函数日志({method ='log',message}){
console [method](message)
}
log({method:info,message:this calls console.info});
log({message:这默认为console.log});

for(let i = 0,list = frames,{length} = frames; i< length; i ++){
console.log(list [i]); //记录每一帧
}




请注意,因为破坏取决于左手边的指定如何去破坏右边的
你不能使用destructring来分配给对象的属性。
这也不包括使用计算的属性名称在解构中。


正如你所看到的,解构是一个简单的简写概念,可以帮助您用更少的代码来做更多。
Chrome,Edge,Firefox,Node.js中的得到很好的支持 ,和Safari,
,所以你可以开始学习和使用它现在!


对于EcmaScript5(IE11)兼容性, Babel Traceur 透镜
可将大多数ES6 / ES7代码转换为ES5,包括解构。



如果仍然不清楚,请随时访问 StackOverflow JavaScript聊天室
作为SO上第二个最受欢迎的房间,专家全天候提供:)



Can someone help me decypher this ES6 statement?

const {
    isFetching,
    lastUpdated,
    items: posts
  } = postsByReddit[selectedReddit] || {
    isFetching: true,
    items: []
  }

I pulled it from the Redux async example - https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js#L81

解决方案

The code is simply declaring three constants, getting them from similarly named properties on an object if it is non-empty, otherwise get them from an object literal that acts as default values. I trust that you are confused over the object like syntax rather than the const keyword.

var|let|const { ... } = ... is an object destructuring declaration.

var|let|const [ ... ] = ... is an array destructuring declaration.

Both are short hand for "break down right hand side and assign to left hand side".

Destructuring can be done on array or object using different brackets. It can be part of a declaration or as stand-alone assignment.

const { isFetching } = obj; // Same as   const isFetching = obj.isFetching
var [ a, b ] = ary;         // Same as   var a = ary[0], b = ary[1]
[ a ] = [ 1 ];              // Same as   a = 1

For object destructuring, you can specify the property name. For array, you can skip elements by leaving blank commas. Destructuring can also form a hierarchy and be mixed.

const { items: posts } = obj;        // Same as   const posts = obj.items
var [ , , c ] = ary;                 // Same as   var c = ary[2]
let { foo: [ { bar } ], bas } = obj; // Same as   let bar = obj.foo[0].bar, bas = obj.bas

When destructuring null or undefined, or array destructure on non-iterable, it will throw TypeError. Otherwise, if a matching part cannot be found, its value is undefined, unless a default is set.

let { err1 } = null;                // TypeError
let [ err3 ] = {};                 // TypeError
let [ { err2 } ] = [ undefined ]; // TypeError

let [ no ] = [];                // undefined
let { body } = {};             // undefined
let { here = this } = {};     // here === this

let { valueOf } = 0;        // Surprise! valueOf === Number.prototype.valueOf

Array destructuring works on any "iterable" objects, such as Map, Set, or NodeList. Of course, these iterable objects can also be destructed as objects.

const doc = document;
let [ a0, a1, a2 ]  =  doc.querySelectorAll( 'a' ); // Get first three <a> into a0, a1, a2
let { 0: a, length } = doc.querySelectorAll( 'a' ); // Get first <a> and number of <a>

Finally, don't forget that destructuring can be used in any declarations, not just in function body:

function log ({ method = 'log', message }) {
  console[ method ]( message );
}
log({ method: "info", message: "This calls console.info" });
log({ message: "This defaults to console.log" });

for ( let i = 0, list = frames, { length } = frames ; i < length ; i++ ) {
   console.log( list[ i ] ); // Log each frame
}

Note that because destructuring depends on left hand side to specify how to destructre right hand side, you cannot use destructring to assign to object properties. This also excludes the usage of calculated property name in destructuring.

As you have seen, destructuring is a simple shorthand concept that will help you do more with less code. It is well supported in Chrome, Edge, Firefox, Node.js, and Safari, so you can start learn and use it now!

For EcmaScript5 (IE11) compatibility, Babel and Traceur transpilers can turn most ES6/ES7 code into ES5, including destructuring.

If still unclear, feel free to come to StackOverflow JavaScript chatroom. As the second most popular room on SO, experts are available 24/7 :)

这篇关于解密ES6 const解构声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆