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);