1.数组去重
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
//Result: [1, 2, 3, 5]
2.浮点数转整数
console.log(10.9 | 0); // 10
console.log(-10.9 | 0); // -10
console.log(23.9 | 0); // Result: 23
console.log(-23.9 | 0); // Result: -23
3.数组降维度
let arr = [ [1], [2], [3] ];
arr = Array.prototype.concat.apply([], arr);
console.log(arr);// [1, 2, 3]
let array = [ [1], [2], [3] ];
array = array.flat(2);
console.log(array); // [1, 2, 3]
let arrMore = [1, 2, [3], [[4]]];
arrMore = arrMore.flat(Infinity);
console.log(arrMore);[1, 2, 3, 4]
4.短路求值
x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
但有时候三元运算符仍然很复杂,我们可以使用逻辑运算符 && 和||来替代,让代码更简洁一些。这种技巧通常被称为“短路求值”。
假设我们想要返回两个或多个选项中的一个,使用 && 可以返回第一个 false。如果所有操作数的值都是 true,将返回最后一个表达式的值
let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3
console.log(0 && null); // Result: 0
使用||可以返回第一个 true。如果所有操作数的值都是 false,将返回最后一个表达式的值。
let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null
5.幂运算
//比Math.power(2,3)
console.log(2 ** 3); // Result: 8
console.log(2 ** 4); // Result: 16
6.转数字
let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"
console.log(+true); // Return: 1
console.log(+false); // Return: 0
7.统计字符串中出现次数最多的字符
//统计每个字母出现的次数,然后存起来,然后进行比较
function maxTimesChar(str) {
if(str.length == 1) {
return str;
}
let charObj = {};
for(let i=0;i<str.length;i++) {
if(!charObj[str.charAt(i)]) {
charObj[str.charAt(i)] = 1;
}else{
charObj[str.charAt(i)] += 1;
}
}
let maxChar = '',
maxValue = 1;
for(var k in charObj) {
if(charObj[k] >= maxValue) {
maxChar = k;
maxValue = charObj[k];
}
}
return maxChar;
}
8.数组合并
var a = [1,2,3];
var b=[4,5]
a = a.concat(b);
console.log(a);
//此处输出为 [1, 2, 3 ,4 ,5]
// ES5 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1)//[0,1,2,3,4,5]
// ES6 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1)//[0,1,2,3,4,5]
9.slice截取
var str1 = 'nihaoya wobuhaoya'
console.log(str1.slice(4,9)); //4位置开始,到9的前一个位置结束
console.log(str1.slice(2,14));//start位置开始,end前一个位置结束
console.log(str1);//原字符串不变
console.log(str1.slice(-1,0)); //返回的是空字符串
console.log(str1.slice(30,100)); //长度超过字符串的长度,返回空字符串
console.log(str1.slice(-1,10));//返回的是空字符串