gpt4 book ai didi

jquery - 从循环中的最后一个元素中删除逗号

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:16 26 4
gpt4 key购买 nike

在 Rails 应用程序 View 中,我从用逗号分隔的数组中输出数据。如何从最后一个元素中删除逗号?我可以这样做:

html = ""
answer.first.selected_answers.each do |sa|
if answer.first.selected_answers[-1] == sa
html << content_tag(:span, "#{sa.possible_answer.text}", class: 'answer')
else
html << content_tag(:span, "#{sa.possible_answer.text}, ", class: 'answer')
end
end
html.html_safe

有没有更优雅的方式?也许使用 JQuery?还是 CSS last-child

最佳答案

也许你可以使用join方法。

例如:

[1,2,3,4,5,6,7].join(", ").split(" ")
=> ["1,", "2,", "3,", "4,", "5,", "6,", "7"]

对于你的代码,也许可以这样写:

answer.first.selected_answers.map { |sa| sa.possible_answer.text }.join(", ").split(" ")
.map{ |t| content_tag(:span, t, class: 'answer') }

关于jquery - 从循环中的最后一个元素中删除逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30411933/

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