这是我的javascript:
var myobject = {};
for(var i = 1; i <= 10 ; i++){
if(i<=5){
key = '123'
if(myobject.key == undefined){
myobject.key = '';
}
myobject.key = myobject.key + 'English';
}
else{
key = '456'
if(myobject.key == undefined){
myobject.key = '';
}
myobject.key = myobject.key + 'Thai';
}
}
key = '123';
document.write(myobject.key);
如果key = 123
我会附加值English
。
但如果key = 456
我会附加值Thai
。
document.write(myobject.key)
:它返回了结果EnglishEnglishEnglishEnglishEnglishThaiThaiThaiThaiThai
但我想要预期的结果EnglishEnglishEnglishEnglish
请问你能帮帮我吗?
答案 0 :(得分:0)
您正在访问key
文字,而不是myobject[key]
。您可以像这样简化代码:
var myobject = {};
for (var i = 1; i <= 10; i++) {
if (i <= 5) {
key = '123'
myobject[key] = (myobject[key] || '') + 'English';
} else {
key = '456'
myobject[key] = (myobject[key] || '') + 'Thai';
}
}
key = '123';
document.write(myobject[key]);