简体   繁体   English

从javascript数组中删除逗号

[英]Removing commas from javascript array

I have 3 strings "a","b","c" in javascript array "testarray". 我在javascript数组“testarray”中有3个字符串“a”,“b”,“c”。

var testarray=new Array("a","b","c");

and then I am printing the value of testarray using javascript alert box. 然后我使用javascript警告框打印testarray的值。

alert(testarray);

The result will be like a,b,c 结果将类似于a,b,c

All these strings are separated by "," character. 所有这些字符串都以“,”字符分隔。 I want to replace this "," with some other character or combination of two or more characters so that the alert box will show something like a%b%c or a%$b%$c 我想用其他字符或两个或多个字符的组合替换此“,”,以便警告框显示类似a%b%ca%$b%$c

Use the join method : 使用join方法

alert(testarray.join("%")); // 'a%b%c'

Here's a working example . 这是一个有效的例子 Note that by passing the empty string to join you can get the concatenation of all elements of the array: 请注意,通过将空字符串传递给join您可以获得数组的所有元素的串联:

alert(testarray.join("")); // 'abc'

Side note : it's generally considered better practice to use an array literal instead of the Array constructor when creating an array: 旁注 :在创建数组时,通常认为使用数组文字而不是Array构造函数是更好的做法:

var testarray = ["a", "b", "c"];

use testarray is getting converted in string using testarray.toString() before alert. 使用testarray在alert之前使用testarray.toString()转换为字符串。 toString internally joining these items using ',' as separator. toString使用','作为分隔符在内部连接这些项目。 you can convert it into string using Array.join and pass own separator. 您可以使用Array.join将其转换为字符串并传递自己的分隔符。

alert(testarray.join("%"));

you can iterate through the array and insert your characters 你可以遍历数组并插入你的角色

var testarray=new Array("a","b","c");
var str;
for (var i = 0; i < testarray.length; i++) {
  str+=testarray[i]+"%";
}
alert(str);

join method is great, just to supplement that you can add array[0]+array[1]+array[2] only if the number of items is very small. join方法很棒,只是为了补充你只能在项目数量非常小的情况下添加数组[0] +数组[1] +数组[2]。

Also don't forget to put the value to "" in case of javascript array assign "undefined" automatically. 另外,在javascript数组自动分配“undefined”的情况下,不要忘记将值设置为“”。 People may get a problem without doing that. 没有这样做,人们可能会遇到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM