If we create some objects, and fill an array with those objects, are the names stored within the array, or only the properties of the object? I guess this may be trivial, but I haven't been able to find an answer.
var boxA = {color: "red", width: 100};
var boxB = {color: "yellow", width: 200};
var boxC = {color: "blue", width: 300};
boxArray = [boxA, boxB, boxC];
for (var i = 0; i < boxArray.length; i++) {
//****
// What code do we insert here to log
// boxA
// boxB
// boxC
//****
}
Of course, it is a trivial workaround to add
boxA.box = boxA;
etc and then call
console.log(boxArray[i].box);
But is that really necessary?
To answer your question directly - no, you can't do what you're asking. I've run into the same scenario a few times. Here's what I've done. Instead of using an array, you could just add your objects to an object literal instead, and map the object to some unique key, such as an id.
var boxes = {
boxA: { color: 'red', width: 100 },
boxB: { color: 'blue', width: 200 },
boxC: { color: 'yellow', width: 300 },
};
for (var boxKey in boxes) {
console.log(boxKey);
}
// to use
boxes.boxA; // do something with boxA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With