2

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?

1
  • I don't think there's a way to automatically link the two arrays. Couldn't you write a function that removes the element from both fruit and objlist? Commented Sep 19, 2012 at 8:15

1 Answer 1

1

There is not necessary to create additional array because you can make binding by for-in construction. Like this

for (var k in fruit) {
    objlist.push({text: function() { return fruit[k]; }});
}

So, with your test cases

var fruit = ["apple","peach","pear","plum"];
var objlist = [];

for (var k in fruit) {
    objlist.push({text: function() { return fruit[k]; }});
}

console.log('---- init state -----')
for(k in objlist) {
    console.log(objlist[k].text());
}

fruit.shift();
console.log('---- shifted state -----')
for(k in objlist) {
    console.log(objlist[k].text());
}

The code gets

---- init state -----
apple
peach
pear
plum
---- shifted state -----
peach
pear
plum
undefined
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I never thought to use for-in. It seems to be doing the closure thing automatically. I figured out another method using text:(function(n) { return function() { return fruit[n]; }}(i) but I like your method better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.