javascript 未捕获的类型错误:尝试访问对象时在非对象上调用了 Object.keys

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17319336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:52:26  来源:igfitidea点击:

Uncaught TypeError: Object.keys called on non-object while trying to access object

javascriptjqueryarraysobject

提问by apaleja

I am trying to access array inside object using Object.keys(obj.arr));method. If I access array directly like below, then it is giving proper output:

我正在尝试使用Object.keys(obj.arr));方法访问对象内部的数组。如果我像下面一样直接访问数组,那么它会提供正确的输出:

 alert(Object.keys(obj.arr));

but if I pass array name using parameter then it is giving error :

但是如果我使用参数传递数组名称,则会出现错误:

var selected = "arr";
alert(Object.keys(obj.arr));

error : Uncaught TypeError: Object.keys called on non-object 

There is example : DEMO

有例子:DEMO

采纳答案by Esailija

If you need dynamic property access, you cannot use .value. That is always literally accessing named key of "value". If you want to access property with the key name contained in the variable valueyou need to use brackets: obj[value]

如果您需要动态属性访问,则不能使用.value. 那总是从字面上访问 的命名键 "value"。如果要value使用变量中包含的键名访问属性,则需要使用方括号:obj[value]

Fixed demo: http://jsfiddle.net/Lv6TY/7/

固定演示:http: //jsfiddle.net/Lv6TY/7/

console.log("Variable Pass "+Object.keys(groups[selected]));