JS优化方法(使用最新的js方法)

1,带有多个条件的if语句

将多个值放在一个数组中,然后调用数组的includes方法。

//longhand(直接的)
if(x==='abc'||x==='def'||x==='ghi'||x==='jkl'){
	//logic(逻辑)
}
//shorthand(速记)
if(['abc','def','ghi','jkl'].includes(x)){
	//logic
}

2,简化if true…else

//longhand
let test:boolean;
if(x>100){
	test = true;
}else {
	test = false;
}
//shorthand
let test = (x >10) ? true : false;
//or we can use directly
let test = x >10;
console.log(test)
//如果有嵌套的条件
let x = 300;
test2 = (x>100) ? 'greater than 100' : (x<50) ? 'less 50' : 'between 50 and 100';
console.log(test2); //'greater than 100'

3,声明变量

当我们想要声明两个具有相同的值或相同类型的变量。

//longhand
let test1;
let test2 = 1;
//shorthand
let test1,test2 = 1;

4,null,undefined 和空值检查

//longhand
if(test !== null || test !== undefined || test !== ''){
	let test2 = test1;
}
//shorthand
let test2 = test1 || '';

5,null 检查和默认赋值

let test1 = null,
	test2 = test1 || '';
console.log("null check" ,test2); //output will be ""

6,undefined 检查和默认赋值

let test1 = undefined,
	test2 = test1 || '';
console.log("undefined check",test2);//output(输出) will be ""
//一般值检查
let test1 = 'test',
	test2 = test1 || '';
console.log(test2); //output: 'test'

对于上述4,5,6点,都可以使用?? 操作符。

//如果左边值为null或undefined,就返回右边的值。默认情况下,它将返回左边的值。
const test = null ?? 'default' ;
console.log(test);
//expected output : "default"
const test1 = 0 ?? 2 ;
console.log(test1);
//expected output : 0

7,给多个变量赋值

当我们想给多个不同的变量赋值时

//longhand
let test1,test2,test3;
test1 = 1;
test2 = 2;
test3 = 3;
//shorthand
let [test1, test2, test3] = [1, 2, 3]

8,简便的赋值操作符

//longhand
test1 = test1 + 1;
test2 = test2 -1;
test3 = test3 * 20;
test1++;
test2--;
test3*=20;

9,if 判断值是否存在

//longhand
if (test1 === true) or if (test1 !== "") or if (test1 !==null)
//shorthand //it will check empty string,null and undefined too
if (test1)

注意:如果 test1 有值,将执行 if 之后的逻辑,这个操作符主要用于 null 或 undefinded 检查。

10,用于多个条件判断的 && 操作符

如果只在变量为true 时才调用函数,可以使用 && 操作符。

//longhand
if(test1){
	callMethod();
}
//shorthand
test1 && callMethod();

11,for each 循坏

//longhand
for (var i = 0;i < testData.length; i++)
//shorthand
for (let i in testData) or for (let i of testData)

遍历数组的每一个变量

