对象属性名称作为数字 [英] Object property name as number

查看:40
本文介绍了对象属性名称作为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 官方 JavaScript 文档 您可以使用整数定义对象字面量属性名称:

According to the official JavaScript documentation you can define object literal property names using integers:

此外,您可以使用数字或字符串文字作为属性名称.

Additionally, you can use a numeric or string literal for the name of a property.

像这样:

me = {
    name: "Robert Rocha",
    123: 26,
    origin: "Mexico"
}

我的问题是,如何引用以整数作为名称的属性?我尝试了通常的 me.123 但出现错误.我能想到的唯一解决方法是使用 for-in 循环.有什么建议吗?

My question is, how do you reference the property that has an integer as a name? I tried the usual me.123 but got an error. The only workaround that I can think of is using a for-in loop. Any suggestions?

推荐答案

您可以像引用数组一样引用对象的属性,并使用 me[123]me["123"]

You can reference the object's properties as you would an array and use either me[123] or me["123"]

这篇关于对象属性名称作为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