admin管理员组

文章数量:1355582

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]));

本文标签: javascriptUncaught TypeError Objectkeys called on nonobject while trying to access objectStack Overflow