# 【JavaScript】什么是扩展运算符？

1. 创建一个数组 `middle`

2. 再创建一个数组把`middle`包含进去

3. 打印出结果

``````var middle = [3, 4];
var arr = [1, 2, middle, 5, 6];
``````
``````console.log(arr);
// [1, 2, [3, 4], 5, 6]
``````

``````var middle = [3, 4];
var arr = [1, 2, ...middle, 5, 6];
``````
``````console.log(arr);
// [1, 2, 3, 4, 5, 6]
``````

## 复制数组

`slice()`是JS数组的一个方法，它可以复制数组，类似的方法，我们可以使用扩展运算符来复制数组：

``````var arr = ['a', 'b', 'c'];
var arr2 = [...arr];
``````
``````console.log(arr2);
// ['a', 'b', 'c']
``````

`arr`数组被分解成单个字母，然后被分配给`arr2`数组。现在我们对`arr2`数组做任何改变都不会影响`arr`源数组。

``````var arr = ['a', 'b', 'c'];
var arr2 = arr;
``````
``````console.log(arr2);
// ['a', 'b', 'c']
``````

``````arr2.push('d');
``````
``````console.log(arr2);
// ['a', 'b', 'c', 'd']
``````
``````console.log(arr);
// ['a', 'b', 'c', 'd']
``````

## 连接数组

``````var arr = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

**arr1 = arr.concat(arr2);**
console.log(arr);
// ['a', 'b', 'c', 'd', 'e', 'f']
``````

``````var arr = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
``````
``````**arr = [...arr, ...arr2];**
console.log(arr);
// ['a', 'b', 'c', 'd', 'e', 'f']
``````

## Math

`Math.max()`会返回一堆数字中最大的数。

``````Math.max();
// -Infinity
``````
``````Math.max(1, 2, 3);
// 3
``````
``````Math.max(100, 3, 4);
// 100
``````

``````var arr = [2, 4, 8, 6, 0];
``````
``````function max(arr) {
return Math.max.apply(null, arr);
}
``````
``````console.log(max(arr));
// 8
``````

``````var arr = [2, 4, 8, 6, 0];
var max = Math.max(...arr);
``````
``````console.log(max);
// 8
``````

## 字符串转换数组

``````var str = "hello";
var chars = [...str];
``````
``````console.log(chars);
// ['h', 'e',' l',' l', 'o']
``````