JS数据类型的相互转换(持续更新...)

36 阅读1分钟
1. 各结构的转换(Map,Obj,Set,Array)
  • map类型转为数组: Array.from()

方法1:

const m1 = new Map([['a',1],['b',2],['c',3]]);
Array.from(m1);

方法2:

const m1 = new Map([['a',1],['b',2],['c',3]]);
[...m1];
  • map类型转为object: Object.fromEntries()
const m1 = new Map([['a',1],['b',2],['c',3]]);
Object.fromEntries(m1);  // 处理map到对象的方式 , key+value
  • object转为map: new Map(Object.entries())
let obj = {"name":"jindu", "qq":"2429462491"};
new Map(Object.entries(obj));
  • set类型转为数组: Array.from()

方法1:

const set = new Set([1, 2, 3, 4, 5]);
Array.from(set);

方法2:

const set = new Set([1, 2, 3, 4, 5]);
[…set];