46 JavaScript code snippets commonly used in development

Source: Internet
Author: User
Tags array length constructor eval json logical operators setinterval trim

45 useful JavaScript tips, tips and best practices

Translator: Dwqs

In this article, I'll share some of the techniques, tips, and best practices that are commonly used in JavaScript. Whether JavaScript developers are using the browser/engine or server-side (ssjs--service Side JavaScript) JavaScript interpreter, they should be known.

Note that the code snippet in the article was tested on the latest Google Chrome (version number 30), which uses the V8 JavaScript engine (V8 3.20.17.15).

1, the first to assign values to the variable do not forget the VAR keyword.

Assigning a value to an undefined variable will make the variable automatically global and should avoid global variables.

2. Use = = = instead of = =

the = = (or!=) operator automatically converts variable types when needed, and = = = = = (or!==) does not perform type conversions. When comparing values and types, you should first consider using = = =

[a] = = =/is False
[Ten] = =/is True
' Ten ' =/Is True
' Ten ' = =/is False
[] = = 0//Is True
[] = = = 0//Is False
' = = False//is true but true = = ' A ' is false
' = = = False//is False

3, undefined, NULL, 0, False, NaN, ' (empty string) are treated as false.

4. Use semicolons at end of line

It's good practice to use semicolons at the end of a line. If you forget, you won't get a warning because in most cases the JavaScript interpreter inserts a semicolon. For more details on why you should use semicolons, see this article: Http://davidwalsh.name/javascript-semicolons.

5. Create an object constructor

function person (firstName, lastName) {
This.firstname = FirstName;
This.lastname = LastName;
}

var Saad = new Person ("Saad", "Mousliki");

6, careful use of typeof, Instanceof and constructor

typeof: Don't forget typeof null returns object, and most objects, typeof (Array, Date, and others) will also return the object
Constructor: Internal prototype properties, which can be overridden (refer to: Another prototype object)
Instanceof:javascript an operator that checks the prototype chain of a constructor
var arr = ["A", "B", "C"];
typeof Arr; Return "Object"
Arr instanceof Array//True
Arr.constructor (); //[]

7. Create a self execution function

This is often called the anonymous function of self invocation or the function expression (Iife) that is called immediately. When you create it, it automatically executes the function.

(function () {
Some private code that'll be executed automatically
})();
(function (a,b) {
var result = A+b;
return result;
}) (10,20)

8, random access to an array of items

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2145, 119];

var Randomitem = Items[math.floor (Math.random () * items.length)];

9. Get a random number within a certain range

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

10, from the number 0 to the maximum value to get an array of numbers

var numbersarray = [], max = 100;

for (Var i=1 numbersarray.push (i++) < Max;); numbers = [0,1,2,3 ... 100]

11. Generate a random string

function Generaterandomalphanum (len) {
var rdmstring = "";
for (; rdmstring.length < len; rdmstring + = Math.random (). toString (2));
Return rdmstring.substr (0, Len);
}

12, disturb the sequence of elements of a numerical array

