我有一个数组
var arr = ["one","two","three","four"];
是否可以通过某些正则表达式将其转换为
"one","two","three","four"
结果不应该是整个字符串,而是逗号分隔的字符串。
任何建议???
答案 0 :(得分: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);
}
答案 1 :(得分:1)
您无法将其转换为以逗号分隔的字符串,只能转换为整个字符串。
使用join()
:
var result = "\"" + array.join("\",\"") + "\"";
答案 2 :(得分: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>
答案 3 :(得分:0)
这样做:
var arr = ["one","two","three","four"];
var str = '"' + arr.join('","') + '"';
console.log(str);
答案 4 :(得分:-1)
在for循环中,您可以单独使用值执行任何操作。
var arr = ["one","two","three","four"];
for (var i = 0; i <= arr.length; i++) {
alert(arr[i]);
}