有人能帮我破译这条ES6语句吗?
const {
isFetching,
lastUpdated,
items: posts
} = postsByReddit[selectedReddit] || {
isFetching: true,
items: []
}
我从Redux异步示例- https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js#L81中提取了它。
发布于 2016-07-12 06:28:01
代码只是简单地声明三个常量,如果对象是非空的,则从类似命名的属性中获取它们,否则从充当默认值的对象文本中获取它们。我相信您对像语法这样的对象而不是const关键字感到困惑。
var|let|const { ... } = ...
是一个对象,用于销毁declaration.。
var|let|const [ ... ] = ...
是一个数组,用于销毁declaration.。
都是“拆分右手并分配到左手边”的缩写。。
可以使用不同的括号对数组或对象执行解构。它可以是声明的一部分,也可以作为独立的任务。
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
对于对象析构,可以指定属性名。对于数组,可以通过保留空白逗号跳过元素。析构也可以形成层次结构并被混合。
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
当破坏null
或undefined
,或在不可迭代的情况下破坏数组时,它将抛出TypeError
。否则,如果找不到匹配的部件,则其值为undefined
,除非设置了默认值。
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
数组析构工作于任何“可迭代”对象,如地图、设置或NodeList。当然,这些可迭代对象也可以作为对象进行销毁。
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>
最后,不要忘记,任何声明都可以使用析构,而不仅仅是在函数体中:
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
}
请注意,因为析构依赖于左手侧来指定如何销毁右侧,所以不能使用析构为对象属性赋值。这也排除了计算的财产名称在析构中的使用。
正如您所看到的,析构是一个简单的速记概念,它将帮助您以更少的代码完成更多工作。它是Chrome、Edge、Firefox、Node.js和Safari中的Node.js,所以现在就可以开始学习和使用它了!
为了EcmaScript5 (IE11)兼容性,巴贝尔和示踪剂传输程序可以将大多数ES6/ES7代码转换为ES5,包括析构。 如果还不清楚,欢迎来到StackOverflow JavaScript聊天室。作为第二大最受欢迎的房间,专家们每周7天24小时开放:)
发布于 2016-07-12 07:21:25
这是对已经给出的答复的补充。析构还支持默认值,这使我们能够简化代码:
const {
isFetching = true,
lastUpdated,
items = []
} = postsByReddit[selectedReddit] || {};
发布于 2016-07-12 02:01:52
基本上:
var isFecthing;
var lastUpdated;
var posts;
if (postsByReddit[selectedReddit]) {
isFecthing = postsByReddit[selectedReddit].isFecthing;
lastUpdated = postsByReddit[selectedReddit].lastUpdated;
posts = postsByReddit[selectedReddit].items.posts;
} else {
isFecthing = true;
items = [];
}
https://stackoverflow.com/questions/38318809
复制相似问题