function testData(element, index, array){
	console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
//logs: test[0]=11, test[1]=24, test[2]=32

12,比较后返回

我们可以在 return 语句中使用比较,它可以将 5 行代码减少到 1 行。

//longhand
let test;
function checkReturn() {
	if (!(test === undefined)) {
		return test;
	}else {
		return callMe('test')
	}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
	console.log(val);
}
//shorthand
function checkReturn() {
	return test || callMe('test')
}

13,箭头函数

//longhand
function add(a,b) {
	return a + b
}
//shorthand
const add = (a,b) => a+b;

更多例子

function callMe(name) {
	console.log('hello', name);
}
callMe = name => console.log('hello', name);

14,简短的函数调用

使用三元操作符来实现多个函数调用。

//longhand
function test1() {
	console.log('test1');
};
function test2() {
	console.log('test2');
};
var test3 = 1;
if(test3 === 1){
	test1();
}else{
	test2();
}
//shorthand
(test3 === 1 ? test1 : test2)();

15,switch 简化

我们可以将条件保存到键值对象中,并根据条件来调用他们。

//longhand
switch (data){
	case 1:
		test1();
	break;
	case 2:
		test2();
	break;
	case 3:
		test();
	break;
	//and so on ...
}
//shorthand
var data = {
	1: test1,
	2: test2,
	3: test
};
data[something] && data[something]();

16,隐式返回

通过箭头函数,我们可以直接返回值,不需要 return 语句。

//longhand
function calculate(diameter) {
	return Math.PI * diameter
}
//shorthand
calculate = diameter => {
	Math.PI * diameter;
}

17,指数表示法

//longhand
for(var i = 0; i < 10000; i++){...}
//shorthand
for(var i =0; i < 1e4; i++){...}

18,默认参数值

//longhand
function add(test1, test2){
	if(test1 === undefined)
		test1 = 1;
	if(test2 === undefined)
		test2 = 2;
	return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2)
add() //output: 3

19,延展操作符简化

//longhand
//joining arrays using concat
const data = [1, 2, 3];
const test = [4, 5, 6].concat(data);
//shorthand
//joining arrays
const data = [1, 2, 3];
const test =[4, 5, 6, ...data];
console.log(test); //[4, 5, 6, 1, 2, 3]

也可以使用延展操作符进行克隆。

//longhand
//cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice();
//shorthand
//cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];

20,模板字面量

简化:使用 + 将多个变量连接成一个字符串

//longhand
const welcome = 'Hi' + test1 + '' + test2 + '.';
//shorthand
const welcome = `Hi ${test1} ${test2}`;

21,跨行字符串

当我们在代码中处理跨行字符串时

//longhand
const data = 'abc abc abc abc abc abc\n\t'
	+ 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
		test test test test test test`

22,对象属性赋值

let test1 = 'a';
let test2 = 'b';
//longhand
let obj = {test1:test1, test2:test2};
//shorthand
let obj = {test1, test2}

23,将字符串转成数字

//longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//shorthand
let test1 = + '123';
let test2 = + '12.3';

24,解构赋值

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test3 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;

25,数组 find 简化

当我们有一个对象数组,并想根据对象属性找到特定对象

const data = [
	{
	type: 'test1',
	name: 'abc'
	},
	{
	type: 'test2',
	name: 'cde'
	},
	{
	type: 'test3',
	name: 'fgh'
	},
]
function findtest1(name) {
	for (let i = 0; i<data.length; i++) {
		if (data[i].type === 'test1' && data[i].name === name) {
			return data[i];
		}
	}
}
//shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); //{type: 'test1', name: 'fgh'}

26,条件查找简化

如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有比这更好的简化技巧。

//longhand
if (type === 'test1') {
	test1();
}
else if (type === 'test2') {
	test2();
}
else if (type === 'test3') {
	test3();
}
else if (type === 'test4') {
	test4();
}
else{
	throw new Error('Invalid value' + type);
}
//shorthand
var types = {
	test1: test1,
	test2: test2,
	test3: test3,
	test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value' + type); func();

27,indexOf 的按位操作简化

在查找数组的某个值时,我们可以使用 indexOf() 方法,但有一种更好的方法。

//longhand
if( arr.indexOf(item) > -1 ) { //item found }
if( arr.indexOf(item) === -1 ){ //item not found }
//shorthand
if( ~ arr.indexOf(item) ) { //item found }
if( !~ arr.indexOf(item) ) { //item not found }

按位(~)运算符将返回true(-1除外),将反向操作只需要 ! ~,另外,也可以使用include() 函数。

if(arr.includes(item)){
	//true if the item found
}

28,Object.entries()

将对象转换为对象数组。

const data = { test1:'abc', test2:'cde', test3:'efg' };
const arr = Object.entries(data);
console.log(arr);
/** output:
[
	["test1", "abc"],
	["test2", "cde"],
	["test3", "efg"]
]
**/

29,Object.values()

这也是 es8 引入的一个新特性,它的功能类似于 Object.entries(),只是没有键。

const data = { test1:'abc', test2:'cde' };
const arr = Object.values(data);
console.log(arr);
/** output:
['abc','cde']

30,双重按位操作

//longhand
Math.floor(1.9) === 1  //true
//shorthand
~~1.9 === 1  //true

31,重复字符串多次

为了重复操作相同的字符,我们可以使用 for 循坏,但其实还有一种简便的方法。

//longhand
let test = '';
for (let i = 0;i < 5; i++) {
	test += 'test';
}
console.log(str); //test test test test test
//shorthand
'test'.repeat(5);

32,查找数组的最大值和最小值

const arr = [1, 2, 3];
Math.max(...arr); //3
Math.min(...arr); //1

33,获取字符串的字符

let str = 'abc';
//longhand
str.charAt(2); //c
//shorthand
str[2]; //c

34,指数幂简化

//longhand
Math.pow(2, 3); //8
//shorthand
2**3 //8
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值