js 数组,字符串,json互相转换 - 小众知识

js 数组,字符串,json互相转换

2013年01月27日 14:18:05 苏内容
  标签: js/json//转换
阅读:7328

数组转字符串

var arr = [1,2,3,4,'巴德','merge'];var str = arr.join(',');
console.log(str); // 1,2,3,4,巴德,merge

字符串转数组

var str = '1,2,3,4,巴德,merge';var arr = str.split(',');
console.log(arr);     // ["1", "2", "3", "4", "巴德", "merge"]   数组console.log(arr[4]);  // 巴德

字符串转数组,数组转数组格式化,数组格式化转数组

var str = '1,2,3,4,巴德,merge';var arr = str.split(',');var strify = JSON.stringify(arr);
console.log(arr);       // ["1", "2", "3", "4", "巴德", "merge"]   数组console.log(arr[4]);    // 巴德console.log(strify);    // ["1", "2", "3", "4", "巴德", "merge"]   字符串var arrParse = JSON.parse(strify);
console.log(arrParse);  // ["1", "2", "3", "4", "巴德", "merge"]   数组

创建直接的实例

这个例子创建了对象的一个新实例,并向其添加了四个属性:

实例

person=new Object();
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";

js实现数组转换成json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function arrayToJson(o) {
    var r = [];
    if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "object") {
      if (!o.sort) {
        for (var i in o)
          r.push(i + ":" + arrayToJson(o[i]));
        if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
          r.push("toString:" + o.toString.toString());
        }
        r = "{" + r.join() + "}";
      } else {
        for (var i = 0; i < o.length; i++) {
          r.push(arrayToJson(o[i]));
        }
        r = "[" + r.join() + "]";
      }
      return r;
    }
    return o.toString();
  }

作用相当于  JSON.stringify(array);


扩展阅读