0

假设我有一个数据数组和一个变量(或多个变量)

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

有没有办法稍后在函数中动态更新数组中的变量?

所以

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

将输出“whatever2”而不是“whatever1”

4

3 回答 3

3

你可以有一个数组和push()你需要的东西,但是当字符串被创建时,它不会再改变了。

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'
于 2012-05-10T01:14:20.107 回答
1

试试这个代码:

var arr = function(i){
    return {
        1: ['whatever' + i,'there are ' + i + ' dogs in the yard.', etc],
    }
}
var anyNumber = 1;
var updatedVar = arr(anyNumber);
于 2012-05-10T01:17:36.410 回答
1

您可以改用函数:

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

这会将您的电话更改为:

function start() {
    i++;
    alert(arr[1][0]());
}
于 2012-05-10T02:01:43.160 回答