Symbol.isConcatSpreadable
Symbol.isConcatSpreadable
静态数据属性代表 众所周知的符号 Symbol.isConcatSpreadable
。Array.prototype.concat()
方法在连接的每个对象上查找此符号,以确定是否应将其视为类似数组的对象并展平为其数组元素。
¥The Symbol.isConcatSpreadable
static data property represents the well-known symbol Symbol.isConcatSpreadable
. The Array.prototype.concat()
method looks up this symbol on each object being concatenated to determine if it should be treated as an array-like object and flattened to its array elements.
Try it
值
描述
¥Description
[Symbol.isConcatSpreadable]
属性可以定义为自身或继承的属性,其值为布尔值。它可以控制数组和类数组对象的行为:
¥The [Symbol.isConcatSpreadable]
property can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects:
- 对于数组对象,默认行为是展开(展平)元素。在这些情况下,
Symbol.isConcatSpreadable
可以避免扁平化。 - 对于类似数组的对象,默认行为是不展开或展平。在这些情况下,
Symbol.isConcatSpreadable
可以强制展平。
示例
数组
¥Arrays
默认情况下,Array.prototype.concat()
将数组展开(展平)到其结果中:
¥By default, Array.prototype.concat()
spreads (flattens) arrays into its result:
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
时,你可以禁用默认行为:
¥When setting Symbol.isConcatSpreadable
to false
, you can disable the default behavior:
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] ]
类似数组的对象
¥Array-like objects
对于类似数组的对象,默认是不扩散。需要将 Symbol.isConcatSpreadable
设置为 true
才能获得展平数组:
¥For array-like objects, the default is to not spread. Symbol.isConcatSpreadable
needs to be set to true
in order to get a flattened array:
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
表示必须添加两个属性。¥Note: The
length
property is used to control the number of object properties to be added. In the above example,length:2
indicates two properties has to be added.
规范
Specification |
---|
ECMAScript Language Specification # sec-symbol.isconcatspreadable |
浏览器兼容性
BCD tables only load in the browser