JavaScript属性访问:点符号与括号?

JavaScript属性访问:点符号与括号?,javascript,syntax,object-literal,Javascript,Syntax,Object Literal,除了第一个表单可以使用变量而不仅仅是字符串文字这一明显事实之外,还有什么理由使用一个而不是另一个,如果是,在哪些情况下 代码: // Given: var foo = {'bar': 'baz'}; // Then var x = foo['bar']; // vs. var x = foo.bar; 上下文:我编写了一个生成这些表达式的代码生成器,我想知道哪个更可取。如果属性名称有特殊字符,则需要使用括号: var foo = { "Hello, world!": true,

除了第一个表单可以使用变量而不仅仅是字符串文字这一明显事实之外,还有什么理由使用一个而不是另一个,如果是,在哪些情况下

代码:

// Given:
var foo = {'bar': 'baz'};

// Then
var x = foo['bar'];

// vs. 
var x = foo.bar;

上下文:我编写了一个生成这些表达式的代码生成器,我想知道哪个更可取。

如果属性名称有特殊字符,则需要使用括号:

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;
除此之外,我想这只是口味的问题。恕我直言,点符号较短,它更明显地表明它是一个属性而不是数组元素(尽管JavaScript当然没有关联数组)。

(来源于。)

方括号表示法允许使用不能与点表示法一起使用的字符:

包括非ASCII(UTF-8)字符,如
myForm[”ダ"]()

其次,方括号表示法在处理 以可预测的方式变化的属性名称:


括号表示法允许您按存储在变量中的名称访问属性:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

obj.x
在这种情况下不起作用。

一般来说,它们的作用相同。
然而,括号表示法给了你机会去做点表示法做不到的事情,比如

var x = elem["foo[]"]; // can't do elem.foo[];

这可以扩展到包含特殊字符的任何属性。

点表示法不适用于internet explorer 8中的某些关键字(如
new
class

我有这个密码:

//app.users is a hash
app.users.new = {
  // some code
}
这会触发可怕的“预期标识符”(至少在windows xp上的IE8上,我还没有尝试过其他环境)。简单的解决方法是切换到括号表示法:

app.users['new'] = {
  // some code
}

括号表示法可以使用变量,因此它在点表示法不起作用的两种情况下很有用:

1) 动态确定属性名称时(直到运行时才知道确切名称)

2) 使用for..in循环遍历对象的所有属性时


来源:

使用这些符号时要小心: 例如,如果我们想访问窗口父级中的函数。 在IE中:

不等于

window.['parent.func']
我们可以使用:

window['parent']['func'] 


要访问它,
[]
符号有用的情况下:

如果您的对象是动态的,并且键中可能有一些随机值,例如
number
[]
或任何其他特殊字符-

var a={1:3};


现在,如果您尝试在like
a.1
中访问,它将通过一个错误进行访问,因为它需要一个字符串。

让我再添加一些方括号表示法的用例。如果您想访问对象中的属性,比如说
x-proxy
,那么
-
将被错误地解释。它们也是类似的其他情况空格、点等,其中点操作对您没有帮助。此外,如果您在变量中有键,则访问对象中键值的唯一方法是使用括号表示法。希望您获得更多上下文。

在JavaScript中访问属性的两种最常见的方法是使用点和方括号。
value.x和value[x]
访问值上的属性,但不一定是相同的属性。区别在于x的解释方式。使用点时,点后的部分必须是有效的变量名,它直接命名属性。使用方括号时,计算括号之间的表达式以获得属性名。而value.x获取名为“x”的值的属性,值[x]尝试计算表达式x并将结果用作属性名。

因此,如果您知道您感兴趣的属性称为“length”,那么您可以说
value.length
。如果您想提取由变量
i
中的值命名的属性,那么您可以说
value[i]
。因为属性名称可以是任何字符串,如果您想访问名为
“2”的属性
“John Doe”
,必须使用方括号:
值[2]或值[“John Doe”]
。即使您事先知道属性的确切名称,也会出现这种情况,因为
“2”和“John Doe”
都不是有效的变量名,因此无法通过点符号访问

