对象解构语法 - ES6 [英] Object destructuring syntax - ES6

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

问题描述

我经历过数组解构语法,这很好理解。

I had been through array destructuring syntax, which is well understood.

当我们说 var {p时,我们在下面做了什么? ,q} = o;

p q in var {p,q} o 的属性不同,即'p''q'?如果是,

Is p and q in var {p, q} different from properties of o i.e., 'p' and 'q'? If yes,

为什么 var {a,b} = o; 不起作用?

> var o = {p: 42, q: true};
    undefined
> p
    ReferenceError: p is not defined
> q
    ReferenceError: q is not defined
> o['p']
    42
> o['q']
    true
> var {p, q} = o;
    undefined
> p
    42
> q
    true
> var {a, b} = o;
    undefined
> a
    undefined
> b
    undefined

*注意:我了解到,字典键是字符串文字在javascript。*

*Note: I learnt that, dictionary keys are string literals in javascript.*

推荐答案

    var o = {p: 42, q: true};
     var {p, q} = o;

此处, var {p,q} = o 只是的缩写var {p:p,q:q} = o

考虑一下。

      var o = { key : "value" };
      var { key : local_var } = o ;
      local_var === o["key"] // true

如果省略local_var,并写入
var {key} = o;
a将使用标识符key创建新的变量键。,就像在执行
var key = o [key]

If you omit the local_var, and write var {key} = o; a new variable key will be created with the idenifier "key"., same like doing var key = o["key"]

所以在你的例子里就像在做

So in your example that's like doing

      var p =  o["p"] ;  //42
       var q = o["q"];   //true
       var a = o["a"];  // undefined
       var b = o["b"];   //undefined

这可能不完全正确,但应该有助于您理解它。

这种类似于其他语言提供的模式匹配,但它有所不同。

This may not be exactly true, but should help you understand it.
It's kind of something like Pattern Matching that other languages provide, but it's different.

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

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