var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
Numbers = Numbers.sort (function () {return math.random () –0.5});
/* The array numbers'll is equal for example to

[120, 5, 228,-215, 400, 458,-85411, 122205] * *

13, the Trim function of string
String.prototype.trim = function () {return this.replace (/^s+|s+$/g, "");

14. Append an array to another array
var array1 = [, "foo", {name: "Joe"},-2458];

var array2 = ["Doe", 555, 100];
Array.prototype.push.apply (Array1, array2);
/* Array1 'll is equal to [, "foo", {name "Joe"}, -2458, "Doe", 555, 100] * *

15. Convert the arguments object into an array
var Argarray = Array.prototype.slice.call (arguments);

16, verify that the parameter is the number type
function Isnumber (n) {
Return!isnan (parsefloat (n)) && isfinite (n);
}

17. Verify that the parameter is an array
function IsArray (obj) {
return Object.prototype.toString.call (obj) = = ' [Object Array] ';
}

Note that the toString () method is overridden, and using this technique will not get the desired result. Or you can do this:
Array.isarray (obj); This is a new array method

If you are not using multiple frames, you can also use the Instanceof method. But if you have multiple contexts, you will get the wrong result.
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]

Instanceof won't work correctly, MyArray loses his constructor
constructor is not shared between frames
Arr instanceof Array; False

18, get the maximum and minimum values in the array of numbers
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 an array
var myarray = [12, 222, 1000];
myarray.length = 0; MyArray is equal to [].

20, do not use Delete to delete an array item
Use split rather than using Delte to delete an item in an array. Using delete simply replaces the original item with the undefined and is not really removed from the array. Do not use the following method
var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2154, 119];
Items.length; Return 11
Delete Items[3]; return True
Items.length; Return 11
/* items would be equal to [548, "a", undefinedx1, 5478,
"Foo", 8852, Undefinedx1, "Doe", 2154, 119] * *
But in the following ways

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2154, 119];
Items.length; Return 11
Items.splice (3,1);
Items.length; Return 10
/* items would be equal to [548, "a", 5478,
"Foo", 8852, Undefinedx1, "Doe", 2154,119] * *

You should use Delete to delete an object's properties

21. Use length to truncate an array
Like the way it empties the array above, we use the Length property to truncate an array.
var myarray = [12, 222, 1000, 124, 98, 10];
Myarray.length = 4; MyArray would be equal to [12, 222, 1000, 124].

In addition, if you set the length of an array to a value larger than the current one, the lengths of the array will be changed, adding a new undefined item to fill. The length property of an array is readable and writable.

Myarray.length = 10; The new array length is 10
MYARRAY[MYARRAY.LENGTH-1]; Undefined

22. Use logical operators in conditions: and, or

var foo = 10;
Foo = = && dosomething (); Equivalent to if (foo = =) dosomething ();
Foo = = 5 | | DoSomething (); Equivalent to if (foo!= 5) dosomething ();

Or can be used to set default parameters for a function

function DoSomething (arg1) {
ARG1 = Arg1 | | 10; If Arg1 is not set, the ARG1 will default to 10
}

23, using the map () method to traverse an array of items

var squares = [1,2,3,4].map (function (val) {
Return Val * val;
});
Squares would be equal to [1, 4, 9, 16]

24. Keep decimal Places

var num = 2.443242342;
num = num.tofixed (4); Num'll is equal to 2.4432

25. Floating point numbers

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

Why is it false? 0.1+0.2 equals 0.30000000000000004. Don't forget, all the JavaScript numbers are internally floating points in 64-bit binary notation, in line with the IEEE 754 standard. For more information, you can read this blog post. You can use the toFixed () and Toprecision () methods to solve this problem.

26, the use of for-in to traverse an object's internal properties of the time to pay attention to check

The following code fragment avoids accessing the properties of a prototype while traversing an object property

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 would be equal to 1
Console.log (b); B is equal to 99

28, the cache needs to query or calculate the variables

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

29, pass the parameter to Isfinite () to verify before

Isfinite (0/0); False
Isfinite ("foo"); False
Isfinite ("10"); True
Isfinite (10); True
Isfinite (undifined); False
Isfinite (); False
Isfinite (NULL); True!!!

30, avoid the negative index in the array

var numbersarray = [1,2,3,4,5];
var from = Numbersarray.indexof ("foo"); From is equal to-1
Numbersarray.splice (from,2); would return [5]
Ensure that the parameter passed to splice () is not a negative number.
31. Serialization and deserialization of JSON
var person = {name: ' Saad ', age:26, department: {id:15, Name: ' R&d '}};
var Stringfromperson = json.stringify (person);
/* Stringfromperson is equal to ' {' name ': ' Saad ', ' Age ': ' Department ': {' ID ': ', ' name ': ' R&d '} ' *
var personfromstring = Json.parse (Stringfromperson);
/* personfromstring is equal to person object * *

32. Avoid using the eval () and function () constructors

Using the Eval and function constructors is a very expensive operation because each time they invoke the script engine to convert the source code into executable code.

var func1 = new Function (Functioncode);
var Func2 = eval (functioncode);

33. Avoid using with

using with () inserts a global variable. Therefore, a variable of the same name is obscured by the overridden value.

34. Avoid using for-in to cycle an array

Don't use that.

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

There's a better way

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

35. Transfer functions to SetTimeout () and setinterval () instead of strings

If you pass a string to settimeout () or setinterval (), the string will be parsed as if using eval, which is time-consuming. Do not use:

SetInterval (' dosomethingperiodically () ', 1000);
SetTimeout (' Dosomethingafterfiveseconds () ', 5000)

Recommended Use

SetInterval (dosomethingperiodically, 1000);
SetTimeout (Dosomethingafterfiveseconds, 5000);

36, the use of switch/case statements, rather than a series of if/else

Using Switch/case is more efficient and more elegant (easier to organize code) than in 2. But do not use switch/case when judging more than 10 kinds of cases.

37. Use Switch/case when judging the range of values

function GetCategory (age) {
var category = "";
Switch (TRUE) {
Case isNaN (age):
Category = "Not a age";
Break
Case (age >= 50):
Category = "old";
Break
Case (age <= 20):
Category = "Baby";
Break
Default
Category = "Young";
Break
};
return category;
}
GetCategory (5); would return "Baby"

38. Specify prototype for objects created

It is possible to write a function to create an object with the specified parameters as prototype:

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

39. HTML Escape function

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

40. Avoid using try-catch-finally inside the loop

At run time, each time a catch clause is executed, the captured exception object is assigned to a variable, and in the try-catch-finally structure, the variable is created each time. Do not use this:

var object = [' foo ', ' Bar '], I;
for (i = 0, len = object.length i <len; i++) {
try {
Do something this throws an exception
}
catch (e) {
Handle exception
}
}

It's like this.

var object = [' foo ', ' Bar '], I;
try {
for (i = 0, len = object.length i <len; i++) {
Do something this throws an exception
}
}
catch (e) {
Handle exception
}

41. Set timeout for xmlhttprequests

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 ();

42, processing WebSocket timeout

Usually when the WebSocket connection is established, if there is no activity within 30 seconds, the server will suspend the connection and the firewall will also suspend the connection.

To prevent timeouts, you may need to send empty messages to the server side at intervals. To do this, you can add the following two functions to your code: one to keep the connection, and the other to cancel the connection's retention. With this technique, you can control the timeout problem.

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);
}
}

The KeepAlive () method should be added at the end of the OnOpen () method of the WebSocket connection, while cancelkeepalive () is added at the end of the OnClose () method.

43, remember: The original operator is always funnier than the function call. Use Vanillajs.

For example, do not use this

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

Instead of using this

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

44, when coding, to keep the code neat. Compress the code before it is online.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.