如果是数组


数组中的元素存储在属性中。由于这些属性的名称是数字,我们通常需要从变量中获取它们的名称,因此我们必须使用括号语法来访问它们。数组的length属性告诉我们它包含多少个元素。此属性名称是有效的变量名称,我们知道它的name,因此要找到数组的长度,通常需要编写
array.length
,因为这比
array[“length”]
更容易编写,当-

  • 属性名为number

    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
  • 属性名称具有特殊字符

    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
  • 属性名称已分配给变量,您希望访问 属性值由该变量指定

    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    

  • 点表示法失败的示例

    json = { 
       "value:":4,
       'help"':2,
       "hello'":32,
       "data+":2,
       "Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object. 
    Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.

    Both
    foo.bar
    and
    foo["bar"]
    access a property on foo but not necessarily the same property. The difference is in how
    bar
    is interpreted. When using a dot, the word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas
    foo.bar
    fetches the property of value named
    “bar”
    ,
    foo["bar"]
    tries to evaluate the expression
    "bar"
    and uses the result, converted to a string, as the property name

    Dot Notation’s Limitation

    if we take this oject :

    const obj = {
      123: 'digit',
      123name: 'start with digit',
      name123: 'does not start with digit',
      $name: '$ sign',
      name-123: 'hyphen',
      NAME: 'upper case',
      name: 'lower case'
    };
    
    json={
    “值:”:4,
    “帮助”:2,
    “你好””:32,
    “数据+”:2,
    
    “点表示法总是可取的。如果您使用的是“更智能”的IDE或文本编辑器,它将显示该对象中未定义的名称。
    仅当名称带有类似破折号或类似无效字符时,以及名称存储在变量中时,才使用括号表示法。

    同时使用
    foo.bar
    foo[“bar”]
    访问foo上的属性,但不一定是相同的属性。区别在于如何解释
    bar
    。使用点时,点后的单词是属性的文字名称。使用方括号时,表示
    window.parent.func 
    
    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    
    json = { 
       "value:":4,
       'help"':2,
       "hello'":32,
       "data+":2,
       "Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object. 
    Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.

    Both
    foo.bar
    and
    foo["bar"]
    access a property on foo but not necessarily the same property. The difference is in how
    bar
    is interpreted. When using a dot, the word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas
    foo.bar
    fetches the property of value named
    “bar”
    ,
    foo["bar"]
    tries to evaluate the expression
    "bar"
    and uses the result, converted to a string, as the property name

    Dot Notation’s Limitation

    if we take this oject :

    const obj = {
      123: 'digit',
      123name: 'start with digit',
      name123: 'does not start with digit',
      $name: '$ sign',
      name-123: 'hyphen',
      NAME: 'upper case',
      name: 'lower case'
    };
    
    obj.123;      // ❌ SyntaxError
    obj.123name;  // ❌ SyntaxError
    obj.name123;  // ✅ 'does not start with digit'
    obj.$name;    // ✅  '$ sign'
    obj.name-123;  // ❌ SyntaxError
    obj.'name-123';// ❌ SyntaxError
    obj.NAME; // ✅ 'upper case'
    obj.name; // ✅ 'lower case'
    
    obj['123'];     // ✅ 'digit'
    obj['123name']; // ✅ 'start with digit'
    obj['name123']; // ✅ 'does not start with digit'
    obj['$name'];   // ✅ '$ sign'
    obj['name-123']; // ✅ 'does not start with digit'
    obj['NAME']; // ✅ 'upper case'
    obj['name']; // ✅ 'lower case'
    
    const variable = 'name';
    const obj = {
      name: 'value'
    };
    // Bracket Notation
    obj[variable]; // ✅ 'value'
    // Dot Notation
    obj.variable; // undefined
    
    var foo = { 'bar': 'baz' };
    console.log(foo['bar']); // baz
    console.log(foo.bar);   //  baz
    
    var foo = { 'bar bar': 'baz' };
    console.log(foo['bar bar']); // baz
    console.log(foo.bar bar);    // error