实现说明
演示用的数据放在这几个模块级绑定中:arrayLike、squares。
模块级对象字面量,键名固定:length。
使用要点
- 每一步打印都带着自己的标签:
array-like:、squares:、set:。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 状态都挂在模块顶层:arrayLike、squares。
核心语句
const squares = Array.from({ length: 5 }, (_, i) => i * i);
代码示例
// 类数组(length + 索引)转真数组:Array.from 按位读取
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
console.log('array-like:', Array.from(arrayLike));
// 第二个参数 mapFn 边遍历边构造,省掉中间数组
const squares = Array.from({ length: 5 }, (_, i) => i * i);
console.log('squares:', squares);
// 可迭代对象同样适用:Set 去重、Map 拆回键值对
console.log('set:', Array.from(new Set([1, 2, 2, 3])));
console.log('map pairs:', Array.from(new Map([['a', 1], ['b', 2]])));
// 字符串按码点迭代:emoji 不会被拆成代理对
console.log('codepoints:', Array.from('a\u{1F44D}b').length);