首页 > 解决方案 > 无法打印对象的值

问题描述

在 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

解决方案


如果字段名称以数字开头,则无法通过点符号访问。这是在 javascript 编译器的词法分析中定义的用于 vars 命名的约定规则。

这是有效的:

gg.first_col
gg._1st_col
gg.a1st_col

如果您使用括号表示法以这种方式引用这些字段是有效的:

gg["1st_col"]

- - 编辑 - -

这些是在 javascript 中定义变量名的基本规则:

  • 名称应以小写字符串开头。
  • 名称不能包含符号或以符号开头。
  • 名称不能以数字开头。
  • 名称可以包含大写字符串、小写字符串和数字的混合。

资料来源:https ://scotch.io/courses/10-need-to-know-javascript-concepts/declaring-javascript-variables-var-let-and-const


推荐阅读