Skip to content
kaba

扩展运算符源码及实现

源码1 min read

1const a = {b:1};
2console.log(...a);

es6->es5 如下:

1"use strict";
2
3var _console;
4
5function _toConsumableArray(arr) {
6 return _arrayWithoutHoles(arr) ||
7 _iterableToArray(arr) ||
8 _unsupportedIterableToArray(arr) ||
9 _nonIterableSpread();
10}
11
12function _nonIterableSpread() {
13 //如果是不可遍历的报错
14 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
15}
16
17function _unsupportedIterableToArray(o, minLen) {
18 if (!o) return;
19 if (typeof o === "string")
20 return _arrayLikeToArray(o, minLen);
21 //截取[object, Object]prototype的类型并赋值给n
22 var n = Object.prototype.toString.call(o).slice(8, -1);
23 if (n === "Object" && o.constructor) n = o.constructor.name;
24 //类数组结构没有 Iterator 接口,需要转换为数组
25 if (n === "Map" || n === "Set") return Array.from(o);
26 //n为参数
27 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
28 return _arrayLikeToArray(o, minLen);
29}
30
31function _iterableToArray(iter) {
32 //可遍历的转换为数组
33 if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter))
34 return Array.from(iter);
35}
36
37function _arrayWithoutHoles(arr) {
38 if (Array.isArray(arr))
39 return _arrayLikeToArray(arr);
40}
41
42function _arrayLikeToArray(arr, len) {
43 if (len == null || len > arr.length)
44 len = arr.length;
45 //遍历赋值
46 for (var i = 0, arr2 = new Array(len); i < len; i++) {
47 arr2[i] = arr[i];
48 }
49 return arr2;
50}
51
52var a = {
53 b: '1'
54};
55
56(_console = console).log.apply(_console, _toConsumableArray(a));