gpt4 book ai didi

javascript - Javascript 中简单嵌套 for 循环的问题

转载 作者:行者123 更新时间:2023-12-02 17:01:11 26 4
gpt4 key购买 nike

我在 Javascript 中的嵌套 for 循环中遇到了一个奇怪的问题。我想用一种语言填充一组答案,然后将其包含在另一个数组中。问题是,当我看到输出时,仅使用内部 for 循环中数组的最后一次迭代。我相信它与基于其他答案的闭包有关,但由于我这里没有多个功能,所以我不确定这会如何。这是JS Fiddle .

代码如下:

var answer_array = [];
var content_array = [];
var i18n_array = ['en', 'fr', 'es'];

for (var i18nCount = 0; i18nCount < 3; i18nCount++) {

var i18nLang = i18n_array[i18nCount];

for (var ansIndex = 0; ansIndex < 3; ansIndex++) {
answer_array[ansIndex] = {
value: 'This is answer # ' + ansIndex + ' in this language ' + i18nLang
};
}

console.log(i18nCount);
console.log(i18nLang);
console.log(JSON.stringify(answer_array,null,4));

content_array[i18nCount] = {
i18n: i18nLang,
text: 'This question is in ' + i18nLang + ' language?',
answers: answer_array,
};
}

console.log(JSON.stringify(content_array,null,4));

它产生这个:

    0
en
[
{
"value": "This is answer # 0 in this language en"
},
{
"value": "This is answer # 1 in this language en"
},
{
"value": "This is answer # 2 in this language en"
}
]
1
fr
[
{
"value": "This is answer # 0 in this language fr"
},
{
"value": "This is answer # 1 in this language fr"
},
{
"value": "This is answer # 2 in this language fr"
}
]
2
es
[
{
"value": "This is answer # 0 in this language es"
},
{
"value": "This is answer # 1 in this language es"
},
{
"value": "This is answer # 2 in this language es"
}
]
[
{
"i18n": "en",
"text": "This question is in en language?",
"answers": [
{
"value": "This is answer # 0 in this language es"
},
{
"value": "This is answer # 1 in this language es"
},
{
"value": "This is answer # 2 in this language es"
}
]
},
{
"i18n": "fr",
"text": "This question is in fr language?",
"answers": [
{
"value": "This is answer # 0 in this language es"
},
{
"value": "This is answer # 1 in this language es"
},
{
"value": "This is answer # 2 in this language es"
}
]
},
{
"i18n": "es",
"text": "This question is in es language?",
"answers": [
{
"value": "This is answer # 0 in this language es"
},
{
"value": "This is answer # 1 in this language es"
},
{
"value": "This is answer # 2 in this language es"
}
]
}
]

最佳答案

您一遍又一遍地重复使用相同的answer_array,覆盖它的 3 个成员。

在每次外部循环迭代时创建一个新数组,而不是在循环外部。

例如:

var content_array = [];
var i18n_array = ['en', 'fr', 'es'];

for (var i18nCount = 0; i18nCount < 3; i18nCount++) {
var answer_array = []; // Move this inside
var i18nLang = i18n_array[i18nCount];

关于javascript - Javascript 中简单嵌套 for 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25695166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com