在字符串名称后附加一个整数

Append an integer to a string name

本文关键字:一个 整数 字符串      更新时间:2023-09-26

嗨,我正试图从impactjs:中的单个字符串(单词列表)中的一个长字符串中迭代for循环

var wordlist3 ="hellwhentrysthisbreaks"
var  xc=3;
var word_length = 4;
var words_in_round = 4;             
for ( i=0; i<words_in_round; i++){        
    var num_words = ['wordlist' + xc].length / word_length;
    var random = Math.floor(Math.random() * ((num_words+1) - 0 ));
    n = Math.round(random / word_length) * word_length;
    random_word =(['wordlist' + xc].substring(n,(n+word_length)))
    random_words += random_word;
}

如果我将wordlist定义为全局,但当我将其定义为局部时,num_words没有正确定义,并且随机单词抛出,则上述代码有效。该对象没有方法子字符串。。

我的问题是,由于我在附加字符串名称并调用.length时转换为局部变量,它给了我新名称的长度(wordlist3.length=9),而不是wordlist3=20的长度。。我也不能在这个对象上调用方法substring。。。

['wordlist' + xc].substring

永远不会工作(好吧,除非前面有另一个变量,例如foo['wordlist' +xc].substring)。这是因为,在Javascript中,[anything]的意思是"任何东西的数组",并且(正如Kendall所提到的)数组没有子字符串方法。

尝试:

random_word =(('wordlist' + xc).substring(n,(n+word_length)))

相反。