Summarize the 45 classic skills of JavaScript

JavaScript language 2020-11-13 05:07:44
summarize classic skills javascript


JavaScript It's a world-class programming language , Can be used for Web Development 、 Mobile application development (PhoneGap、Appcelerator)、 Server side development (Node.js and Wakanda) wait .

JavaScript It's also the first language for many new people to enter the programming world . It can be used to display simple prompt box in browser , It can also be done through nodebot or nodruino To control the robot . Able to write well structured 、 Performance efficient JavaScript Code developers , Now it has become the most sought after person in the recruitment market .

In this article , I will share some JavaScript The technique of 、 Tips and best practices , Except for a few , Whether it's a browser JavaScript engine , Or the server side JavaScript Interpreter , All apply .

1、 Always use... When assigning a variable for the first time var keyword

Variables are not declared and directly valued , Default as a new global variable , Try to avoid using global variables .

2、 Use === replace ==

== and != Operators automatically convert data types when needed . but === and !== Can't , They compare values and data types at the same time , This also makes them better than == and != fast .

[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false

3、underfined、null、0、false、NaN、 The logical result of an empty string is false

4、 Use semicolons at the end of the line

In practice, it is better to use semicolon , It's OK to forget to write , In most cases JavaScript The interpreter will automatically add . For why use semicolons

5、 Using object constructors

function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");

6、 Careful use typeof、instanceof and contructor

  • typeof:JavaScript Unary operators , Used to return the original type of the variable as a string , Be careful ,typeof null And will return to object, Most object types ( Array Array、 Time Date etc. ) And will return to object
  • contructor: Internal prototype properties , It can be rewritten by code
  • instanceof:JavaScript The operator , Will search for... In the constructor in the prototype chain , Return if found true, Otherwise return to false
var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); //[]

7、 Use self calling functions

Functions are automatically executed directly after creation , It's often called self calling anonymous functions (Self-Invoked Anonymous Function) Or call function expression directly (Immediately Invoked Function Expression ). The format is as follows :

(function(){
// The code placed here will execute automatically
})();
(function(a,b){
var result = a+b;
return result;
})(10,20)

8、 Get members randomly from an array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];

9、 Get the random number in the specified range

This function can generate false data for testing , For example, it refers to the salary within the specified range .

var x = Math.floor(Math.random() * (max - min + 1)) + min;

10、 Generated from 0 Array of numbers to a specified value

var numbersArray = [] , max = 100;
for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]

11、 Generate a random alphanumeric string

function generateRandomAlphaNum(len) {
var rdmString = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}

12、 Disorganize the number array

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});
/* numbers The array will look like [120, 5, 228, -215, 400, 458, -85411, 122205] */

It's used here JavaScript Built in array sorting function , A better way is to use special code to achieve ( Such as Fisher-Yates Algorithm ), You can see StackOverFlow This discussion on .

13、 String to space

Java、C# and PHP And other languages have implemented special string space function , but JavaScript None of them , You can use the following code for String An object function trim function :

String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};

new JavaScript The engine already has trim() The native implementation of . Many times follow books and websites to find information to learn , You will find that there is no goal , I learned a lot but I don't know what I can achieve . Have a clear career learning plan , There are many problems in the learning process , You can come to our front end to learn and communicate q-u-n78478301, Basics , Advanced . Demand for talents from enterprises How to learn front-end development , And learning what there is a free system to share , Let you whether it is self-study or find the corresponding training can let you less detours . Hope to help you quickly understand the front end , Learning front end

14、 Append between arrays

var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 The value is [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

15、 Object to array

var argArray = Array.prototype.slice.call(arguments);

16、 Verify that it's a number

function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}

17、 Verify array

function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}

But if toString() If the method has been rewritten , It won't work . You can also use the following methods :

Array.isArray(obj); // its a new Array method

If not used in the browser frame, You can also use instanceof, But if the context is too complex , It's also possible to make mistakes .

var myFrame = document.createElement('iframe');
document.body.appendChild(myFrame);
var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); // [a,b,10]
// myArray The constructor of has been lost ,instanceof The result will be abnormal
// Constructors cannot span frame Shared
arr instanceof Array; // false

18、 Get the maximum and minimum values in the array

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);

19、 Empty array

var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].

20、 Don't directly from the array delete or remove Elements

If you use array elements directly delete, In fact, it did not delete , Just set the element to undefined. Array element deletion should use splice.

Avoid :

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items The result is [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */

But should :

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items The result is [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119]

You can use... When deleting the properties of an object delete.

21、 Use length Property to truncate an array

In the previous example, I used length Property to empty the array , It can also be used to truncate arrays :

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

meanwhile , If you put length Properties get bigger , The length value of the array will increase , Will use undefined To fill in as a new element .length It's a writable property .

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

22、 Use logical and or... In conditions

var foo = 10;
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

Logic or can also be used to set default values , For example, the default value of function parameters .

function doSomething(arg1){
arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
}

23、 bring map() Function method to data loop

var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]

24、 Keep the specified decimal places

var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432

Be careful ,toFixec() The returned string is , Not numbers .

25、 Floating point problems

0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

Why? ? because 0.1+0.2 be equal to 0.30000000000000004.JavaScript All the numbers follow IEEE 754 Standard build , It's all inside 64 A floating-point number means , For details, please refer to JavaScript How the numbers in are encoded .

By using toFixed() and toPrecision() To solve this problem .

26、 adopt for-in Loop through the properties of the object

Here's how to use it , It can prevent iteration from entering the prototype properties of the object .

