javascript - 无法打印对象的值
问题描述
在 javscript 中
我无法从对象中获取值。
打印整个对象时正在打印。但是,当我尝试仅访问 1 个字段时,它显示错误
function add_new_row()
{
let gg =
{
"1st_col" : '99',
"2nd_col" : '88',
"3rd_col" : ['77', '66'],
"4th_col" : '55',
}
console.log(gg); //{1st_col: "99", 2nd_col: "88", 3rd_col: Array(2), 4th_col: "55"}
console.log(gg.1st_col); //Error here
//this is the line where I called this function in button HTML
}
抛出的错误是:
Uncaught ReferenceError: add_new_row is not defined
at HTMLInputElement.onclick (index2.html:120)
onclick @ index2.html:120
解决方案
如果字段名称以数字开头,则无法通过点符号访问。这是在 javascript 编译器的词法分析中定义的用于 vars 命名的约定规则。
这是有效的:
gg.first_col
gg._1st_col
gg.a1st_col
如果您使用括号表示法以这种方式引用这些字段是有效的:
gg["1st_col"]
- - 编辑 - -
这些是在 javascript 中定义变量名的基本规则:
- 名称应以小写字符串开头。
- 名称不能包含符号或以符号开头。
- 名称不能以数字开头。
- 名称可以包含大写字符串、小写字符串和数字的混合。
推荐阅读
- node.js - 在 Digitalocean NodeJS 液滴上使用 NPM 失败
- woocommerce-subscriptions - 如何在我的帐户中添加个人资料图片(文件上传)> 在没有插件的 WooCommerce 中编辑帐户
- javascript - 我试图改变 div 背景颜色,但没有。创建更改元素背景颜色的新功能
- graph-theory - 可以用属性而不是整数标记顶点吗?
- python - Flask Jinja2 不渲染引导轮播
- reactjs - React Router Dom v4 Home Activeclass上的多个嵌套路由
- typescript - 缩小联合的条件类型
- python - 为单词中的字母分配数值
- c++ - 为什么 decltype(captured_var) 的行为不符合预期?
- python - 激活 bot.polling,同时激活命令处理程序。Telebot,蟒蛇 3