美文网首页前端大牛
Array.prototype.concat 妙用

Array.prototype.concat 妙用

作者: lip2up | 来源:发表于2018-04-02 17:16 被阅读3次

将单个值,变成数组处理

function foo(val) {
    const list = [].concat(val)
}

如果参数 val 是单个值,则 list[ val ],如果是数组,则 list 就等于该数组,相当于以下代码:

function foo(val) {
    const list = val instanceof Array ? val : [ val ]
}

这是因为,concat 具有一个很大的特性:

[].concat(1)          => [1]
[].concat([1, 2, 3])  => [1, 2, 3]

另,还可以利用 concat 的这种特性,实现数组平坦化(flat)

a = [[1, 2], [3, 4]]
[].concat.apply([], a)  // [1, 2, 3, 4]

相关文章

网友评论

    本文标题:Array.prototype.concat 妙用

    本文链接:https://www.haomeiwen.com/subject/dryxhftx.html