在JavaScript中将数组转换为格式化字符串

时间:2016-05-13 04:23:57

标签: javascript arrays

我有一个数组元素

    [{
    "x": 326,
    "y": 176
}, {
    "x": 244,
    "y": 300
}, {
    "x": 189,
    "y": 420
}, {
    "x": 154,
    "y": 546
}, {
    "x": 139,
    "y": 679
}, {
    "x": 152,
    "y": 827
}, {
    "x": 183,
    "y": 954
}, {
    "x": 230,
    "y": 1088
}, {
    "x": 291,
    "y": 1217
}, {
    "x": 365,
    "y": 1333
}, {
    "x": 446,
    "y": 1417
}, {
    "x": 554,
    "y": 1469
}]

我想将此转换为像这样的字符串

"{326,176},{244,300},{189,420},{154,546},{139,679},{152,827},{183,954},  {230,1088},{291,1217},{365,1333},{446,1417},{554,1469}"

我们怎样才能在javascript中实现这一点..在此先感谢..

1 个答案:

答案 0 :(得分:6)

使用Array.prototype.map()Array.prototype.join()的组合,这是一种方法:

var ele = '[{"x":326,"y":176},{"x":244,"y":300},{"x":189,"y":420},{"x":154,"y":546},{"x":139,"y":679},{"x":152,"y":827},{"x":183,"y":954},{"x":230,"y":1088},{"x":291,"y":1217},{"x":365,"y":1333},{"x":446,"y":1417},{"x":554,"y":1469}]';

var array = JSON.parse(ele);
var string = array.map(i => '{' + i.x + ',' + i.y + '}').join(',');

console.log(string);

此输出

{326,176},{244,300},{189,420},{154,546},{139,679},{152,827},{183,954},{230,1088},{291,1217},{365,1333},{446,1417},{554,1469}