JavaScript Looping Through Object Properties
My previous post contained a small piece of code explaining how to loop through object properties with the Reflection
namespace in C#.
In this post, I'd like to explain how to loop through a JavaScript object.
Let's create an object in JavaScript:
var myObject = {
Name: "Elad",
LastName: "Shalom",
Age: 26,
Kids: ["Daniel"]
};
This object contains four properties:
Name
(string)LastName
(string)Age
(int)Kids
(array)
Now for the loop part:
function LoopThroughProperties(obj)
{
for (var propName in obj)
{
alert(propName + ": " + obj[propName]);
}
}
The function will receive an object and loop through all of its properties.
I'd like to explain a bit about the for
syntax I used. Those of you who write in C#/ VB/ Java will find it very similar to the foreach
loop in JavaScript.
Since an object in JavaScript is a form of array, I can easily call every one of its properties the same way (almost) I'd call them when looping through an array. This type of foreach
loop in JavaScript is also very useful when going through a hash table. Since we won't know the numbers the hash contains, we can simply loop through it.
Thanks.
发表评论
tJCOZS whoah this blog is wonderful i love reading your articles. Keep up the good work! You know, many people are searching around for this info, you could help them greatly.
dExd1a pretty helpful material, overall I imagine this is well worth a bookmark, thanks
XYqzVg I think this is a real great post.Really thank you!