简体   繁体   English

Javascript数组中的动态串联

[英]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" 将输出“ whatever2”而不是“ whatever1”

You could have an array and push() stuff you need, but when the string is made, it won't change anymore. 您可能需要一个数组和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'

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

you can use eval(): 您可以使用eval():

  var i = 1;
    var arr = {
            1: ["'whatever' + i","'there are ' + i + ' dogs in the yard.'"], 
        }
    function start() {
    i++;
    alert(eval(arr[1][0]));
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM