top-20-javascript-tips-and-tricks-to-increase-your-speed-and-efficiency-283g

原始地址:https://dev.to/techygeeky/top-20-javascript-tips-and-tricks-to-increase-your-speed-and-efficiency-283g

方便和有用的技巧来减少代码行数并加速开发工作!

在我们的日常任务中,我们需要编写诸如排序、搜索、查找唯一值、传递参数、交换值等函数,所以在这里我列出了一些简写技巧,以便以专业的方式编写所有这些函数!✌🏻
JavaScript是一门非常棒的语言💛,学习和使用起来非常方便。对于给定的问题,可能有多种方法可以达到相同的解决方案。在本文中,我们将只讨论最快的方法。🚀
这些方法肯定会对你有所帮助:

  • 减少代码行数
  • 编码比赛
  • 黑客马拉松或其他限时任务。⏱
    这些JavaScript黑科技的多数使用了ECMAScript 6(ES2015)及以后的技术,虽然最新版本是ECMAScript11(ES2020)。
    注意:下面所有的技巧都在Google Chrome的控制台上测试过。

原文链接

1. 声明和初始化数组
我们可以使用默认值(如“”,null0)来初始化特定大小的数组。你可能已经用过这些方法来初始化一维数组,但是如何初始化二维数组或矩阵呢?
const array = Array(5).fill('');
// 输出
(5) ["", "", "", "", ""]
const matrix = Array(5).fill(0).map(()=>Array(5).fill(0));
// 输出
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5

原文链接

2. 求和、最小值和最大值
我们可以使用reduce方法来快速查找基础数学运算结果。
const array = [5,4,7,8,9,2];
- 求和
array.reduce((a,b) => a+b);
// 输出: 35
- 最大值
array.reduce((a,b) => a>b?a:b);
// 输出: 9
- 最小值
array.reduce((a,b) => a<b?a:b);
// 输出: 2

原文链接

3. 排序字符串、数字或对象的数组
我们内建了用于排序字符串的sort()和reverse()方法,但是对于数字或对象的数组呢?
让我们检查一下数字和对象的排序技巧,包括升序和降序排列。
- 排序字符串数组
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出
(4) ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// 输出
(4) ["Steve", "Musk", "Kapil", "Joe"]
- 排序数字数组
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出
(6) [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// 输出
(6) [100, 40, 25, 10, 5, 1]
- 排序对象数组
const objectArr = [
{ first_name: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出
(3) [{}, {}, {}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3

原文链接

4. 是否需要过滤数组中的假值?
如0undefinednullfalse""''可以通过以下技巧很容易地省略掉。
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]

原文链接

5. 使用逻辑运算符处理不同的条件
如果你想减少嵌套的if..else或switch case,你可以简单地使用逻辑运算符AND/ORfunction doSomething(arg1){
arg1 = arg1 || 10;
// 如果arg1没有设置,将arg1设置为默认值10
return arg1;
}
let foo = 10;
foo === 10 && doSomething();
// 等同于 if (foo == 10) then doSomething();
// 输出: 10
foo === 5 || doSomething();
// 等同于 if (foo != 5) then doSomething();
// 输出: 10

原文链接

6. 移除重复值
你可能已经使用过indexOf()for循环来找到第一个找到的索引,或者使用includes()从数组中返回布尔值true/false来查找/删除重复项。下面有2种更快速的方法。
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// 或者
const nonUnique = [...new Set(array)];
// 输出: [5, 4, 7, 8, 9, 2]

原文链接

7. 创建计数器对象或映射
大部分情况下,我们需要通过创建计数器对象或映射来跟踪变量key以及它们的频率/出现次数来解决问题。
let string = 'kapilalipak';
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}const countMap = new Map();
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {
countMap.set(string[i], 1);
}
}
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}

原文链接

