Let's say you have an array of strings such as:
var fruit = ["apple","peach","pear","plum"];
and an empty array that is to be filled with objects, each of which will have a text property bound to a specific index of the fruit array:
var objlist = [];
for (var i=0;i<fruit.length;i++) {
objlist.push({text: fruit[i]});
}
//objlist[0].text = "apple", objlist[1].text = "peach", etc.
Is there a way to "bind" the elements of the first array so the following statement:
fruit.shift()
will cause the text properties of the objects in objlist to update to their corresponding index in the fruit array?
//objlist[0].text = "peach", objlist[1].text = "pear", etc.
I've come to terms with the fact that .text will probably have to be a function .text() but that's okay for my purposes.
The following doesn't work for obvious reasons:
for (var i=0;i<fruit.length;i++) {
objlist.push({text: function() { return fruit[i]; }}); //i is not bound
}
However, this works perfectly:
[0,1,2,3].forEach(function(i) {
objlist.push({text: function() { return fruit[i]; }}); //i is bound
});
With the second method I can modify fruit[] and objlist will update accordingly, but it's not elegant.
My question: is there a better method to do this? Maybe something akin to using pointers?
fruitandobjlist?