20个提高开发效率的JavaScript技巧

Nolan990 2021-06-15 19:31:27
技巧 javascript 开发 效率 提高


减少代码行数和加快开发的技术!

我们在开发中,经常要写一些函数,如排序、搜索、寻找唯一的值、传递参数、交换值等,在这里我列出了我搜集的一些技术资源,可以像高手一样写出这些函数!

 

 JavaScript确实是一门很好的开发语言。对于给定的问题,可以有不止一种方法来达到相同的解决方案。在这篇文章中,我们将讨论最快速的方法。

 这些方法肯定会对你有帮助:

  • 减少LOC(代码行)的数量
  • 编码竞赛
  • 黑客马拉松
  • 或者其他限时任务

这些JavaScript黑客技术大多使用ECMAScript6(ES2015)以后的技术,尽管最新版本是ECMAScript11(ES2020)。

注意:下面所有的技巧都是在谷歌浏览器的控制台测试的。

 

1. 申明和初始化数组

可以用默认值来初始化特定大小的数组,如""、null或0。你可能已经把这些用于一维数组,但如何初始化二维数组/矩阵呢?

const array = Array(5).fill('');
// Output
(5) ["", "", "", "", ""]
const matrix = Array(5).fill(0).map(()=>Array(5).fill(0));
// Output
(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);
// Output: 35
  • 最大值
array.reduce((a,b) => a>b?a:b);
// Output: 9
  • 最小值
array.reduce((a,b) => a<b?a:b);
// Output: 2

 

3. 对字符串、数字或对象的数组进行排序

有内置的sort()和reverse()方法来对字符串进行排序,但对数字或对象数组的排序呢?
数字和对象的排序技巧,可以按照递增和递减的顺序进行排序。

  • 字符串排序
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]
  • 数字排序
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
(6) [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// Output
(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));
// Output
(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. 是否需要从一个数组中过滤掉无用的值?

 像0,undefined,null,false,"",''这样的值可以通过下面的技巧轻松过滤。

const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// Output
(3) [3, 6, 7]

 

5. 为各种条件使用逻辑运算符

如果你想减少嵌套,比如if...else或switch,可以使用逻辑运算符AND/OR。

function doSomething(arg1){
arg1 = arg1 || 10;
// set arg1 to 10 as a default if it’s not already set
return arg1;
}
let foo = 10;
foo === 10 && doSomething();
// is the same thing as if (foo == 10) then doSomething();
// Output: 10
 foo === 5 || doSomething(); // is the same thing as if (foo != 5) then doSomething(); // Output: 10

 

6. 删除重复的值

你可能已经在for循环中使用了indexOf(),它返回第一个找到的索引,或者使用较新的includes(),它从数组中返回布尔值true/false,以找出/删除重复的值。这里我们有两种更快捷的方法。

const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]

 

7. 创建一个计数器对象或Map

很多时候,需要通过创建计数器对象或Map来解决问题,该对象以变量为键,以其频率/出现次数为值来跟踪变量。

let string = 'kapilalipak';
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// Output
{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); } } // Output 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!';
}
// Output
Fever(97): "Take Some Rest!"
Fever(100): "Visit Doctor!"

 

9. 与传统的once相比,for循环更快。

for 和 for...in 默认会得到索引,但你可以使用 arr[index]。

for...in也接受非数字,所以要避免它。

forEach, for...of 可以直接得到元素。

forEach也可以得到索引,但for...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}; // Output gender: "Male" name: "Kapil Raghuwanshi" primary: "Mani Primary School" programming: "Extreme" secondary: "Lass Secondary School" sleeping: "Pro" swimming: "Average"

 

11. 箭头函数

箭头函数表达式是传统函数表达式的一个紧凑的替代方案,但它有局限性,不能在所有情况下使用。因为它们有词法范围(parental scope),没有自己的this和arguments,因此它们指的是它们被定义的环境。

const person = {
name: 'Kapil',
sayName() {
return this.name;
}
}
person.sayName();
// Output
"Kapil"

箭头函数改写为:

const person = {
name: 'Kapil',
sayName() {
return this.name;
}
}
person.sayName();
// Output
"Kapil"

1

2. 可选链式

如果在?之前的值是未定义的或空的,可选链式?就会停止评估,并返回未定义。

const user = {
employee: {
name: "Kapil"
}
};
user.employee?.name;
// Output: "Kapil"
user.employ?.name;
// Output: undefined
user.employ.name
// Output: 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;
});
// Output
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

 

14. 空值合并运算符

空值合并运算符(??)是一个逻辑运算符,当其左侧的操作数为空或未定义时,返回其右侧的操作数,否则返回其左侧的操作数。

const foo = null ?? 'my school';
// Output: "my school"

const baz = 0 ?? 42;
// Output: 0

 

15. Rest & Spread 运算符

那些神秘的3个点...可以Rest或Spread!

function myFun(a, b, ...manyMoreArgs) {
return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");
// Output: 6

const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
lyrics;
// Output:
(5) ["head", "shoulders", "knees", "and", "toes"]

 

16. 缺省参数

const search = (arr, low=0,high=arr.length-1) => {
return high;
}
search([1,2,3,4,5]);
// Output: 4

 

17. 将十进制转换为二进制或十六进制

我们可以使用一些内置的方法,如.toPrecision()或.toFixed()来帮助实现此类问题。

num.toString(2);
// Output: "1010"
num.toString(16);
// Output: "a"
num.toString(8);
// Output: "12"

 

18. 使用解构简单交换2个值

let a = 5;
let b = 8;
[a,b] = [b,a]
[a,b]
// Output
(2) [8, 5]

 

19. 单行回文检查

function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// Output: true

 

20. 将对象的属性变成一个数组的属性

使用Object. entries(),Object.key()和Object.values()。

const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj);
// Output
(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]

我整理的就这些了,兄弟们。

如果想跟我一起学习,请关注我。

版权声明
本文为[Nolan990]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/kfer/p/top-20-javascript-tips-and-tricks-to-increase-your-efficiency.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless