gpt4 book ai didi

javascript - 无法打印对象的值

转载 作者:行者123 更新时间:2023-11-28 17:04:43 25 4
gpt4 key购买 nike

在 JavaScript 中

我无法从对象中获取值。

打印时整个对象正在打印。但是,当我尝试仅访问 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 编译器词法分析中定义的变量命名约定规则。

这是有效的:

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

关于javascript - 无法打印对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com