首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Symbol.isConcatSpreadable

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

| Symbol.isConcatSpreadable属性的属性特性: |

|:----|

| Writable | no |

| Enumerable | no |

| Configurable | no |

描述

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

  • 对于数组对象,默认情况下,用于concat时,会按数组元素展开然后进行连接(数组元素作为新数组的元素)。重置Symbol.isConcatSpreadable可以改变默认行为。

  • 对于类似数组的对象,用于concat时,该对象整体作为新数组的元素,重置Symbol.isConcatSpreadable可改变默认行为。

示例

数组

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

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

var alphaNumeric = alpha.concat(numeric); 

console.log(alphaNumeric); // Result: ['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); // Result: ['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"]

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Symbol.isconcatspreadable' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'Symbol.isconcatspreadable' in that specification.

Draft

No change.

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

48

(Yes)

48 (48)

No support

No support

No support

Feature

Android

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

No support

No support

(Yes)

48.0 (48)

No support

No support

No support

扫码关注腾讯云开发者

领取腾讯云代金券