将每个对象中的字符串循环到一个字符串

时间:2014-07-01 02:41:51

标签: javascript jquery data-structures

如何在每个对象中循环字符串添加到一个字符串,如下面的结果?
我需要将每个变量this_encode添加到一个字符串中,该怎么做?

result: '<img src=""><iframe></iframe><img src="">'

for (var key in obj) {
    if (obj[key].file_type == 0) {
        var this_encode = '<img src="' + obj[key].file_name + obj[key].file_format + '">';
    } else if(obj[key].file_type == 1) {
        var this_encode = '<iframe width="150" height="100" src="'+obj[key].file_embed_url +'" frameborder="0" allowfullscreen></iframe>';
    }
}

OBJ

file_embed_url: ""  
file_format: "jpg"  
file_name: "53b21c90dded9"  
file_sequence: "0"  
file_type: "0"  
gallery_id: "1"  
id: "138"  

file_embed_url: "//www.youtube.com/embed/-x6jzKpqeuw"  
file_format: ""  
file_name: ""  
file_sequence: "1"  
file_type: "1"  
gallery_id: "1"  
id: "139"  

...

1 个答案:

答案 0 :(得分:3)

在循环外声明您的this_encode变量,然后使用连接创建单个字符串

// first initialise your variable as an empty string; can't concatenate to undefined
var this_encode = '';

// Now run your code as before with 2 small differences
//      (1) Remove the var declarations
//      (2) Use += instead of = to indicate that you want to append the following text to the this_encode variable
for (var key in obj) {
    if (obj[key].file_type == 0) {
        this_encode += '<img src="' + obj[key].file_name + obj[key].file_format + '">';
    //  ^           ^ see the change here
    //  |
    //  var declartion removed from here (and below)
    } else if(obj[key].file_type == 1) {
        this_encode += '<iframe width="150" height="100" src="'+obj[key].file_embed_url +'" frameborder="0" allowfullscreen></iframe>';
        //          ^ and here
    }
}