1、数组转字符串 join
var aArr = [1,2,2,2,2,3] var sStr = null; sStr = aArr.join("-"); console.log(sStr)//1-2-2-2-2-3 sStr = aArr.join("+"); console.log(sStr)//1+2+2+2+2+3
2、字符串转数组
var sStr = "abc,abcd,aaa"; var aArr = null; aArr = sStr.split(",") console.log(aArr)// ["abc", "abcd", "aaa"] aArr = sStr.split("") console.log(aArr)//["a", "b", "c", ",", "a", "b", "c", "d", ",", "a", "a", "a"] aArr = sStr.split("-") console.log(aArr)//["abc,abcd,aaa"] //字符串转数组通过split参数切割成若干个字符串,并以数组形式返回
3、将JSON字符串对象互转 (注意是JSON字符串)
var oObj = { name:‘北京‘, age:1800, value:‘首都‘ } var sStr = JSON.stringify(oObj); console.log(sStr) //{"name":"北京","age":1800,"value":"首都"} console.log(typeof sStr) //string var sJsonStr = ‘{"name":"北京","age":1800,"value":"首都"}‘ var oJsonObj = JSON.parse(sJsonStr) console.log(oJsonObj) //{name: "北京", age: 1800, value: "首都"} console.log(typeof oJsonObj) //object
4、非字符串通过JSON.parse转对象
var sString = ‘121212‘ var sJsonString = JSON.parse(sString) console.log(sJsonString)//121212 console.log(typeof sJsonString) //number var sString = ‘nanjign‘ var sJsonString = JSON.parse(sString) //Uncaught SyntaxError: Unexpected token a in JSON at position 1
通过运行代码得知,js对字符串能转换就转换为其他类型是数据。尽量不报错,仁至义尽。
原文地址:https://www.cnblogs.com/bigDipper/p/9169143.html
时间: 2024-11-05 13:39:14