8. 三元运算符是酷的
你可以通过使用三元运算符来避免嵌套的条件语句if..elseif..elseif。
function Fever(temp) {
return temp > 97 ? 'Visit Doctor!'
: temp < 97 ? 'Go Out and Play!!'
: temp === 97 ? 'Take Some Rest!';
}
// 输出
Fever(97): "Take Some Rest!"
Fever(100): "Visit Doctor!"

原文链接

9. 与传统for循环相比,forfor...in循环更快
- forfor...in默认情况下可以获得索引,但是你可以使用arr[index]来获得元素的值。
- for...in还可接受非数值,因此要避免使用它。
- forEach和for...of直接获取元素的值。
- forEach也可以获得索引,但是for...of不能。
- forfor...of会考虑数组中的空洞,而其他两种不会。

原文链接

10. 合并两个对象
在我们的日常任务中,经常需要合并多个对象。
const user = {
name: 'Kapil Raghuwanshi',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {...user, ...college, ...skills};
// 输出
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"

原文链接

11. 箭头函数
箭头函数是传统函数表达式的一种紧凑形式,但功能有限,不能在所有情况下使用。由于它们具有词法作用域(也称为父级作用域),没有自己的this和arguments,因此它们指向定义它们的环境。
const person = {
name: 'Kapil',
sayName() {
return this.name;
}
}
person.sayName();
// 输出
"Kapil"
但是
const person = {
name: 'Kapil',
sayName : () => {
return this.name;
}
}
person.sayName();
// 输出
""

原文链接

12. 可选链操作符
可选链?.?.之前的值为undefinednull时停止计算,并返回undefinedconst user = {
employee: {
name: "Kapil"
}
};
user.employee?.name;
// 输出: "Kapil"
user.employ?.name;
// 输出: undefined
user.employ.name
// 输出: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined

原文链接

13. 打乱一个数组
利用内建的Math.random()方法。
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
return Math.random() - 0.5;
});
// 输出
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// 再次调用
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

原文链接

14. 空值合并运算符
空值合并运算符??是一个逻辑运算符,当左侧操作数为nullundefined时,返回其右侧操作数,否则返回左侧操作数。
const foo = null ?? 'my school';
// 输出: "my school"
const baz = 0 ?? 42;
// 输出: 0

原文链接

15. Rest和Spread运算符
神秘的3个点...可以用于参数的收集(rest)和展开(spread)🤓
function myFun(a, b, ...manyMoreArgs) {
return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");
// 输出: 6const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
lyrics;
// 输出:
(5) ["head", "shoulders", "knees", "and", "toes"]

原文链接

16. 默认参数
const search = (arr, low=0,high=arr.length-1) => {
return high;
}
search([1,2,3,4,5]);
// 输出: 4

原文链接

17. 将十进制转换为二进制或十六进制
我们可以使用内建方法如.toPrecision().toFixed()来实现很多帮助功能。
const num = 10;
num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"

原文链接

18. 使用解构交换2个值
let a = 5;
let b = 8;
[a,b] = [b,a]
[a,b]
// 输出
(2) [8, 5]

原文链接

19. 单行回文检查
好吧,这不是一个完整的简写技巧,但它会给你一个更清晰的思路来处理字符串。
function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// 输出: true

原文链接

20. 将对象的属性转换为属性数组
使用Object.entries()、Object.keys()和Object.values()
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj);
// 输出
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3
Object.keys(obj);
(3) ["a", "b", "c"]
Object.values(obj);
(3) [1, 2, 3]
这就是目前为止的所有内容! 🤗
如果你还了解其他类似的技巧,请加入我们的
[GitHub 仓库](https://github.com/kapilraghuwanshi/quick-javascript-tips-tricks-hacks),我们一起学习它们吧。

原文链接

如果您通过这篇文章真正学到了新东西,或者它让您的开发工作比以前更快,喜欢它,保存它并与您的同事分享。
我已经写了相当一段时间的技术博客,大部分都在我的
[Medium](https://www.medium.com/@techygeeky)上发表,这是我在Dev.to上的第一篇技术文章/教程。希望大家会喜欢!🤩
让我们在一起保持联系
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值