JavaScript属性访问:点表示法与括号?

发布于 2025-02-10 13:09:15 字数 254 浏览 1 评论 0原文

除了显而易见的事实是,第一个形式可以使用变量,而不仅仅是字符串字面的,是否有任何理由使用一个形式,如果是这样,则在哪种情况下使用?

在代码:

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

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

// vs. 
var x = foo.bar;

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

Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?

In code:

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

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

// vs. 
var x = foo.bar;

Context: I've written a code generator which produces these expressions and I'm wondering which is preferable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

太傻旳人生 2025-02-17 13:09:15

来自在这里。

( 使用无法与点表示法一起使用的字符:

  var foo = myform.foo []; //错误的语法
var foo = myform [“ foo []”]; //正确的语法
 

包括非ASCII(UTF-8)字符,如myForm [“ダ”]更多示例< /a>)。

其次,在处理时方括号符号很有用
以可预测方式变化的属性名称:

  for(var i = 0; i&lt; 10; i ++){
  某个功能(myform [“ myControlnumber” + i]);
}
 

综述:

  • dot符号的写入速度更快,阅读更清晰。
  • 方括号符号允许访问包含的属性
    特殊字符和选择
    使用变量的属性

的另一个示例是无法与点表示法一起使用的字符属性名称,其本身包含dot

例如,JSON响应可以包含一个称为bar.baz的属性。

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

(Sourced from here.)

Square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

including non-ASCII (UTF-8) characters, as in myForm["ダ"] (more examples).

Secondly, square bracket notation is useful when dealing with
property names which vary in a predictable way:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing
    special characters and selection of
    properties using variables

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax
云淡风轻 2025-02-17 13:09:15

括号符号允许您通过存储在变量中的名称访问属性:

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

obj.x在这种情况下无法使用。

The bracket notation allows you to access properties by name stored in a variable:

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

obj.x would not work in this case.

一身骄傲 2025-02-17 13:09:15

在JavaScript中访问属性的两种最常见方法是带有点和方括号。 value.xvalue [x]访问Value上的属性,但不一定是同一属性。 区别在于X的解释方式。使用点时,点之后的零件必须是有效的变量名称,并且直接名称属性。使用方括号时,评估括号之间的表达式以获取属性名称。 value.x获取名为“ x”的值的属性,而值[x]试图评估表达式x并将结果用作属性名称。

因此,如果您知道您感兴趣的属性被称为称为“长度”,您说value.length。如果要提取由变量i中持有的值命名的属性,则说value [i]。而且,由于属性名称可以是任何字符串,如果要访问名为“ 2”“ John Doe”的属性,则必须使用方括号:value value [2]value [“ John Doe”]。即使您提前知道属性的精确名称,也是如此,因为“ 2” and “ John Doe”都是有效的变量名称,因此不能是通过点表示法访问。

在数组的情况下

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

The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

So if you know that the property you are interested in is called “length”, you say value.length. If you want to extract the property named by the value held in the variable i, you say value[i]. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: value[2] or value["John Doe"]. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.

In case of Arrays

The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length because that is easier to write than array["length"].

饮湿 2025-02-17 13:09:15

class )。

某些关键字(例如

//app.users is a hash
app.users.new = {
  // some code
}

DOT表示法不适用于Internet Explorer 8中的 在Windows XP上的IE8上,我没有尝试过其他环境)。简单的解决方案是切换到括号符号:

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

Dot notation does not work with some keywords (like new and class) in internet explorer 8.

I had this code:

//app.users is a hash
app.users.new = {
  // some code
}

And this triggers the dreaded "expected indentifier" (at least on IE8 on windows xp, I havn't tried other environments). The simple fix for that is to switch to bracket notation:

app.users['new'] = {
  // some code
}
神也荒唐 2025-02-17 13:09:15

foo.barfoo [“ bar”]访问foo上的属性,但不一定是同一属性。区别在于如何解释bar。使用点时,点之后的单词是属性的字面名称。使用方括号时,评估括号之间的表达式以获取属性名称。而foo.bar获取
值命名“ bar”的属性,foo [“ bar”]试图评估表达式“ bar”并使用结果,转换为字符串,作为属性名称。

如果我们采用此对象,请点表示法的限制

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

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 object:

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'
};

accessing its properties using dot notation

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'

But none of this is a problem for the Bracket Notation:

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'

Accessing variable using variable:

const variable = 'name';
const obj = {
  name: 'value'
};
// Bracket Notation
obj[variable]; // ✅ 'value'
// Dot Notation
obj.variable; // undefined
堇年纸鸢 2025-02-17 13:09:15

一般来说,他们做同样的工作。
然而,括号符号为您提供了使用点符号无法做的事情的机会,例如,

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

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

Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like

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

This can be extended to any property containing special characters.

念﹏祤嫣 2025-02-17 13:09:15

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

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;

除此之外,我想这只是一个品味问题。恕我直言,点符号较短,它更明显地是属性而不是数组元素(尽管当然JavaScript无论如何都没有关联阵列)。

You need to use brackets if the property name has special characters:

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;

Other than that, I suppose it's just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it's a property rather than an array element (although of course JavaScript does not have associative arrays anyway).

瞄了个咪的 2025-02-17 13:09:15

使用这些符号时要小心:
例如。如果要访问窗口父母中存在的功能。
在IE中:

window['parent']['func']

window.['parent.func']

我们可以使用:

window['parent']['func'] 

访问

window.parent.func 

Be careful while using these notations:
For eg. if we want to access a function present in the parent of a window.
In IE :

window['parent']['func']

is not equivalent to

window.['parent.func']

