js数据类型之间的转换

92 阅读1分钟

数组 ↔ 字符串

数组转字符串

1.toString()

const arr = [1, 2, 3];
const str = arr.toString(); // "1,2,3"

2.join(separator)

const arr = [1, 2, 3];
const str = arr.join("-"); // "1-2-3"

字符串转数组

1.split(separator)

const str = "1,2,3";
const arr = str.split(","); // ["1","2","3"]

2.扩展运算符 / Array.from()(把每个字符拆成数组)

const str = "hello";
const arr = [...str]; // ["h","e","l","l","o"]
const arr2 = Array.from(str); // ["h","e","l","l","o"]

对象 ↔ 数组

###对象转数组

1.Object.keys(obj) → 获取键数组

const obj = {a: 1, b: 2};
Object.keys(obj); // ["a", "b"]

2.Object.values(obj) → 获取值数组

Object.entries(obj); // [["a",1], ["b",2]]

3.Object.entries(obj) → 获取键值对数组

Object.entries(obj); // [["a",1], ["b",2]]

数组转对象

1.通过 Object.fromEntries() (数组是 [key, value] 的形式)

const arr = [["a", 1], ["b", 2]];
const obj = Object.fromEntries(arr); // {a:1, b:2}

2.使用 reduce 手动转换

const arr = [["a",1],["b",2]];
const obj = arr.reduce((acc, [k,v]) => (acc[k]=v, acc), {});

对象 ↔ 字符串

对象转字符串

1.JSON.stringify()

const obj = {a:1, b:2};
const str = JSON.stringify(obj); // '{"a":1,"b":2}'

字符串转对象

1.JSON.parse()

const str = '{"a":1,"b":2}';
const obj = JSON.parse(str); // {a:1, b:2}

数组 ↔ 对象(特殊情况)

  • 如果数组是 [value1, value2,...],想转对象可以:
const arr = ["a","b","c"];
const obj = {...arr}; // {0:"a", 1:"b", 2:"c"}
  • 对象的值或键转数组可用前面 Object.keys/values/entries。

总结表格

转换类型方法
数组 → 字符串toString() / join()
字符串 → 数组split() / [...str] / Array.from(str)
对象 → 数组Object.keys() / Object.values() / Object.entries()
数组 → 对象Object.fromEntries() / reduce / 扩展运算符 {...arr}
对象 → 字符串JSON.stringify()
字符串 → 对象JSON.parse()