0%

ES6的剩余运算符“...”

...语法一般用于三种情况:

  1. ​ 对于不确定参数数量的函数
1
2
3
4
5
6
function sum(...num)
{
return num.reduce((cur, next) => cur + next);
}
console.log(1, 2, 3);
//expected output: 6
  1. 快速创建数组, ...运算符可以将任意可枚举的对象转换为数组
1
2
3
4
5
6
7
8
9
function example()
{
return [...arguments];
}
console.log(example(a,b,c));
//expected output: ['a','b','c']
//对string也适用
console.log([...'hello']);
//expected output: ['h','e','l','l','o'];
  1. 合并数组
1
2
3
var all = [1, ...[2,3], 4, 5];
console.log(all);
//expected output: [1,2,3,4,5]

所以,我对...运算符粗浅的看做未知数量的可迭代对象。

示例:这个代码是根据传入的字符串返回它的摩斯密码形式

使用...

1
2
3
4
5
6
7
8
9
var uniqueMorseRepresentations = function (words) {
var mosmap = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
var str = words.map(res => {
var s = ''
res.split('').map(r => {s += mosmap[r.charCodeAt() - 97]})
return s
})
return [...new Set(str)].length //就是这里看不懂
};

未使用...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var uniqueMorseRepresentations = function(words) {
const morseCode = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
let map = {};
let num = 0;
let morse = '';
for(let i = 0; i < words.length; i++)
{
for(let j = 0; j < words[i].length; j++)
{
morse += morseCode[words[i].charCodeAt(j) - 97];
}

console.log(morse);
if(!map[morse])
{
map[morse] = 1;
num++;
}
morse = '';
}
return num;
}