In JavaScript, create 7 variables with the same value but different names

In JavaScript, how do I make a for loop that would make 7 variables with the same value,but different names. So, I want to take a string and subtract the last two letters. I do this with

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

And then make 6 more of the stem variables with the names of stem0 through stem6. Right now my code is:

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

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

Note some implications with regard to scope when doing this. Essentially, the subsequent variables are initialized in the global namespace. Remedy that by defining them in advance.

That said, I suspect that your application logic could be simplified to avoid needing 7 identical variables.


你可以像这样拥有它:

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

只需使用一个数组。

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

for (var i = 0; i < 7; i++) {
    stemArray[i] = value;
};
链接地址: http://www.djcxy.com/p/69996.html

上一篇: 我如何显示所有localStorage保存的变量?

下一篇: 在JavaScript中,创建具有相同值但名称不同的7个变量