简体   繁体   中英

javascript: How to convert a array of string into a pure string that concatenate the items separated by comma?

I have an javascript array of string that looks like:

A = ['a', 'b', 'c'];

I want to convert it to (all string):

strA = '"a","b","c"'

How do I achieve this?

You can use join with "," as glue.

var strA = '"' + A.join('","') + '"';

join will only add the glue between the array elements. So, you've to add the quotes to start and end of it.

Try this

A = ['a', 'b', 'c'];
A.toString();
alert(A);

You could try just concatenating the values in a simple for loop something like this:

var array = ["1", "a", 'b'];
var str = '';
for (var i = 0; i<array.length; i++){
  str += '"' + array[i] + '",';
}
str = str.substring(0, str.length - 1);

or if you're feeling crazy you could do :

   str = JSON.stringify(array)
   str = str.substring(1, str.length -1);

Do you mean something like this? This works in chrome.

function transformArray(ar) {
  var s = ar.map(function (i) { 
    return "\"" + i + "\","; })
  .reduce(function(acc, i) { 
    return acc + i; 
  });
  return s.substring(0, s.length-1);
}

transformArray(["a", "b", "c"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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