使用JavaScript将逗号分隔的数组减少为字符串

时间:2018-07-05 11:20:23

标签: javascript

我想将响应数组转换为逗号分隔的字符串或数字。有什么可行的方法吗? 实际数据:[521,221,623]

预期数据: 521,221,623 '521','221','623'

我尽力了。但是我没有实现。任何建议或意见,不胜感激。

3 个答案:

答案 0 :(得分:1)

获得字符串521,221,623

var arr = [521,221,623]; // your array
var str = arr.join(","); // join each element of array with a separator 
console.log(str); // check it in console

要获取第二个字符串“ 521”,“ 221”,“ 623”

var arr = [521,221,623]; // your original array.
var newArr = arr.map( (num)=> { return "'" + num + "'" }).join(","); // map is used to iterate each element and manipulate if needed
console.log(newArr);

API ref:mapjoin

答案 1 :(得分:1)

使用Array.join()

const x = [521,221,623];
console.log("'"+x.join("','")+"'");

答案 2 :(得分:0)

const res = [521,221,623].map(x => `'${x}'`).join(',')

const res = [521,221,623].map(x => `'${x}'`).join(',')
console.log(res);