How do I retain an objects key name outside of scope of "for in"? Javascript
Question: How do retain the key name after a for in look exits. If I assign the key string to a variable outside of the scope of "for in" it turns into a number. is there any way to prevent this and maintain the key name? Thanks
Example:
var lastItem = undefined;
function getKeyNames(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
lastItem = i;
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
alert (lastItem);
objects.push(obj);
}
}
return objects;
}
alert (lastItem);
The alert inside the function (and inside the开发者_开发知识库 for in) outputes the actual string name of the key, but when I alert outside of the function, I get a number. Any Ideas how to retain the string name of the key? Just to make it clear I'm not talking about the value of an object, but the actual name of the key.
Works fine:
var foo = { foo : 22, bar : 42 };
for(var i in foo);
alert(i); // "bar"
What, exactly, are you passing to the function?
Your example looks fine. After getKeyNames
is called, lastValue
will hold the last key found in the object.
However, your example does not call getKeyNames
, so the alert(lastValue)
should alert "undefined".
If you ARE calling it somewhere, and you find that lastValue
contains a number, well it's probably because your object contains a number. For example, for (var i in ['a','b','c'])
will iterate "length", "0", "1", "2".
精彩评论