We may either use:

window['parent']['func'] 

or

window.parent.func 

to access it

花辞树 2025-02-17 13:09:15

时,您必须使用方括号符号

  1. 当属性名称为编号 。

      var ob = {
      1:“一个”,
      7:'七'
    }
    OB.7 // Syntaxerror
    OB [7] //“七”
     
  2. 属性名称具有特殊字符。

      var ob = {
      “这是一个”:1,
      “这是七个”:7,
    }  
    OB。
    ob ['这是一个'] // 1
     
  3. 属性名称分配给变量,您要访问
    属性值通过此变量。

      var ob = {
      “一个”:1,
      “七”:7,
    }
    
    var _seven ='七';
    ob._seven //未定义
    OB [_seven] // 7
     

You have to use square bracket notation when -

  1. The property name is number.

    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
  2. The property name has special character.

    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
  3. The property name is assigned to a variable and you want to access the
    property value by this variable.

    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    
澉约 2025-02-17 13:09:15

括号符号可以使用变量,因此在两个点表示法无法正常工作的情况下很有用:

1)当属性名称被动态确定时(当确切的名称在运行时不知道时)。

2)使用for ..在循环中浏览对象的所有属性。

资料来源: https:// /docs/web/javascript/guide/working_with_objects

Bracket notation can use variables, so it is useful in two instances where dot notation will not work:

1) When the property names are dynamically determined (when the exact names are not known until runtime).

2) When using a for..in loop to go through all the properties of an object.

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

半山落雨半山空 2025-02-17 13:09:15

[]表示法很有帮助:

如果您的对象是动态的,并且在键中可能会有一些随机值,例如number 和 [] 例如 -

var a = {1:3};

现在,如果您尝试访问a.1,它将通过错误,因为它是错误的,因为它是期待那边的弦。

Case where [] notation is helpful :

If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -

var a = { 1 : 3 };

Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.

铜锣湾横着走 2025-02-17 13:09:15

点表示法总是可取的。如果您使用的是一些“智能” IDE或文本编辑器,它将显示该对象的未定义名称。
仅当您的名称具有像破折号或类似的东西无效时,仅使用括号符号。而且,如果名称存储在变量中。

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.

流年里的时光 2025-02-17 13:09:15

让我添加其他方形符号的用例。如果要在对象中访问x-proxy的属性,则-将被错误解释。它们是其他一些情况,例如空间,点等,点操作对您无济于事。同样,如果您在变量中具有键,则仅访问对象中键值的唯一方法是按括号表示法。希望您获得更多背景。

Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.

奢望 2025-02-17 13:09:15

点符号失败的一个示例

json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"

An example where the dot notation fails

json = { 
   "value:":4,
   'help"':2,
   "hello'":32,
   "data+":2,
   "????":'????',
   "a[]":[ 
      2,
      2
   ]
};

// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json["????"]);
console.log(json["a[]"]);

// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.????);
console.log(json.a[]);

The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name

星光不落少年眉 2025-02-17 13:09:15

或者,当您想动态更改元素的类动作时:

// Correct

showModal.forEach(node => {
  node.addEventListener(
    'click',
    () => {
      changeClass(findHidden, 'remove'); // Correct
    },
    true
  );
});

//correct
function changeClass(findHidden, className) {
  for (let item of findHidden) {
    console.log(item.classList[className]('hidden'));// Correct
  }
}

// Incorrect 
function changeClass(findHidden, className) {
  for (let item of findHidden) {
    console.log(item.classList.className('hidden')); // Doesn't work
  }
}

Or when you want to dynamically change the classList action for an element:

// Correct

showModal.forEach(node => {
  node.addEventListener(
    'click',
    () => {
      changeClass(findHidden, 'remove'); // Correct
    },
    true
  );
});

//correct
function changeClass(findHidden, className) {
  for (let item of findHidden) {
    console.log(item.classList[className]('hidden'));// Correct
  }
}

// Incorrect 
function changeClass(findHidden, className) {
  for (let item of findHidden) {
    console.log(item.classList.className('hidden')); // Doesn't work
  }
}
维持三分热 2025-02-17 13:09:15

点表示法和括号符号两者都用于访问JavaScript中的对象属性。点符号主要使用,因为它易于阅读和理解。那么,为什么我们应该使用括号符号,那么当时有什么区别?好吧,括号符号[]允许我们使用变量访问对象属性,因为它将方括号内的表达式转换为字符串。

const person = {
  name: 'John',
  age: 30
};

//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'

const nameBracket = person['name'];
console.log(nameBracket);
// 'John'

现在,让我们看一个可变示例:

const person = {
  name: 'John',
  age: 30
};

const myName = 'name';
console.log(person[myName]);
// 'John'

另一个优点是点符号仅包含字母数字(和_和$),因此,如果要访问下面的对象(包含' - ',则必须为此使用括号符号))

const person = {
  'my-name' : 'John'
}

console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error

The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is mostly used as it is easier to read and comprehend. So why should we use bracket notation and what is the difference between then? well, the bracket notation [] allows us to access object properties using variables because it converts the expression inside the square brackets to a string.

const person = {
  name: 'John',
  age: 30
};

//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'

const nameBracket = person['name'];
console.log(nameBracket);
// 'John'

Now, let's look at a variable example:

const person = {
  name: 'John',
  age: 30
};

const myName = 'name';
console.log(person[myName]);
// 'John'

Another advantage is that dot notation only contain be alphanumeric (and _ and $) so for instance, if you want to access an object like the one below (contains '-', you must use the bracket notation for that)

const person = {
  'my-name' : 'John'
}

console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文