扩展运算符原理及实现

date
Dec 22, 2020
slug
kuozhanyunsuanfu
status
Published
tags
JavaScript
源码
summary
从源码看扩展运算符的实现
type
Post
const a = {b:1};
console.log(...a);
es6->es5 如下:
"use strict";

var _console;

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) ||
    _iterableToArray(arr) ||
    _unsupportedIterableToArray(arr) ||
    _nonIterableSpread();
}

function _nonIterableSpread() {
  //如果是不可遍历的报错
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string")
    return _arrayLikeToArray(o, minLen);
  //截取[object, Object]prototype的类型并赋值给n
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  //类数组结构没有 Iterator 接口,需要转换为数组
  if (n === "Map" || n === "Set") return Array.from(o);
  //n为参数
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}

function _iterableToArray(iter) {
  //可遍历的转换为数组
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter))
    return Array.from(iter);
}

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr))
    return _arrayLikeToArray(arr);
}

function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length)
    len = arr.length;
  //遍历赋值
  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }
  return arr2;
}

var a = {
  b: '1'
};

(_console = console).log.apply(_console, _toConsumableArray(a));

© kaba 2019 - 2022