js字符串转数组,转对象⽅法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) //stringjson检查
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对字符串能转换就转换为其他类型是数据。尽量不报错,仁⾄义尽。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论