Question

Note: No jQuery
How could i do something like this:

var array = new Array();
array[name] = "Tom";
array[age] = 15;
foreach(array as key=>value){
    alert(key + " = " + value);
}
Was it helpful?

Solution

First of all, you should call it obj or person instead of array; an array is a sequence of similar elements, not a single object.

You can do it like this:

var person = new Object();
person['name'] = "Tom";
person['age'] = 15;
for (var key in person) {
    if(!person.hasOwnProperty(key)) continue;     //Skip base props like toString

    alert(key + " = " + person[key]);
}

You can also initialize the object using properties, like this:

person.name = "Tom";
person.age = 15;

You can also use JavaScript object literal syntax:

var person = { name: "Tom", age: 15 };

OTHER TIPS

This will work in your simple example scenario:

for (var key in array) {
  alert(key + " = " + array[key]);
}

For general use, it's recommended that you test to be sure that the property hasn't been grafted onto the object somewhere else in the inheritance chain:

for (var key in array) {
  if (array.hasOwnProperty(key)) {
    alert(key + " = " + array[key]);
  }
}

Use a javascript object

var object = {};
object.name = "Tom";
object.age = 15;
for ( var i in object ) {
    console.log(i+' = '+ object[i]);
}

First, you don't want an array, you want an object. PHP's idea of what constitutes an array is frankly a little weird.

var stuff = {
    name: "Tom",
    age: 15
};

/* Note: you could also have done
var stuff = {};
stuff.name = "Tom";
stuff.age = 15;

// or

var stuff = {};
stuff["name"] = "Tom";
stuff["age"] = 15;

*/

for (var key in stuff) {
    alert(key + " = " + stuff[key];
}
key=0;while(key<array.length) {
    alert(key + " = " + array.item(key));
    key++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top