for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}

27、 Comma operator

var a = 0;
var b = ( a++, 99 );
console.log(a); // a will be equal to 1
console.log(b); // b is equal to 99

28、 Temporarily store variables for calculation and query

stay jQuery selector , Can temporarily store the whole DOM Elements .

var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');

29、 Check the incoming... In advance isFinite() Parameters of

isFinite(0/0) ; // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
isFinite(null); // true, Pay special attention to this

30、 Avoid using negative numbers as indexes in arrays

var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ; // from is equal to -1
numbersArray.splice(from,2); // will return [5]

Pay attention to pass it on to splice The index parameter of should not be negative , When it's a negative number , Elements are removed from the end of the array .

31、 use JSON To serialize and deserialize

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson The result is "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString The value of is equal to person The objects are the same */

32、 Do not use eval() Or function constructors

eval() And function constructors (Function consturctor) It's expensive , Every time you call ,JavaScript The engine has to convert the source code to executable code .

var func1 = new Function(functionCode);
var func2 = eval(functionCode);

33、 Do not use eval() Or function constructors

eval() And function constructors (Function consturctor) It's expensive , Every time you call ,JavaScript The engine has to convert the source code to executable code .

var func1 = new Function(functionCode);
var func2 = eval(functionCode);

34、 Avoid using with()

Use with() You can add variables to the global scope , therefore , If there are other variables of the same name , It's easy to confuse , Second, the value will also be covered .

35、 Don't use... For arrays for-in

avoid :

var sum = 0;
for (var i in arrayNumbers) {
sum += arrayNumbers[i];
}

It is :

var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
sum += arrayNumbers[i];
}

Another benefit is ,i and len Two variables are in for In the first declaration of the loop , Both are initialized only once , It's faster than the following :

for (var i = 0; i < arrayNumbers.length; i++)

36、 Pass to setInterval() and setTimeout() Use functions instead of strings

If to setTimeout() and setInterval() A string , They will use something similar to eval Change the way , It's going to be slower , Do not use :

setInterval('doSomethingPeriodically()', 1000);
setTimeout('doSomethingAfterFiveSeconds()', 5000);

It's about using :

setInterval(doSomethingPeriodically, 1000);
setTimeout(doSomethingAfterFiveSeconds, 5000);

37、 Use switch/case Instead of a big pile of if/else

Use... When judging that there are more than two branches switch/case Faster , And it's more elegant , More conducive to the organization of code , Of course , If there is more than 10 Branches , Don't use it switch/case 了 .

38、 stay switch/case Use the number range... In

Actually ,switch/case Medium case Conditions , You can also write :

function getCategory(age) {
var category = "";
switch (true) {
case isNaN(age):
category = "not an age";
break;
case (age >= 50):
category = "Old";
break;
case (age <= 20):
category = "Baby";
break;
default:
category = "Young";
break;
};
return category;
}
getCategory(5); // Will return "Baby"

39、 Using objects as prototypes of objects

Here's how , You can give an object as a parameter , To create new objects based on this prototype :

function clone(object) {
function OneShotConstructor(){};
OneShotConstructor.prototype = object;
return new OneShotConstructor();
}
clone(Array).prototype ; // []

40、HTML Field conversion function

function escapeHTML(text) {
var replacements= {"<": "<", ">": ">","&": "&", "\"": """};
return text.replace(/[<>&"]/g, function(character) {
return replacements[character];
});
}

41、 Don't use... Inside the loop try-catch-finally

try-catch-finally in catch Part of the execution assigns an exception to a variable , This variable will be built as a new variable in the runtime scope .

Avoid :

var object = ['foo', 'bar'], i;
for (i = 0, len = object.length; i <len; i++) {
try {
// do something that throws an exception
}
catch (e) {
// handle exception
}
}

And should :

var object = ['foo', 'bar'], i;
try {
for (i = 0, len = object.length; i <len; i++) {
// do something that throws an exception
}
}
catch (e) {
// handle exception
}

42、 Use XMLHttpRequests Pay attention to setting timeout

XMLHttpRequests When executed , When there is no response for a long time ( Such as network problems ) when , The connection should be terminated , Can pass setTimeout() To get the job done :

var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
clearTimeout(timeout);
// do something with response data
}
}
var timeout = setTimeout( function () {
xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true);
xhr.send();

At the same time, it should be noted that , Don't start more than one XMLHttpRequests request .

43、 Handle WebSocket timeout

Usually ,WebSocket After the connection is created , If 30 No activity in seconds , The server will timeout the connection , The firewall can also timeout connections that are not active in the unit cycle .

To prevent this from happening , Every once in a while , Send an empty message to the server . The following two functions can be used to implement this requirement , One to keep the connection active , The other is dedicated to ending this state .

var timerID = 0;
function keepAlive() {
var timeout = 15000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
cancelTimeout(timerId);
}
}

keepAlive() The function can be placed in WebSocket Connected onOpen() The back of the way ,cancelKeepAlive() Put it in onClose() The end of the method .

44、 Time notice that the original operator is faster than the function call , Use VanillaJS

such as , Don't do this in general :

var min = Math.min(a,b);
A.push(v);

Instead of :

var min = a < b ? a : b;
A[A.length] = v;

45、 Pay attention to code structure when developing , Check and compress before going online JavaScript Code

Don't forget to use a code beautification tool when writing code . Use JSLint( A grammar checker ) And compress the code before going online ( For example, use JSMin).

版权声明
本文为[JavaScript language]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple