简体   繁体   English

javascript:如何将字符串数组转换为连接以逗号分隔的项目的纯字符串?

[英]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: 我有一个字符串的javascript数组,看起来像:

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. 您可以使用带有"," join作为胶水。

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

join will only add the glue between the array elements. join只会在数组元素之间添加胶水 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: 您可以尝试在一个简单的for循环中串联这些值,如下所示:

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. 这适用于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"]);

暂无
暂无

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

相关问题 如何在 JavaScript 中将逗号分隔的字符串转换为数组 - How to Convert Comma Separated String into an Array in JavaScript 将逗号分隔的字符串转换为 JavaScript 数组 - Convert comma separated string to a JavaScript array 如何在JavaScript中将本地存储的逗号分隔字符串转换为数值数组 - How to convert comma separated string of local storage into numeric array in javascript 如何在 javascript 中将逗号分隔的字符串转换为数字数组 - How to convert comma separated string into numeric array in javascript 如何使用javascript在逗号分隔的字符串中转换json值 - how to convert json values in comma separated string using javascript 如何在不使用.join()的情况下将数组转换为不带逗号的字符串并在javascript中用空格分隔? - How to convert array into string without comma and separated by space in javascript without using .join()? 如何将数组转换为不带逗号的字符串,并在 javascript 中用空格分隔而不连接? - How to convert array into string without comma and separated by space in javascript without concatenation? 使用嵌套数组以逗号分隔的字符串转换JSON - Convert JSON in comma separated string with nested array 如何将逗号分隔的字符串转换为数据数组? - How to convert a string of comma separated values into data array? 如何在 ReactJS 中将二维数组转换为逗号分隔的字符串 - How to convert 2D array in to comma separated string in ReactJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM