0

Let's say I have an array of data and a variable (or multiple variables)

var i = 1;
var arr = {
        1: ['whatever' + i,'there are ' + i + ' dogs in the yard.', etc], 
    }

Is there a way to dynamically update the variable(s) in the array later on in a function?

So

function start() {
i++;
alert(arr[1][0]);
}

Would output "whatever2" instead of "whatever1"

2
  • 2
    What do you mean with 'update the variable'?. Please, explain it better Commented May 10, 2012 at 1:12
  • Your question is not clear... if you think about changing i later on, that's not possible. 'whatever' + i and 'there are ' + i + ' dogs in the yard.' are evaluated when the array is defined, i.e. the value of i is determined at that moment and that value is concatenated with the other string. Commented May 10, 2012 at 1:14

3 Answers 3

3

You could have an array and push() stuff you need, but when the string is made, it won't change anymore.

var array = ['whatever',i,'there are ',i,' dogs in the yard.'];
array.push('more stuff');
array.push('even more stuff');
var string = array.join('')
//string = 'whatever[whatever "i" is during join]there are[whatever "i" is during join]dogs in the yard.more stuffeven more stuff'
Sign up to request clarification or add additional context in comments.

Comments

1

You could use functions instead:

var i = 1;
var arr = {
    1: [
        function() { return 'whatever' + i },
        function() { return 'there are ' + i + ' dogs in the yard.' },
        function() { return 'etc' }
    ], 
}:

Which would change your calls to:

function start() {
    i++;
    alert(arr[1][0]());
}

1 Comment

Clever. This is the closest to what I wanted. Thanks!
1

Try this code:

var arr = function(i){
    return {
        1: ['whatever' + i,'there are ' + i + ' dogs in the yard.', etc],
    }
}
var anyNumber = 1;
var updatedVar = arr(anyNumber);

Comments

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.