一,数组转字符串 (三种方法)
数组方法 | 说明 |
---|---|
toString() | 用于把一个逻辑值转换为字符串,并返回结果 |
toLocaleString() | 把数组转换成本地约定的字符串 |
join() | 用于把数组中的所有元素放入一个字符串 |
1. toString()
let a = ["01", "02", "03", "04", "05"];
let b = a.toString();
console.log(b);
toString()方法不可以指定分隔符,但是我们可以通过replace()方法指定替换
g:代表全局匹配
i:代表忽略大小写
gi:代表全局匹配+忽略大小写
let a = ["01", "02", "03", "04", "05"];
let c = a.toString().replace(/,/gi,'-')
console.log(c);
2. join()
- 元素是通过指定的分隔符进行分隔的
- 默认用逗号进行分隔,分隔符可以自定义修改 如:( , - 。 ! )等
let a = ["01","02","03","04","05"]
let b = a.join()
console.log(b)
二,字符串转数组(2种方法)
1. split()
-
把一个字符串分割成字符串数组
let a = "01,02,03,04";
let b = a.split(",");
console.log(b);
split()方法 | 说明 | 代码呈现 |
---|---|---|
split() | 默认逗号分隔 | ['01', '02', '03', '04'] |
split(’,’) 逗号 | 默认分割 | ['01', '02', '03', '04'] |
split(’ ')空字符串 | 每个字符之间都会被分割 | ['0', '1', ',', '0', '2', ',', '0', '3', ',', '0', '4' |
2. 扩展运算符
-
es6里面的扩展运算符
let arr = "01,02,03,04";
let nawStr = [...arr.split(",")];
console.log(nawStr);
['01', '02', '03', '04']
let arr = "01,02,03,04";
let nawStr = [...arr];
console.log(nawStr);
['0', '1', ',', '0', '2', ',', '0', '3', ',', '0', '4']
三,JSON字符串转成对象
JSON.parse()
JSON.parse()
方法用来解析 JSON 字符串,就是把JSON字符串转成对象。
let myObject = '{"name":"zs","age":18}'
console.log(JSON.parse(myObject)) // {name: 'zs', age: 18}
let imgs = this.rowData.image //字符串类型
this.ruleForm.ctupian = JSON.parse(imgs)
console.log("图片",this.ruleForm.ctupian)