3

我有一个数组

var arr = ["one","two","three","four"];

是否可以通过一些正则表达式来转换它

"one","two","three","four"

结果不应该是整个字符串,而是逗号分隔的字符串。

有什么建议么 ???

4

5 回答 5

3

function func(){
   var arr = ["one","two","three","four"];
   var result = "";
   for (var i = 0; i <= arr.length - 1; i++) {
       result += '"' + arr[i] + '",';
   }
   result = result.substring(0, result.length - 1);
   alert(result);
}

于 2012-11-01T09:49:10.200 回答
1

您不能将其转换为逗号分隔的字符串,只能转换为整个字符串。

用于join()

var result = "\"" + array.join("\",\"") + "\"";
于 2012-11-01T09:44:14.930 回答
0

做这个:

var arr = ["one","two","three","four"];
var str = '"' + arr.join('","') + '"';
console.log(str);

演示

于 2012-11-01T09:58:54.923 回答
0
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to convert the array into a String.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>

</body>
</html>
于 2012-11-01T09:40:36.263 回答
-1

在 for 循环中,您可以分别对值执行任何操作。

var arr = ["one","two","three","four"];
for (var i = 0; i <= arr.length; i++) {
    alert(arr[i]);
}
于 2012-11-01T09:40:45.117 回答