不可错过的JS代码优化技巧

更新日期: 2022-04-20阅读: 534标签: 技巧

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

对于不包含大逻辑的 if-else 条件,可以使用下面的快捷写法。我们可以简单地使用三元运算符来实现这种简化。

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
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 和空值检查

当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

5. null 检查和默认赋值

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // 输出 ""

6. undefined 检查和默认赋值

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // 输出 ""

一般值检查

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // 输出: 'test'

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

如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。

const test= null ?? 'default';
console.log(test);
// 输出结果: "default"
const test1 = 0 ?? 2;
console.log(test1);
// 输出结果: 0

7. 给多个变量赋值

当我们想给多个不同的变量赋值时,这种技巧非常有用。

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];

8. 简便的赋值操作符

在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;

9. if 判断值是否存在

这是我们都在使用的一种常用的简便技巧,在这里仍然值得再提一下。

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //检查空字符串、null或者undefined
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;
  // ...
}
// 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() //输出结果: 3

19. 延展操作符简化

//longhand
// 使用concat连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
// 连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

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

//longhand
// 克隆数组
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand
//克隆数组
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 test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;

25. 数组 find 简化

当我们有一个对象数组,并想根据对象属性找到特定对象,find 方法会非常有用。

const data = [{
        type: 'test1',
        name: 'abc'
    },
    {
        type: 'test2',
        name: 'cde'
    },
    {
        type: 'test1',
        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
}

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

35. 避免全局查找

在一个函数中会用到全局对象存储为局部变量来减少全局查找,因为访问局部变量的速度要比访问全局变量的速度更快些

function search() {
//当我要使用当前页面地址和主机域名
alert(window.location.href + window.location.host);
}
//最好的方式是如下这样 先用一个简单变量保存起来
function search() {
var location = window.location;
alert(location.href + location.host);
}

36. 避免阻塞性函数

JavaScript 执行过程耗时越久,浏览器等待响应用户输入的时间就越长。所以在我们需要防止使用一些阻塞性函数,比如:

document.write()


为站长发电

链接: https://www.fly63.com/article/detial/11373

微信小程序技巧_你需要知道的小程序开发技巧

一直以来进行了比较多的微信小程序开发... 总会接触到一些和官方组件或 api 相关或其无法解决的需求,于是决定在这里小小的整理一下微信小程序开发的一些技巧

微信小程序分享到朋友圈方法与技巧

小程序提供onShareAppMessage 函数,此函数只支持分享给我微信朋友,小程序如何分享到朋友圈呢?使用canvas绘制一张图片,并用wx.previewImage预览图片,然后长按图片保存图片到手机。

前端新手程序员不知道的 20个小技巧

前端新手程序员不知道的 20个小技巧:作为前端开发者,使用双显示器能大幅提高开发效率、学编程最好的语言不是PHP,是English、东西交付之前偷偷测试一遍、问别人之前最好先自己百度,google一下、把觉得不靠谱的需求放到最后做,很可能到时候需求就变了...

小技巧:检查你本地及公共 IP 地址

本地的 IP 地址是分配给你计算机上的内部硬件或虚拟网卡的本地/私有 IP 地址。根据你的 LAN 配置,上述 IP 地址可能是静态或动态的。公共的 IP 地址是你的 Internet 服务提供商(ISP)为你分配的公共/外部 IP 地址。

12 个 CSS 高级技巧汇总

使用 :not() 在菜单上应用/取消应用边框;给body添加行高;所有一切都垂直居中;逗号分隔的列表;使用负的 nth-child 选择项目;对图标使用SVG;优化显示文本;对纯CSS滑块使用 max-height;继承 box-sizing

26 个 jQuery使用技巧

禁用右键点击;禁用搜索文本框;新窗口打开链接;检测浏览器;预加载图片;样式筛选;列高度相同;字体大小调整;返回页面顶部;获取鼠标的xy坐标;验证元素是否为空;替换元素

提高网站加载速度的一些小技巧

为你网站的用户留下良好的第一印象是非常必要的。随着商业领域的竞争,拥有一个吸引人的网站可以帮助你脱颖而出。研究表明,如果加载时间超过3秒,会有 40% 的用户放弃访问你的网站

《CSS世界》中提到的实用技巧

清除浮动主要用于子元素浮动(float)之后,父元素无法撑起高度和宽度。文字少时居中,多时靠左因为div嵌套着p,所以p的尺寸并不会超过div。但是要注意,当p的内容为英文单词组成的时候

不常被提及的JavaScript小技巧

这次我们主要来分享11个在日常教程中不常被提及的JavaScript小技巧,他们往往在我们的日常工作中经常出现,但是我们又很容易忽略。Set类型是在ES6中新增的,它类似于数组,但是成员的值都是唯一的

CSS-in-JS 库 styled-class

为什么要在JavaScript里写CSS?避免命名全局污染,条件和动态样式(比如选择主题色之类的),在框架层面进行限制或补充(比如补全供应商前缀),避免业务人员使用奇技淫巧

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!