gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:44:43 27 4
gpt4 key购买 nike

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

...

最佳答案

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

关于javascript - 将每个对象中的字符串循环到一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24501760/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com