Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

为什么array.concat(obj)需要设置obj的@@isConcatSpreadable和length后才能正常的执行?

执行如下代码:

const array = ['a', 'b', 'c'];
let obj = {0:1,1:2 }
console.log(array.concat(obj));

// 设置 obj 的 @@isConcatSpreadable
obj[Symbol.isConcatSpreadable] = true;
console.log(array.concat(obj));

// newObj同时存在length和@@isConcatSpreadable
let newObj = {0:1,1:2,length:2 }
newObj[Symbol.isConcatSpreadable] = true;
console.log(array.concat(newObj));

其输出为

["a", "b", "c", { 0: 1, 1: 2 }]
["a", "b", "c"]
["a", "b", "c", 1, 2]

为什么需要同时设置obj[Symbol.isConcatSpreadable]length后才能如期望的执行concat?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

数组的 concat() 实例方法的参数,要么是新的元素,要么是新的数组。
一般来说,对象作为数组的 concat() 实例方法的参数,相当于一个独立的新元素。
但是把一个特殊的类数组对象传入,同时该对象还实现了 [Symbol.isConcatSpreadable] API,意味着对象作为被数组的 concat() 实例方法使用的时候允许被展开,相当于 array.concat(...newObj),从该 [Symbol.isConcatSpreadable] 的接口名字就能看出。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...