JS 难点攻克

汇聚各个时间段,关于 JS 的一些难点问题,他们掌握之后又很容易忘记,全部汇总在这里

JSON.stringify 循环引用问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getCircularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (['components', '$progress', 'instances', 'matched'].includes(key)) {
return '[ignore]';
} else if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]'; // 或者 return undefined; 表示跳过这个属性
}
seen.add(value);
}
return value;
};
}
console.log('pushTabs', JSON.stringify(this.$route, getCircularReplacer(), 2));

Date 对象保留日期部分,去除时间部分

通常操作如下:

1
2
3
4
5
6
date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
console.log('date', date.toLocaleString());

优雅的操作如下

1
2
3
date = new Date();
date.setHours(0, 0, 0, 0);
console.log('date', date.toLocaleString());

创建指定长度的数组

在 JavaScript 中,有多种方式可以创建指定长度的数组。以下是一些常用的方法:

  1. 使用 Array 构造函数:
    1
    2
    3
    const length = 10;
    const array = new Array(length);
    console.log(array); // 输出: [empty × 10]

这种方法只是构建一个长度为10,却没有元素的数组,使用 foreach,map 等循环不会执行。

  1. 使用 Array.from:

    1
    2
    3
    const length = 10;
    const array = Array.from({ length: length });
    console.log(array); // 输出: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
  2. 使用 fill 方法初始化数组:

    1
    2
    3
    const length = 10;
    const array = new Array(length).fill(0);
    console.log(array); // 输出: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  3. 使用扩展运算符 (spread operator) 和 Array.keys:

    1
    2
    3
    const length = 10;
    const array = [...Array(length)];
    console.log(array); // 输出: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
  4. 使用 map 方法初始化数组:

    1
    2
    3
    const length = 10;
    const array = Array(length).fill().map((_, i) => i);
    console.log(array); // 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]