JS 难点攻克
三月 15, 2023
1916
汇聚各个时间段,关于 JS 的一些难点问题,他们掌握之后又很容易忘记,全部汇总在这里
JSON.stringify 循环引用问题
1 | function getCircularReplacer() { |
Date 对象保留日期部分,去除时间部分
通常操作如下:
1 | date = new Date(); |
优雅的操作如下
1 | date = new Date(); |
创建指定长度的数组
在 JavaScript 中,有多种方式可以创建指定长度的数组。以下是一些常用的方法:
- 使用
Array
构造函数:1
2
3const length = 10;
const array = new Array(length);
console.log(array); // 输出: [empty × 10]
这种方法只是构建一个长度为10,却没有元素的数组,使用 foreach,map 等循环不会执行。
使用
Array.from
:1
2
3const length = 10;
const array = Array.from({ length: length });
console.log(array); // 输出: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]使用
fill
方法初始化数组:1
2
3const length = 10;
const array = new Array(length).fill(0);
console.log(array); // 输出: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]使用扩展运算符 (
spread operator
) 和Array.keys
:1
2
3const length = 10;
const array = [...Array(length)];
console.log(array); // 输出: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]使用
map
方法初始化数组:1
2
3const length = 10;
const array = Array(length).fill().map((_, i) => i);
console.log(array); // 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- 本文作者:scwang90
- 本文链接:https://blog.scwang90.cn/2023/03/15/breakthrough-js/index.html
- 版权声明:本分享所有文章均采用 BY-NC-SA 许可协议,转载请注明出处!