Symbol.isConcatSpreadable
Symbol.isConcatSpreadable 静态数据属性表示内置的 Symbol Symbol.isConcatSpreadable。当使用 Array.prototype.concat() 方法进行连接时,它会查找要连接的每个对象上的此 Symbol,以确定该对象是否应被视为类数组对象并展平为数组元素。
试一试
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];
let alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric);
// Expected output: Array ["a", "b", "c", 1, 2, 3]
numeric[Symbol.isConcatSpreadable] = false;
alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric);
// Expected output: Array ["a", "b", "c", Array [1, 2, 3]]
值
内置的 Symbol Symbol.isConcatSpreadable。
Symbol.isConcatSpreadable 的属性特性 | |
|---|---|
| 可写 | 否 |
| 可枚举 | 否 |
| 可配置 | 否 |
描述
[Symbol.isConcatSpreadable] 属性可以定义为自身属性或继承属性,其值为布尔值。它可以控制数组和类数组对象的行为。
- 对于数组对象,默认行为是展开(展平)元素。
Symbol.isConcatSpreadable可以避免在这种情况下进行展平。 - 对于类数组对象,默认行为是不展开或展平。
Symbol.isConcatSpreadable可以强制在这种情况下进行展平。
示例
数组
默认情况下,Array.prototype.concat() 会将数组展开(展平)到其结果中。
js
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];
const alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
当将 Symbol.isConcatSpreadable 设置为 false 时,您可以禁用默认行为。
js
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];
numeric[Symbol.isConcatSpreadable] = false;
const alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Result: ['a', 'b', 'c', [1, 2, 3] ]
类数组对象
对于类数组对象,默认是不展开。需要将 Symbol.isConcatSpreadable 设置为 true 才能获得展平后的数组。
js
const x = [1, 2, 3];
const fakeArray = {
[Symbol.isConcatSpreadable]: true,
length: 2,
0: "hello",
1: "world",
};
x.concat(fakeArray); // [1, 2, 3, "hello", "world"]
注意:length 属性用于控制要添加的对象属性的数量。在上面的示例中,length:2 表示必须添加两个属性。
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-symbol.isconcatspreadable |
浏览器兼容性
加载中…