javascript的一些小技巧

在日常的项目开发中经常出现却容易被忽略的JavaScript小技巧,今天列举几个学习一下。

1、截取数组

如果您想从数组的末尾删除值,有比使用splice()更快的替代方法。

例如,如果你知道原始数组的长度,就可以通过重新定义它的length属性来实现截取。

1
2
3
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

这是一个特别简洁的解决方案。但是,slice()方法的运行时更快。如果速度是你的主要目标,考虑使用下面的方式。

1
2
3
4
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);

console.log(array); // Result: [0, 1, 2, 3]

2、转换Number类型

我们可以通过加法运算符+将一个string类型的变量转回为number 类型的。

1
2
3
4
5
let int = "15";
int = +int;

console.log(int); // Result: 15
console.log(typeof int); Result: "number"

在某些上下文中,+将被解释为连接操作符,而不是加法操作符。当这种情况发生时(您希望返回一个整数,而不是浮点数),您可以使用两个波浪号:~~。(需要注意为英文格式)

一个波浪号~,被称为“按位不运算符”,等价于 - n - 1。所以~15 = -16.

使用两个~~可以有效的否定运算。这是因为 - (- n - 1) - 1 = n + 1 - 1 = n。也就是说 ~-16 = 15

1
2
3
4
const int = ~~"15"

console.log(int); // Result: 15
console.log(typeof int); Result: "number"

3、转换String类型

我们可以通过+连接运算符将一个number类型的变量转换成string类型。

1
2
3
4
const val = 1 + "";

console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

4、转换Boolean类型

常规的boolean型值只有 true 和 false,但是在JavaScript中我们可以将其他的值认为是 ‘truthy’ 或者 ‘falsy’的。

除了0, “”, null, undefined, NaN 和 false,其他的我们都可以认为是‘truthy’的。

我们可以通过负运算符!将一系列的变量转换成“boolean”型。

1
2
3
4
5
6
const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;

console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

5、获取数组中的最后的元素

数组方法slice()可以接受负整数,如果提供它,它将从数组的末尾开始截取数值,而不是开头。

1
2
3
4
5
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

6、格式化JSON代码

我们可能在处理一些JSON相关的处理时很多时候都会使用到JSON.stringify,但是你是否意识到它可以帮助缩进JSON呢?

stringify()方法接受两个可选参数:一个replacer函数和一个space值,replacer函数可以用来过滤显示的JSON。

space值接受一个整数,表示需要的空格数或一个字符串(如’\t’来插入制表符),它可以使读取获取的JSON数据变得容易得多。

1
2
3
4
5
6
7
console.log(JSON.stringify({ dabao: 'D', jiaru: 'J' }, null, '\t'));

// Result:
// '{
// "dabao": D,
// "jiaru": J
// }'

7、类中自动绑定

我们可以在类中通过使用ES6增加的箭头函数的方式来实现隐形绑定作用域。而按照之前的处理,我们需要显式的去为我们写的方法进行绑定,类似于 this.myMethod = this.myMethod.bind(this)这样。当我们的类中有很多方法时,会增加大量的绑定的代码的书写。现在我们就可以通过箭头函数的方式来简化这个过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

import React, { Component } from React;
export default class App extends Compononent {
constructor(props) {
super(props);
this.state = {};
}
demo = () => {
// 隐式绑定
}
render() {
return (
<>
<div>
{this.demo()}
</div>
</>
)
}
};

8、最大值

1
2
3
4
5
6
7
8
// ES5 的写法
Math.max.apply(this,[1,2,3,4]) //4
// ES6 的写法
Math.max(...[1,2,3,4]) //4
// reduce
[1,2,3,4].reduce((accumulator, currentValue)=>{
return accumulator = accumulator > currentValue ? accumulator : currentValue
});//4

Math.max()是Math对象内置的方法,参数是字符串;
reduce是ES5的数组api,参数有函数和默认初始值;
函数有四个参数,pre(上一次的返回值),cur(当前值),curIndex(当前值索引),arr(当前数组)

9、求和

1
2
3
[1,2,3,4].arr.reduce(function (prev, cur) {
return prev + cur;
},0) //10
1
2
3
4
5
6
7
8
9
10
11
function sum(arr) {
var len = arr.length;
if(len == 0){
return 0;
} else if (len == 1){
return arr[0];
} else {
return arr[0] + sum(arr.slice(1));
}
}
sum([1,2,3,4]) //10

利用slice截取改变数组,再利用递归求和

10、合并

1
2
3
[1,2,3,4].concat([5,6]) //[1,2,3,4,5,6]
[...[1,2,3,4],...[4,5]] //[1,2,3,4,5,6]
[1,2,3,4].push.apply([1,2,3,4],[5,6]) //[1,2,3,4,5,6]
1
2
3
4
5
let arr=[1,2,3,4];
[5,6].map(item=>{
arr.push(item)
})
//arr值为[1,2,3,4,5,6],注意不能直接return出来,return后只会返回[5,6]

11、判断是否包含值

1
2
3
4
[1,2,3].includes(4) //false
[1,2,3].indexOf(4) //-1 如果存在换回索引
[1, 2, 3].find((item)=>item===3)) //3 如果数组中无值返回undefined
[1, 2, 3].findIndex((item)=>item===3)) //2 如果数组中无值返回-1

includes(),find(),findIndex()是ES6的api

1
2
3
[1,2,3].some(item=>{
return item===3
}) //true 如果不包含返回false

12、每一项设置值

1
[1,2,3].fill(false) //[false,false,false]

fill是ES6的方法

1
[1,2,3].map(() => 0)

13、每一项是否满足

1
[1,2,3].every(item=>{return item>2}) //false

every是ES5的api,每一项满足返回 true

14、有一项满足

1
[1,2,3].some(item=>{return item>2}) //true

some是ES5的api,有一项满足返回 true

15、过滤数组

1
[1,2,3].filter(item=>{return item>2}) //[3]

filter是ES5的api,返回满足添加的项的数组

16、对象和数组转化

1
2
3
4
Object.keys({name:'大宝',age:25}) //['name','age']
Object.values({name:'大宝',age:25}) //['大宝',25]
Object.entries({name:'大宝',age:25}) //[[name,'大宝'],[age,25]]
Object.fromEntries([name,'大宝'],[age,25]) //ES10的api,Chrome不支持 , firebox输出{name:'大宝',age:25}