实现说明
顶层就这几处状态:steps、glyphs、squares。
使用要点
- 跑完文件,输出里会留下标记——
steps:、glyphs:、code units:。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件用顶层绑定保存自己的状态:steps、glyphs、squares。
核心语句
const squares = Array.from(new Set([3, 1, 3, 2]), (n) => n * n);
const steps = Array.from({ length: 5 }, (_, i) => (i + 1) * 10);
代码示例
// Array.from({length}) 先造出稀疏壳,第二个参数 mapFn 逐位填值
const steps = Array.from({ length: 5 }, (_, i) => (i + 1) * 10);
console.log('steps:', steps);
// 从字符串按码点展开:emoji 代理对保持完整,不会被拆成两个元素
const glyphs = Array.from('a😀b');
console.log('glyphs:', glyphs, 'length:', glyphs.length);
// 对照:按 UTF-16 码元切分会把 😀 撕成两个孤立代理项
console.log('code units:', 'a😀b'.split(''), 'length:', 'a😀b'.split('').length);
// 从 Set 等可迭代对象转换,mapFn 顺手加工每个元素
const squares = Array.from(new Set([3, 1, 3, 2]), (n) => n * n);
console.log('squares:', squares);