如何在javascript

时间:2017-09-17 03:57:30

标签: javascript jquery

这是我的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

请问你能帮帮我吗?

1 个答案:

答案 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]);