Scenario 1: Turn a string into a number
normal operation
let str = '2'
console.log(Number(str)) //2
Sao operation one
let str = '2'
console.log(~~str) //2
~~ The function of ~~ is to remove the decimal part, for positive numbers, round down; for negative numbers, round up; different from Math. integer part
The non-numeric value is 0, which is specifically
~~null; // => 0
~~undefined; // => 0
--NaN; // => 0
~~0; // => 0
~~{
}; // => 0
~~[]; // => 0
~~(1/0); // => 0
~~false; // => 0
~~true; // => 1
~~1.9; // => 1
~~-1.9; // => -1
Sao operation two
let str = '2'
console.log(+str) //2
When used as a unary operator, the + operator has no effect on the Number type. But if applied to a string type, it will be converted to a number:
let a = 25;
a =+ a;
console.log(a); //25
let b = '50';
console.log(typeof b); //String
b=+b;
console.log(typeof b); //Number
Usually the + operator is used to quickly convert a string to a number. But if the string literal cannot be converted to a number, the result will be unexpected:
let a = 'zs';
a =+ a;
console.log(a) //NaN
console.log(typeof a); //Number
let b = '';
b=+b;
console.log(b); //0
console.log(typeof b); //Number
Scenario 2: Array Flattening
normal operation
let arr = [1, [2, [3, 4,5]]];
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten(arr))// [1, 2, 3, 4,5]
Sao operation
let arr = [1, [2, [3, 4]]];
console.log(arr.flat(Infinity)); // [1, 2, 3, 4,5]
Flat in ES6
We can also directly call the flat method in ES6 to flatten the array. The syntax of the flat method: arr.flat ( [depth] ) where depth is the parameter of flat, and depth is the expansion depth of the array that can be passed (default is not filled, the value is 1), that is, expand one layer of the array. If the number of layers is uncertain, the parameters can be passed into Infinity, which means that no matter how many layers are to be expanded:
Scenario 3: Application of spread operator
1. Array deduplication
let arr = [3, 5, 2, 2, 5, 5];
let setArr = new Set(arr) // 返回set数据结构Set(3) {3, 5, 2}
//方法一 es6的...解构
let unique1 = [...setArr ]; //去重转数组后 [3,5,2]
//方法二 Array.from()解析类数组为数组
let unique2 = Array.from(setArr ) //去重转数组后 [3,5,2]
2. String deduplication
let str = "352255";
let unique = [...new Set(str)].join(""); // 352
3. Realize union, intersection, and difference
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]); // Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x))); // set {2, 3}
// (a 相对于 b 的)差集
let difference = new Set([...a].filter(x => !b.has(x))); // Set {1}
5. Apply with rest operator
function sumRest (...m) {
var total = 0;
for(var i of m){
total += i;
}
return total;
}
console.log(sumRest(1,2,3));//6
6. Array sorting
const sortNumbers = (...numbers) => numbers.sort();