JavaScript - Symbol.isConcatSpreadable 属性
Symbol.isConcatSpreadable 属性用于自定义对象作为参数传递给 Array.prototype.concat() 方法时的行为。如果我们尝试对数组调用 concat(),它会自动展平嵌套数组。但是,如果我们尝试将对象而不是数组传递给 concat(),它将被视为单个对象,而不会展平。如果您想以展平对象内数组的方式连接数组,这可能会导致问题。
这时就需要使用 Symbol.isConcatSpreadable 了。当对象的 symbol 属性设置为 true 时,这意味着 concat() 在传递给该对象时应该展平该对象。该对象将作为单个项目处理,如果设置为 false 或不存在,则不会被展平。
语法
以下是 JavaScript Symbol.isConcatSpreadable 属性的语法 -
Array[Symbol.isConcatSpreadable]
参数
此属性不接受任何类型的参数。
返回值
此属性返回连接结果。
示例
示例 1
让我们看下面的示例,我们将使用 isConcatSpreadle 并将数组设置为 false。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
Symbol.prototype.lengthx = function() {
return this.description.length;
};
const a = Symbol('TutorialsPoint');
document.write(a.lengthx());
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示该数字。
示例 2
考虑另一种场景,我们将使用 isConcatSpreadable 并将数组设置为 true。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = ['a', 'b', 'c'];
const y = [1, 4, 3];
y[Symbol.isConcatSpreadable] = true;
const result = x.concat(y);
document.write(JSON.stringify(result));
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将使用 isConcatSpreadable 和 Array.from() 方法。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
length: 3,
0: 'Rabbit',
1: 'Fox',
2: 'Lion',
[Symbol.isConcatSpreadable]: true
};
const a = ['Carrot'];
const result = Array.from(a).concat(x);
document.write(JSON.stringify(result));
</script>
</body>
</html>
当我们执行脚本时,它将在网页上显示一段文本。

