最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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:

 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

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:

 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

Share Improve this question asked Jun 26, 2013 at 11:56 apalejaapaleja 4054 gold badges10 silver badges21 bronze badges 1
  • Both of your snippets do the same thing – Esailija Commented Jun 26, 2013 at 12:04
Add a ment  | 

1 Answer 1

Reset to default 3

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 value you need to use brackets: obj[value]

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

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

评论列表(0)

  1. 暂无评论