有些地方我将数组更改为像对象这样的数组:
let arr = ['a','b']
let arrLike = {...arr, length: arr.length}
console.log(arrLike)
> {0: "a", 1: "b", length: 2}
它并不完美,但这允许我通过使用合并来覆盖数组。即:
> let a1 = [1,2,3], b1 = [1,2,3]
> Object.assign(a1, arr)
[ 'a', 'b', 3 ]
> Object.assign(b1, arrLike)
[ 'a', 'b']
这是可取的,但我也想让concat工作,
['z'].concat(arr)
> ["z", "a", "b"] // good
['z'].concat(arrLike)
> ["z", {0: "a", 1: "b" length: 2}] // bad
无论如何都要修改arrLike
以使concat起作用吗?
答案 0 :(得分:6)
您需要定义Symbol.isConcatSpreadable
以告诉concat()
将其视为类似数组:
arrLike[Symbol.isConcatSpreadable] = true;
示例:
let arr = ['a','b'];
let arrLike = {
...arr,
length: arr.length,
[Symbol.isConcatSpreadable]: true
};
console.log(['z'].concat(arrLike))