我正在寻找一个使用变量
在循环中返回值的快速解决方案有基本代码
var origins = [
{level: '1', hp: 5600},
{level: '2', hp: 7600},
{level: '3', hp: 9600}
];
var text1 = "";
var text2 = "";
for (var key in origins) {
if (origins.hasOwnProperty(key)) {
text1 = origins[key].level;
text2 = origins[key].hp;
}
}
我正在尝试调用循环变量
console.log(text1 + " " + text2)
它给了我一个我不想要的输出:
3 9600
我看起来输出的例外结果是这样的:
1 5600
2 7600
3 9600
编辑: 有JSfiddle
答案 0 :(得分:4)
您需要将console.log放在循环中或添加到一个文本变量,如final。见下文
var origins = [
{level: '1', hp: 5600},
{level: '2', hp: 7600},
{level: '3', hp: 9600}
];
var text1 = "";
var text2 = "";
var final = "";
for (var key in origins) {
if (origins.hasOwnProperty(key)) {
text1 = origins[key].level;
text2 = origins[key].hp;
final += "Level: " + text1 + '\n' + "HP: " + text2 + '\n';
}
}
//I need to get external variable that would exeute in loop
alert(final);
//Excepted Result as one alert with output:
//Level 1: 5600
//Level 2: 7600
//Level 3: 9600
答案 1 :(得分:3)
我认为这可能会对您有所帮助:
var origins = [
{level: '1', hp: 5600},
{level: '2', hp: 7600},
{level: '3', hp: 9600}
];
var text1 = "";
var text2 = "";
var s= "";
for (var key in origins) {
if (origins.hasOwnProperty(key)) {
text1 = origins[key].level;
text2 = origins[key].hp;
s += '\n' + "Level " + text1 + ": " + text2;
}
}
然后再做
alert(s);
答案 2 :(得分:2)
var origins = [
{level: '1', hp: 5600},
{level: '2', hp: 7600},
{level: '3', hp: 9600}
];
var text1 = "";
var text2 = "";
for (var key in origins) {
if (origins.hasOwnProperty(key)) {
text1 = origins[key].level;
text2 = origins[key].hp;
console.log(text1 + " " + text2);
}
}
编辑:如果您想将结果保存为整个字符串
var origins = [
{level: '1', hp: 5600},
{level: '2', hp: 7600},
{level: '3', hp: 9600}
];
var text1 = "";
var text2 = "";
var result = ""; // String to print
for (var key in origins) {
if (origins.hasOwnProperty(key)) {
text1 = origins[key].level;
text2 = origins[key].hp;
result += text1 + " " + text2 + "\n";
}
}
alert(result);
如果您希望各自以HTML格式显示此内容,只需将result += text1 + " " + text2 + "\n";
替换为result += text1 + " " + text2 + "<br>";
,将alert(result);
替换为document.getElementById("myelem").innerHTML = result;