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

loop string in each object to one string

本文关键字:字符串 一个 循环 对象      更新时间:2023-09-26

如何在每个对象中循环字符串添加到一个字符串,如下面的结果?
我需要将每个变量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"  
...

在循环外声明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
    }
}