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

2023-10-26

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JS优化方法(使用最新的js方法) 的相关文章

随机推荐

  • 认识 ESP-IDF-v4.3+工程结构(ESP32-C3应用调整示例)

    ESP32 C3 学习测试到今天 一直在使用 ESP IDF 的框架 但是还从来没有注意过工程结构 遇到复杂一点的项目 工程结构就显得太乱了 本文就来了解下 ESP IDF 工程结构 目录 前言 一 ESP IDF工程基本框架 1 1 工程
  • 数学是成就卓越开发人员的必备技能

    本文转载至 http blog jobbole com 444 编者按 原文作者Alan Skorkin是一名软件开发人员 他在博客中分享对软件开发相关的心得 其中有很多优秀的文章 本文就是其中一篇 作者认为 成为优秀的开发人员 可以没有数
  • javaEE企业级框架ssm知识点整合【思维导图】

    ssm Spring SpringMVC Mybatis 框架是轻量级javaEE应用开发最受欢迎的一种组合框架之一 使用这种框架的项目使JavaEE架构具有高度可维护性和可扩展性 同时极大地提高了项目的开发效率 降低了开发和维护的成本 而
  • webkit和webkit2的区别

    转自 http blog csdn net shunzi 1984 article details 6196483 原文地址 https trac webkit org wiki WebKit2 webkit2为了在API层支持多进程改变了
  • Linux “/“ 分区扩容

    前言 扩容是一项很简单的工作 但是有时候因为长时间没有操作过扩容 指令会比较生疏 因此写一篇扩容的文档 方便在再次失忆的情况下能快速回忆起操作流程 逻辑卷扩容的流程 创建PV gt 扩容VG gt 扩容LV 以下是扩容的详细流程 1 查看当
  • 人工智能梯度下降的优化器SGD、Momentum、AdaGrad、Adam的数学原理以及无框架实现

    系列文章目录 人工智能 梯度下降的原理和手写实现 文章目录 系列文章目录 前言 一 梯度下降优化器是什么 二 SGD优化方法 1 SGD是什么 2 SGD的数学原理 3 SGD的实现 4 SGD的缺陷 三 Momentum优化方法 1 Mo
  • 为什么公司规定所有接口都必须加上分布式锁,你知道吗?

    上一篇文章我们聊了聊Redisson这个开源框架对Redis分布式锁的实现原理 如果有不了解的兄弟可以看一下 都2022年了 出去面试连分布式锁的源码你都不会画 今天就给大家聊一个有意思的话题 每秒上千订单场景下 如何对分布式锁的并发能力进
  • 如何通过代码获取framedebugger里面的drawcall信息

    最近想做个性能工具 用来分析当前drawcall里面的具体调用 不知道unity有没有获取数据的具体接口 不过framedebugger里面的确有相关数据 这是方案一 另外一个方案是hook 理论上应该参考下renderdoc的实现应该就可
  • 使用scrapy爬取数据

    安装scrapy 使用清华镜像 打开PyCharm 安装scrapy框架 pip install i https pypi tuna tsinghua edu cn simple scrapy 新建一个名为python scrapy的项目
  • 深入浅出图解CNN-卷积神经网络

    首先 介绍一下卷积的来源 它经常用在信号处理中 用于计算信号的延迟累积 假设一个信号发生器每个时刻t产生一个信号xt 其信息的衰减率为wk 即在k 1个时间步长后 信息为原来的wk 倍 假设w1 1 w2 1 2 w3 1 4 时刻t收到的
  • linux查找目录下的所有文件中是否含有某个字符串

    Linux查找文件内容的常用命令方法 从文件内容查找匹配指定字符串的行 grep 被查找的字符串 文件名 例子 在当前目录里第一级文件夹中寻找包含指定字符串的 in文件 grep thermcontact in 从文件内容查找与正则表达式匹
  • [论文阅读]《Database Maanagement Systems》-第六章

    第六章 QUERY BY EXAMPLE QBE 查询示例 QBE P201 P216 Example is always more efficacious than precept 身教胜于言教 榜样总是比教训更有效 precept 规则
  • openGL之API学习(一七三)glsl如何设置版本version和兼容性

    version 120 version 120 core version 120 compatibility version 300 es GLSL ES 提供了一个 version 指令来指定着色器使用的GLSL ES的版本 如果不指定G
  • c++ 日志输出库 spdlog 简介

    spdlog是一个开源的 快速的 仅有头文件的C 11 日志库 它提供了向流 标准输出 文件 系统日志 调试器等目标输出日志的能力 它支持的平台包括Windows Linux Mac Android iOS 官方参考 https githu
  • 后缀自动机(SAM)——黑盒使用方案

    首先讲下后缀自动机吧 会写一下部分必要的原理 其他的原理不做解释 代码未讲解的部分希望能当做黑盒来使用 既不了解具体原理但知道其性质以及如何使用 我实在是佩服发明出AC自动机 回文自动机 后缀自动机这人 前置知识 AC自动机中的Fail树
  • 如何使用Chrome浏览器模拟弱网情况

    点击谷歌浏览器图标 打开浏览器后 按下F12键 弹出开发者工具窗口 刷新网页 页面的加载速度为597ms 在开发者工具中 点击Online 在弹出的菜单中点击Slow 3G 慢速3G网络 重新加载网站 发现页面的加载速度变慢了 变成6 5s
  • openssl engine在tls中的应用

    openssl engine的实现和原理在上一篇文章 https blog csdn net liu942947766 article details 128837041 spm 1001 2014 3001 5502 openssl en
  • MATLAB随机生成m个三维坐标点,且各个坐标点之间的距离不小于n

    randi函数 randi max m n 生成均匀分布的随机整数 max生成的随机整数最大值 生成m行n列的矩阵 编写函数sampling function x y z sampling lowx upx lowy upy lowz up
  • 第五篇:进阶篇 发动机的噪声特性

    本专栏分享传统NVH知识点 从声学理论 材料声学 汽车噪声振动分析 车辆及其零部件甚至原材料的声学测试方法等多维度介绍汽车NVH 一些专用术语同时给出了中英文对照 欢迎新人 同行 爱好者一起交流 由于内容写的较为仓促 有误的地方欢迎大家批评
  • JS优化方法(使用最新的js方法)

    1 带有多个条件的if语句 将多个值放在一个数组中 然后调用数组的includes方法 longhand 直接的 if x abc x def x ghi x jkl logic 逻辑 shorthand 速记 if abc def ghi