给出以下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
答案 0 :(得分:0)
代码创建两个变量,一个对象(n
)和一个字符串(a
)。可以使用.
或[]
运算符访问对象的属性。您应该阅读Javascript对象如何工作的描述,例如this一个。
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