I encountered a unique issue while working with nested for loops in Javascript. My goal was to populate an array of answers in one language and then include those in another array. However, I noticed that only the last iteration of the inner for loop's array was being used in the output. After researching, I suspect it may be related to closures, but since there are no multiple functions involved, I am unsure how to address this issue. Here is a link to the JS Fiddle showing the problem.
Below is the code snippet:
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));
The produced output showcases this unexpected behavior:
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"
}
]
}
]