Stephen
Stephen

Reputation: 1991

Dynamic Concatenation in Javascript Array

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"

Upvotes: 0

Views: 2579

Answers (3)

Jacob
Jacob

Reputation: 78840

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]());
}

Upvotes: 1

Danilo Valente
Danilo Valente

Reputation: 11342

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);

Upvotes: 1

Joseph
Joseph

Reputation: 119847

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'

Upvotes: 3

Related Questions