内置的Symbol.isConcatSpreadable符号用于配置某对象作为Array.prototype.concat()方法的参数时是否展开其数组元素。

Symbol.isConcatSpreadable 属性的属性特性:
writable false
enumerable false
configurable false

描述

@@isConcatSpreadable 符号 (Symbol.isConcatSpreadable) 可以直接定义为对象属性或继承而来,它是布尔类型。它可以控制数组或类似数组(array-like)的对象的行为:

示例

数组

默认情况下,Array.prototype.concat() 展开其元素连接到结果中:

var alpha = ['a', 'b', 'c'], 
    numeric = [1, 2, 3]; 

var alphaNumeric = alpha.concat(numeric); 

console.log(alphaNumeric); // 结果: ['a', 'b', 'c', 1, 2, 3]

设置Symbol.isConcatSpreadablefalse

var alpha = ['a', 'b', 'c'], 
    numeric = [1, 2, 3]; 

numeric[Symbol.isConcatSpreadable] = false;
var alphaNumeric = alpha.concat(numeric); 

console.log(alphaNumeric); // 结果: ['a', 'b', 'c', [1, 2, 3] ]

Array-like 对象

对于类数组 (array-like)对象,默认不展开。期望展开其元素用于连接,需要设置 Symbol.isConcatSpreadable 为true:

var x = [1, 2, 3];

var fakeArray = { 
  [Symbol.isConcatSpreadable]: true, 
  length: 2, 
  0: "hello", 
  1: "world" 
}

x.concat(fakeArray); // [1, 2, 3, "hello", "world"]

技术标准

标准 状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
Symbol.isconcatspreadable
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
Symbol.isconcatspreadable
Draft No change.

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 未实现 48 (48) 未实现 未实现 未实现
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 未实现 48.0 (48) 未实现 未实现 未实现

参考