1. 初始化一个数组 \color{#00bacb}{1.初始化一个数组} 1.初始化一个数组
const array = Array(6).fill('');
// ['', '', '', '', '', '']
const matrix = Array(6).fill(1).map(() => Array(5).fill(2));
//[[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]] 二维数组
2. 数组求和,求最大值和最小值 \color{#00bacb}{2.数组求和,求最大值和最小值} 2.数组求和,求最大值和最小值
const array1 = [5,4,7,8,9,2];
const a=array1.reduce((a,b) => a+b);
console.log(a)//36 求和
const b=array1.reduce((a,b) => a > b ? a : b);
console.log(b)//9最大值
const c=Math.max(...array1)
console.log(c)//9最大值
array.reduce((a,b) => a < b ? a : b); Math.min(...array)//最小值
3. 过滤错误值 \color{#00bacb}{3.过滤错误值} 3.过滤错误值
const array = [1, 0, undefined, 6, 7, '', false];
array.filter(Boolean);
// [1, 6, 7]
4. 使用逻辑运算符 \color{#00bacb}{4. 使用逻辑运算符} 4.使用逻辑运算符
let a=11;
a>10 && aa(a);
function aa(){
a--;
console.log(a)//10
}
5. 简化判断 \color{#00bacb}{5. 简化判断} 5.简化判断
if(a === undefined || a === 10 || a=== 15 || a === null) {
//...
}
if([undefined, 10, 15, null].includes(a)) {
//...
}
6. 清空数组 \color{#00bacb}{6.清空数组} 6.清空数组
将 array.length = 0
console.log(array) // []
7. 组合数组 \color{#00bacb}{7.组合数组} 7.组合数组
const start = [1, 2]
const end = [5, 6, 7]
1、const numbers = [9, ...start, ...end, 8]
2、start.concat(end);
当合并数组非常大时
3、Array.prototype.push.apply(start, end)
const start = [1,2]
const end = [1,5,6,7]
//const c=[1,...start,...end]
//const c=start.concat(end)
//Array.prototype.push.apply(start,end)h或写成 start.push.apply(start,end);
console.log(start)//[1,2,1,5,6,7]
8. 验证 u n d e f i n e d 和 n u l l \color{#00bacb}{8. 验证 undefined 和 null} 8.验证undefined和null
if(a === null || a === undefined) {
doSomething()
}
a ?? doSomething()
9. 将数组元素转换为数字 \color{#00bacb}{9. 将数组元素转换为数字} 9.将数组元素转换为数字
const array = ['12', '1', '3.1415', '-10.01'];
array.map(Number); // [12, 1, 3.1415, -10.01]
10. 将类数组转换为数组 \color{#00bacb}{10. 将类数组转换为数组} 10.将类数组转换为数组
Array.prototype.slice.call(arguments);
[...arguments]
11. 对象属性的动态声明 \color{#ffcd41}{11. 对象属性的动态声明} 11.对象属性的动态声明
const dynamic = 'color';
var item = {
brand: 'Ford',
[dynamic]: 'Blue'
}
console.log(item);
// { brand: "Ford", color: "Blue" }
12. 获取查询参数 \color{#ffcd41}{12. 获取查询参数} 12.获取查询参数
如果我们想获取 URL 中的参数,可以使用 window 对象的属性。
window.location.search
如果一个 URL 是 google.com?project=js&type=1 那么通过上面的操作你会得到 ?project=js&type=1。如果你想得到其中一个参数,你可以这样做。
let type = new URLSearchParams(location.search).get('type');
12. 检查对象是否为空 \color{#ffcd41}{12.检查对象是否为空} 12.检查对象是否为空
Object.keys({}).length // 0
13. 获取数组中的最后一项 \color{#ffcd41}{13.获取数组中的最后一项} 13.获取数组中的最后一项
arr.slice(-1)
14. 将值转换为布尔值 \color{#ffcd41}{14. 将值转换为布尔值} 14.将值转换为布尔值
!!undefined // false
!!“996” // true
!!null // false
!!NaN // false