Javascript如何在换行符上显示数组的每个元素 [英] Javascript how to show each element of array on a new line

查看:70
本文介绍了Javascript如何在换行符上显示数组的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串构建形式,用逗号分隔值,我使用split来获取每个值,然后我想在新行上显示每个值,但实际上发生的是我在新行上获取了每个值,除了最后两个显示在同一行上.只是为了清楚起见:

I have a string build form comma separated values I use split to get each value and after that I want to show each value on a new line but what really happens is that I get each value on a new line except of the last two which are shown together on a same line. Just to make it clear:

value1

value1

,值2

,value3

,value4,value5

,value4,value5

这是我正在使用的功能:

Here is the function which I'm using:

_checkDates: function(dates) {
        if (dates != null)
        {
            var zzz = dates.split(',');
            var xxx = zzz.length;
            console.log(xxx);
            for (var i=0; i<=xxx; i++)
                {
                    zzz[i] = zzz[i] + '<br />';
                    return zzz;
                }
        }
        return dates;
    }

请明确一点,这是用ExtJS 4编写的,我几乎可以肯定,在这种情况下,问题是纯JavaScript的,与ExtJS 4无关,但无论如何,也许我是错的.

Just to be clear this is written in ExtJS 4, I'm almost sure that in this case the problem is pure JavaScript and is not related with ExtJS 4 but anyways, maybe I'm wrong.

那么有什么主意为什么会发生,以及我怎样才能使最后的障碍也能换上新的行呢?

So any ideas why does it happen and how I could make that last elemnt to get on a new line as well?

谢谢

Leron

推荐答案

for循环可疑.首先,您不处理所有项目(如@sarfraz所指出的,最后一个项目丢失了).次要在for循环正文中返回结果(zzz):

The for-loop is suspicious. Firstly, you do not process all items (the last one is missing, as @sarfraz pointed out). Sencondly you are returning the result (zzz) in the for-loop body:

for (var i=0; i<=xxx; i++)
{
  zzz[i] = zzz[i] + '<br />';
  return zzz; // for-loop will stop here! resulting in ["value1<br />", "Value2", etc...]
}

在Javscript中,您可以简单地连接"数组:

In Javscript you can simple "join" the array:

return dates.split(',').join("<br />")

由于您只是替换字符串,因此可以使用replace方法:

Since you are simply replacing strings you could use the replace method:

return dates.replace(",", "<br />");

这篇关于Javascript如何在换行符上显示数组的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