Skip to content

__spreadArray不符合预期 #282

@rabit2022

Description

@rabit2022
// iife file test1.jsfl
(function () {
    const set = new Set();
    set.add(0);
    set.add(1);

    // 1.应该使用的方法
    const arr = Array.from(set);
    console.log(arr);


    var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {

        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
            if (ar || !(i in from)) {
                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                ar[i] = from[i];
            }
        }
        return to.concat(ar || Array.prototype.slice.call(from));
    };
    const arr2 = __spreadArray([],set,true)
    console.log(arr2);

    // 源代码
    console.log([...set])
})();

[ 0, 1 ]
[]
[ 0, 1 ]

[...set] 被翻译为 __spreadArray,但是set.length是undefined,返回[],不符合预期

可以添加以下代码(babel helpers方法)

function _iterableToArray(r) {if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions