【问题标题】:loop string in each object to one string将每个对象中的字符串循环到一个字符串
【发布时间】:2014-07-01 02:41:50
【问题描述】:

如何将每个对象中的循环字符串添加到一个字符串中,如下所示?
我需要将每个变量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>';
    }
}

对象

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"  

...

【问题讨论】:

  • obj 的数据是什么?
  • 在循环外声明你的字符串,然后使用连接创建一个字符串。
  • @jasonscript 谢谢回复,你能举个例子吗?
  • @AdamMerrifield obj 是上面例子中的javascript对象
  • @user1775888 声明this_encode 你开始for之前。所以它会是var this_encode = '';,然后是for (var key in obj) {。在for 中,只需将var this_encode = 替换为this_encode +=

标签: javascript jquery data-structures


【解决方案1】:

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

【讨论】:

  • 感谢@AdamMerrifield。更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2017-07-14
  • 2011-06-18
  • 2012-01-14
  • 1970-01-01
  • 2018-04-12
相关资源
最近更新 更多