简体   繁体   English

javascript对象中字符串键的单引号

[英]single quotes for string keys in javascript object

In nodejs I was creating a list of objects with each object supposed to have a string key and a number as value.在 nodejs 中,我创建了一个对象列表,每个对象都应该有一个字符串键和一个数字作为值。 I am able to create this without issues but while trying to log this with console.log() .我可以毫无问题地创建它,但是在尝试使用 console.log() 记录它时。 I could see some keys did not have a single quotes surrounding the key while some did.我可以看到有些键在键周围没有单引号,而有些则有。

eg例如

[
    { '2d22f294': 0 },    
    { b6d108da: 0 },
    { b17562ff: 0 },
    { '0e4a0beb': 0 }
  ]

Could anyone explain what does it mean to have a single quotes surrounding the key , I was of the assumption this meant the key was a string but even the ones without single quotes around the keys are strings and act like strings.任何人都可以解释在 key 周围有一个单引号是什么意思,我假设这意味着 key 是一个字符串,但即使是那些没有单引号的 key 也是字符串并且像字符串一样。

如果它以数字开头,则打印必须向您显示有效的 javascript 并且引号告诉您它是一个字符串。

If you have an object like this如果你有这样的对象

let object = {
    name: 'Jim',
    25: 'Age'
}

You can access the properties in the following way:您可以通过以下方式访问属性:

  • for the name key ... object.name or object['name'] .对于name键 ... object.nameobject['name']

  • for the key 25 ... object[25] or object['25']对于键25 ... object[25]object['25']

This is because properties cannot start with a number in js.这是因为 js 中的属性不能以数字开头。 Therefore you have to access them with brackets.因此,您必须使用括号访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM