2014-09-04 124 views
-5

在JavaScript中,如何创建一个for循环,使7个变量​​具有相同的值,但名称不同。所以,我想要一个字符串并减去最后两个字母。我这样做在JavaScript中,创建具有相同值但名称不同的7个变量

var stringExample = prompt("Blah blah"); 
var stem = stringExample.substring(0, stringExample.length-2); 

然后再用stem0到stem6的名称制作6个stem变量。现在,我的代码是:

for (var i = 0; i < 7; i++) { 
    eval('var stem' + i + '= toDecline.substring(0, toDecline.length - 2'); 
}; 
+4

所以你想要一个数组...... – elclanrs 2014-09-04 18:38:01

+2

最有可能有更好的方式来做你想做的事情。发布你正在尝试做的事情。 – 2014-09-04 18:42:10

+0

[在JavaScript中使用动态变量名称]可能的重复(http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – Teemu 2014-09-04 19:02:48

回答

1
var stem = stringExample.substring(0, stringExample.length-2); 
var stem0 = stem1 = stem2 = stem3 = stem4 = stem5 = stem6 = stem; 

注意一些implications with regard to scope这样做的时候。本质上,后续变量在全局名称空间中初始化。通过预先定义它们来弥补。

这就是说,我怀疑你的应用程序逻辑可以被简化以避免需要7个相同的变量。

+0

怎么样:'var stem0 = stem1 = stem2 = stem3 = stem4 = stem5 = stem6 = stringExample.substring(0,stringExample.length-2);' – 2014-09-04 19:03:17

+0

@isherwood我一直试图弄清楚如何解决7个变量的问题。之后,我使用'var nom = stem0 + ='a';'将字符串添加到字符串的末尾。但是,当我添加另一行'var gen = stem0 + ='ae';'它最终使'gen'的值变为'nom + ='ae''的值我需要七个变量,因为我做了一个变量比如nom或gen 7次,而且它只是在最后加上更多的文字。有关于此的任何想法? – 2014-09-04 19:12:37

+0

使用'var stem0 = stem1 = stem2 = stem3 = stem4 = stem5 = stem6 = stem;'工作。 – 2014-09-04 19:29:09

1

你可以把它像这样:

var stem = stringExample.substring(0, stringExample.length-2); 
    var stemr=[]; 
    for (var i = 0; i < 7; i++) { 
    stemr[i]=stem; 
    } 
1

只需使用一个数组。

var stemArray = []; 
var value = stringExample.substring(0, stringExample.length-2); 

for (var i = 0; i < 7; i++) { 
    stemArray[i] = value; 
}; 
+0

嗯....也许我的代码是关闭的,但没有奏效。 'var toDecline = prompt(“输入单词的属性”); var stem = toDecline.substring(0,toDecline.length - 2); (var i = 0; i <7; i ++){ all1 [0] = stem + ='a'; all1 [1] = stem + ='ae'; all1 [2] = stem + ='ae'; all1 [3] = stem + ='am'; all1 [4] =词干+ ='a'; all1 [5] = stem + ='ae'; all1 [6] = stem + ='arum'; all1 [7] = stem + ='is'; all1 [8] = stem + ='as'; all1 [9] = stem + ='is'; }; console.log(all1);'P.S.我在做一个拉丁语单词下降者。 – 2014-09-04 19:22:29

+0

什么不起作用?顺便说一句,在你的代码中,那个循环什么都不做。 – forgivenson 2014-09-04 19:32:01

相关问题