null和undefined的区别、数组和伪数组的区别

null和undefined的区别

undefined:

字面意思是未定义的值,语义是希望表示一个变量最原始的状态,而非人为操作的结果。这种原始状态会在以下四个场景中出现:

  • 声明了一个变量但没有赋值
  • 访问对象上不存在的属性
  • 函数定义了形参,但是没有传递实参
  • 使用void对表达式求值

null:

字面意思是空值,语义是希望表示一个对象被人为的重置为空对象,而非一个变量最原始的状态。在内存中的表示就是栈中的变量没有指向堆中的内存对象。

null有属于自己的数据类型NULL,而不是Object类型。

typeof为什么会将null判定为Object类型?

因为JS数据类型在底层都是以二进制的形式表示的,二进制的前三位为0就会被typeof判断为Object类型,而null的二进制恰好都是0,因此null被误判为Object类型。


数组和(类)伪数组的区别

数组:

数组是一个特殊对象,与常规对象的区别:

  • 有新的元素添加到列表中的时候,自动更新length属性
  • 设置length属性,可以截断数组
  • 从Array.prototype中继承了方法
  • 属性为Array

类数组:

类数组是一个拥有length属性,并且他属性为非负整数的普通对象,类数组不能直接调用数组方法。


区别:

类数组是简单对象,它的原型关系和数组不同

// 原型关系和原始值转换
let arrayLike = {
    length: 10,
};
console.log(arrayLike instanceof Array); // false
console.log(arrayLike.__proto__.constructor === Array); // false
console.log(arrayLike.toString()); // [object Object]
console.log(arrayLike.valueOf()); // {length: 10}

let array = [];
console.log(array instanceof Array); // true
console.log(array.__proto__.constructor === Array); // true
console.log(array.toString()); // ''
console.log(array.valueOf()); // []

类数组转换为数组

转换方法:

  • 使用Array.from()
  • 使用Array.prototype.slice.call()
  • 使用Array.prototype.forEach()进行属性遍历并且组成新的数组

转换须知:

  • 转换后的数组长度由length决定。索引不连续的时候,转换结果是连续的,会自动补位。
    • let al1 = {
          length: 4,
          0: 0,
          1: 1,
          3: 3,
          4: 4,
          5: 5,
      };
      console.log(Array.from(al1)) // [0, 1, undefined, 3]
      
  • 仅考虑0或者正整数的索引
    • // 代码示例
      let al2 = {
          length: 4,
          '-1': -1,
          '0': 0,
          a: 'a',
          1: 1
      };
      console.log(Array.from(al2)); // [0, 1, undefined, undefined]
      
  • 使用slice转换产生稀疏数组(就是数组实际个数 < length的数组,如下例)
    • let al2 = {
          length: 4,
          '-1': -1,
          '0': 0,
          a: 'a',
          1: 1
      };
      console.log(Array.from(al2)); //[0, 1, empty × 2]
      
  • 使用数组方法操作类数组需要注意的地方
    • let arrayLike2 = {
        2: 3,
        3: 4,
        length: 2,
        push: Array.prototype.push
      }
      
      // push 操作的是索引值为 length 的位置
      arrayLike2.push(1);
      console.log(arrayLike2); // {2: 1, 3: 4, length: 3, push: ƒ}
      arrayLike2.push(2);
      console.log(arrayLike2); // {2: 1, 3: 2, length: 4, push: ƒ}
      
posted @ 2022-08-26 08:55  笔下洛璃  阅读(587)  评论(0编辑  收藏  举报