【问题标题】:Javascript syntax meaningJavascript语法含义
【发布时间】:2015-06-11 18:12:18
【问题描述】:

鉴于以下 JavaScript 块:

var n = { a: 1, b: "1.0", c: false, d: true };
var a = "b";

谁能帮我解释一下下面的表达方式:

n.a 
n[ a ]
n.a == n.b 
n.a === n.b 
n.b == n.d 
n.a =n= n.d  
n.c ? "a" : "b" 
n.e   
n.e 
n.e != null 

【问题讨论】:

标签: javascript syntax


【解决方案1】:

代码创建了两个变量,一个对象 (n) 和一个字符串 (a)。可以使用.[] 运算符访问对象的属性。您应该阅读有关 Javascript 对象如何工作的说明,例如 this one。

n.a                  // Accesses the 'a' property of n, which currently holds 1
n[ 'a' ]             // Also accesses the 'a' property. Same as above.
n[ a ]               // Since a holds the string 'b', the accesses the
                     // 'b' property of n
n.a == n.b           // Compares n's 'a' property to n's 'b' property
n.a === n.b          // Same, but does a strict comparison so type
                     // and value are compared
n.b == n.d           // Another comparison with different properties
n.a =n= n.d          // Sets n to true. Will cause the lines after this
                     // not to function as expected since n is no longer
                     // an object. See Barmar's comments below.
n.c ? "a" : "b"      // Shorthand for if (n.c) return "a" else return "b" 
n.e                  // Accesses 'e' attribute of n (Currently not set)
n.e != null          // Compares (unset) e attribute to null

【讨论】:

  • 您应该根据他对问题所做的更改来更新您的答案。 o 不见了。
  • n.a =n= n.d 等价于n.a = (n = n.d)
  • @Barmar 所以n = n.d 设置n 等于true。这是有道理的,但现在n 不是对象,所以n.a = true 试图将true 分配给不再是对象的变量的属性。
  • 显然分配给布尔值的属性不会导致错误,但它不会做任何事情。 true.a = true
猜你喜欢
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多