Pranav Raykar Pranav Raykar - 2 months ago 12
Javascript Question

Unexpected behaviour when _.allKeys(obj) array(say var arr) is reffered to object :obj.arr[0], it returns undefined

For those who don't know what _.allKeys(obj) does, here's a snippet

var allKeys = function(obj){
var key=[];
for(var pname in obj){
key.push(pname);
}
return key;
};`


So it returns an array of property/method names of an object which is passed to it.

//Say I have an object obj.
var obj={firstname:"John", lastname:"Adams"};
var arr=allKeys(obj); //stores the returned array of property names into arr.
for(var i;i<arr.length;i++){
console.log("Property name: "+arr[i]); //this detects the propertyname
console.log("Value name"+obj.arr[i]); //But when its referred to the object it does not return its value,why so ?
console.log("------");
}


This should give me:




Property name: firstname

Value name: John

------


Property name: lastname

Value name: Adams

------



Instead it gives me :




Property name: firstname

Value name: undefined

------

Property name: lastname

Value name: undefined

------



Any ideas why it does that ?

Answer

This will give you the same result as you expected

var allKeys = function(obj){
          var key=[];
          for(var pname in obj){
          key.push(pname);              
          }
          return key;
        };

var obj={firstname:"John", lastname:"Adams"};
var arr=allKeys(obj);  //stores the returned array of property names into arr.
for(var i=0;i<arr.length;i++){
  console.log("Property name: "+arr[i]); //this detects the propertyname
  console.log("Value name: "+obj[arr[i]]); // I used BRACKET NOTATION
  console.log("------");
}

Ref

Hope this helps :)

Comments