44 Trick JavaScript Tips
JavaScript is a world-leading programming language for Web development, mobile application development (PHONEGAP, Appcelerator), server-side development (node. js and Wakanda), and more. JavaScript is also the first language for many beginners to step into the programming world. It can be used to display a simple cue box in a browser or to control a robot by Nodebot or Nodruino. Developers who can write well-structured, performance-efficient JavaScript code are now the most sought after in the recruiting market.
In this article, I'll share some of the JavaScript tips, tricks, and best practices that apply, with the exception of a few, whether it's a browser's JavaScript engine or a server-side JavaScript interpreter.
1. Be sure to use the var keyword when assigning a variable for the first time
Variables are not declared and are directly assignable, and as a new global variable by default, avoid using global variables as much as possible.
2, use = = = Replace = =
The = = and! = operators automatically convert data types when needed. but = = = and!== do not, they compare values and data types at the same time, which makes them faster than = = and! =.
[ten] = = = =//Is False
[Ten] = =//Is True
' Ten ' = =//Is True
' = = = =/= 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 a semicolon at the end of the line
In practice it is best to use a semicolon, forget to write it is OK, most of the case the JavaScript interpreter will be automatically added. For reasons to use semicolons, refer to the truth about semicolons in the article JavaScript (https://davidwalsh.name/javascript-semicolons).
5. Using the Object Builder
function person (firstName, lastName) {
This.firstname = FirstName;
This.lastname = LastName;
}
var Saad = new Person ("Saad", "Mousliki");
6. Use typeof, instanceof and contructor with care
The Typeof:javascript unary operator, which returns the original type of the variable as a string (basic tutorial qkxue.net), note that typeof null also returns object, most of the object types (arrays array, Time date, and so on) will also return an object
Contructor: Internal prototype properties, which can be overridden by code
The instanceof:javascript operator, which is searched in the constructor in the prototype chain, returns true if found, otherwise false
var arr = ["A", "B", "C"];
typeof Arr; Returns "Object"
Arr instanceof Array//True
Arr.constructor (); //[]
`
7. Using the self-calling function
Functions are executed automatically after they are created, often referred to as self-invoking anonymous functions (self-invoked Anonymous function) or directly calling function expressions (Immediately invoked functions expression). The format is as follows:
(function () {
The code placed here will be executed automatically
})();
(function (A, b) {
var result = A+b;
return result;
}) (10,20)
8. Get members randomly from the array
var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2145, 119];
var Randomitem = Items[math.floor (Math.random () * items.length)];
9. Get random numbers within a specified range
This feature is particularly valuable when generating false data for testing, such as the number of wages in a given range (Tengyun technology ty300.com).
var x = Math.floor (Math.random () * (Max-min + 1)) + min;
10. Generate a numeric array from 0 to a specified value
var numbersarray = [], max = 100;
for (var I=1; Numbersarray.push (i++) < Max;);//numbers = [... 100]
11. Generate a random alphanumeric string
function Generaterandomalphanum (len) {
var rdmstring = "";
for (; rdmstring.length < len; rdmstring + = Math.random (). toString (. substr (2));
Return rdmstring.substr (0, Len);
}
12. Scramble the order of the array of numbers
var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
Numbers = Numbers.sort (function () {return math.random ()-0.5});
/* Numbers array will resemble [120, 5, 228,-215, 400, 458,-85411, 122205] */
The JavaScript built-in array sorting function is used here, and a better approach is to implement it with specialized code (such as the Fisher-yates algorithm), which can be found in the discussion on StackOverflow.
13, string to go to space
Languages such as Java, C #, and PHP implement specialized string de-whitespace functions, but there is no JavaScript in which you can use the following code to function as a trim function for a string object:
String.prototype.trim = function () {return this.replace (/^\s+|\s+$/g, "");};
The new JavaScript engine already has a native implementation of trim ().
14. Append between arrays
var array1 = [N, "foo", {name "Joe"},-2458];
var array2 = ["Doe", 555, 100];
Array.prototype.push.apply (Array1, array2);
/* Array1 value for [+, ' foo ', {name ' Joe '}, -2458, ' Doe ', 555, 100] */
15. Object conversions to arrays
var Argarray = Array.prototype.slice.call (arguments);
16, verify whether the number
function Isnumber (n) {
Return!isnan (parsefloat (n)) && isfinite (n);
}
17. Verify that it is an array
function IsArray (obj) {
return Object.prototype.toString.call (obj) = = = ' [Object Array] ';
}
But if the ToString () method is rewritten, it won't work. You can also use the following methods:
Array.isarray (obj); Its a new Array method
`
If you do not use a frame in your browser, you can also use instanceof, but if the context is too complex, there may be an error.
Manuscripts: Diligent Learning qkxue.net
Read the full version of the graphic 44 tips for JavaScript
44 Trick JavaScript Tips