45 JavaScript programming considerations, Skills Daquan _javascript Tips

Source: Internet
Author: User
Tags array length setinterval

JavaScript is a global programming language that can be used for web development, mobile application development (PHONEGAP, Appcelerator), server-side development (Node.js and Wakanda), and so on. JavaScript is still the first language that many beginners have entered into the world of programming. It can be used to display a simple cue box in a browser, or to control a robot by Nodebot or Nodruino. Developers who are able to write structured, high-performance JavaScript code are now the most sought-after recruiters in the market.

In this article, I'll share some of the techniques, tips, and best practices of JavaScript, with the exception of a few, whether it's a browser JavaScript engine or a server-side JavaScript interpreter.

The sample code in this article passes the test on the latest version of Google Chrome 30 (V8 3.20.17.15).

1. Be sure to use the var keyword the first time you assign a value to a variable

Variables are not declared and are directly assignable, and the default is to be a new global variable, avoiding the use of global variables as much as possible.

2, use = = = Replace = =

The = = and the!= operator automatically converts the data type as needed. but = = = and!== do not, they compare values and data types at the same time, which makes them faster than = = and!=.

Copy Code code as follows:

[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, underfined, NULL, 0, FALSE, NaN, null string logical result is False
4, end of line use semicolon

The best thing to do in practice is to use semicolons, and forgetting to write is fine, and most of the JavaScript interpreter is added automatically. For why you should use semicolons, refer to the truth about semicolons in article JavaScript.

5. Use Object Builder

Copy Code code as follows:

function person (firstName, lastName) {
This.firstname = FirstName;
This.lastname = LastName;
}
var Saad = new Person ("Saad", "Mousliki");



6, careful use of typeof, Instanceof and Contructor
The Typeof:javascript unary operator, used to return the original type of the variable as a string, noting that typeof null also returns object, and that most object types (array array, time date, and so on) return the object


Contructor: Internal prototype properties, which can be overridden by code


The instanceof:javascript operator, which searches in the constructor in the prototype chain, returns True if it is found, or returns false


Copy Code code as follows:

var arr = ["A", "B", "C"];
typeof Arr; Returns "Object"
Arr instanceof Array//True
Arr.constructor (); //[]



7. Using a self-calling function
Functions are automatically executed immediately after they are created, often referred to as calling an anonymous function (self-invoked Anonymous function) or directly calling a function expression (Immediately invoked function Expression). The format is as follows:


Copy Code code as follows:

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

8, from the array of random access to members

Copy Code code as follows:

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



9. Get the random number within the specified range
This feature is particularly valuable when generating false data for testing, such as the number of wages in a specified range.


Copy Code code as follows:

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



10, generate a numeric array from 0 to the specified value
Copy Code code as follows:

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



11. Generate Random alphanumeric strings
Copy Code code as follows:

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

12, disturb the order of the number array

Copy Code code as follows:

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] * *



Here we use JavaScript-built array sorting functions, preferably with specialized code (such as the Fisher-yates algorithm), which you can see on the StackOverflow.

13, String to space

Languages such as Java, C #, and PHP implement specialized string-space functions, but they are not in JavaScript, and you can use the following code to provide a trim function for the string object function:

Copy Code code as follows:

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

Copy Code code as follows:

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



15. Converting Objects to arrays
Copy Code code as follows:

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



16, verify whether the number
Copy Code code as follows:

function Isnumber (n) {
Return!isnan (parsefloat (n)) && isfinite (n);
}



17, verify is an array
Copy Code code as follows:

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:


Copy Code code as follows:

Array.isarray (obj); Its a new Array method



If you do not use a frame in the browser, you can also use instanceof, but if the context is too complex, there may be an error.


Copy Code code as follows:

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]
The MyArray constructor has been lost and the instanceof result will not be normal
Constructors are not shared across frame
Arr instanceof Array; False



18, get the maximum and minimum values in the array
Copy Code code as follows:

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 the array
Copy Code code as follows:

var myarray = [12, 222, 1000];
myarray.length = 0; MyArray is equal to [].



20, do not directly from the array delete or remove elements
If the array element uses delete directly, it is not deleted, just the element is placed for undefined. Array element deletion should use splice.

Avoid:

Copy Code code as follows:

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 results are [548, "a", undefinedx1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] * *

and should:

Copy Code code as follows:

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



You can use delete when you delete an object's properties.

21. Truncating an array with the Length property

The previous example uses the Length property to empty the array, and it can also be used to truncate the array:

Copy Code code as follows:

var myarray = [12, 222, 1000, 124, 98, 10];
Myarray.length = 4; MyArray would be equal to [12, 222, 1000, 124].



At the same time, if you make the length property larger, the value of the array is incremented, and the undefined is used to fill the new element. Length is a writable property.


Copy Code code as follows:

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

22, in the condition of the use of logic and OR

Copy Code code as follows:

var foo = 10;
Foo = = && dosomething (); Is the same thing as if (foo = =) dosomething ();
Foo = = 5 | | DoSomething (); Is the same thing as if (foo!= 5) dosomething ();



Logic or can also be used to set default values, such as the default values for function arguments.


Copy Code code as follows:

function DoSomething (arg1) {
Arg1 = Arg1 | | 10; Arg1 'll have as a default value if it ' s not already set
}



23, make the map () function method to the data loop
Copy Code code as follows:

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



24. Keep the specified number of decimal places
Copy Code code as follows:

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



Note that tofixec () returns a string, not a number.

25, floating point calculation problem

Copy Code code as follows:

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



Why, then? Because 0.1+0.2 equals 0.30000000000000004. The number of JavaScript is built on the IEEE 754 standard, and is internally a 64-bit floating-point decimal representation, as you can see how the numbers in JavaScript are encoded.

You can solve this problem by using tofixed () and toprecision ().

26, check the properties of the object by For-in Loop
The following usage can prevent iterations from entering the object's prototype properties.

Copy Code code as follows:

for (var name in object) {
if (Object.hasownproperty (name)) {
Do something with Name
}
}



27. Comma operator
Copy Code code as follows:

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. Temporary storage of variables for calculation and query
In the jquery selector, you can temporarily store the entire DOM element.


Copy Code code as follows:

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



29, check the parameters of incoming isfinite () in advance
Copy Code code as follows:

Isfinite (0/0); False
Isfinite ("foo"); False
Isfinite ("10"); True
Isfinite (10); True
Isfinite (undefined); False
Isfinite (); False
Isfinite (NULL); True, this is particularly noticeable when



30, to avoid the use of negative numbers in the array index
Copy Code code as follows:

var numbersarray = [1,2,3,4,5];
var from = Numbersarray.indexof ("foo"); From is equal to-1
Numbersarray.splice (from,2); would return [5]



Note that the index parameters passed to splice are not negative, and when they are negative, the elements are deleted from the end of the array.

31, using JSON to serialize and deserialize

Copy Code code as follows:

var person = {name: ' Saad ', age:26, department: {id:15, Name: ' R&d '}};
var Stringfromperson = json.stringify (person);
/* Stringfromperson result is "{" name ":" Saad "," Age ":", "department": {"ID": "," name ":" R&d "}" * *
var personfromstring = Json.parse (Stringfromperson);
/* Personfromstring the same value as the person object * *



32. Do not use eval () or function builder
The cost of the eval () and function constructors (functions Consturctor) is large, and each time the JavaScript engine converts the source code into executable code.


Copy Code code as follows:

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



33. Avoid using with ()
Use with () to add a variable to the global scope, so if there are other variables of the same name, it is easy to confuse and the value will be overwritten.

34, do not use for-in array
Avoid:

Copy Code code as follows:

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



But:


Copy Code code as follows:

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



Another advantage is that I and Len two variables are in the first declaration of the For Loop, and the two are only initialized once, which is faster than the following:


Copy Code code as follows:

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



35. Use functions instead of strings to SetInterval () and settimeout ()
If you pass settimeout () and SetInterval () a string, they will be converted in a similar way to Eval, which is certainly slower, so do not use:


Copy Code code as follows:

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



But by:


Copy Code code as follows:

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

36, using Switch/case instead of a large stack of if/else

It's quicker to use switch/case when you're judged to have more than two branches, and it's also more elegant and easier to organize your code, and of course, if you have more than 10 branches, don't use switch/case.

37, the use of digital range in Switch/case

In fact, the case conditions in the switch/case, you can also write:

Copy Code code as follows:



function GetCategory (age) {


var category = "";


Switch (TRUE) {


Case isNaN (age):


Category = "Not a age";


Break


Case (age &gt;= 50):


Category = "old";


Break


Case (age &lt;= 20):


Category = "Baby";


Break


Default


Category = "Young";


Break


};


return category;


}


GetCategory (5); will return to "Baby"





38, using objects as the prototype of the object

This allows you to create a new object that is based on the given object as a parameter:

Copy Code code as follows:

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



39. HTML Field conversion function
Copy Code code as follows:

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



40, do not use try-catch-finally inside the loop

The catch section in Try-catch-finally assigns an exception to a variable when executed, which is constructed into a new variable within the runtime scope.

Avoid:

Copy Code code as follows:

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



and should:


Copy Code code as follows:

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, the use of xmlhttprequests Note set timeout
xmlhttprequests when executing, when there is no response for a long time (such as a network problem, etc.), should abort the connection, you can do this through settimeout ():

Copy Code code as follows:

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



Also note that you should not initiate multiple xmlhttprequests requests at the same time.

42, processing the WebSocket timeout

Typically, after a websocket connection is created, if there is no activity within 30 seconds, the server side will timeout the connection, and the firewall can time-out the connection for which there is no active unit cycle.

To prevent this from happening, you can send an empty message to the server at any given time. You can use these two functions to implement this requirement, one for keeping the connection active, and another for ending this state.

Copy Code code as follows:

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 () function can be placed on the last side of the OnOpen () method of the WebSocket connection, cancelkeepalive () at the very end of the OnClose () method.

43, time note the original operator faster than the function call, using VANILLAJS
For example, do not generally do this:

Copy Code code as follows:

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



This can be replaced by:


Copy Code code as follows:

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



44, attention to the development of the code structure, the line before the inspection and compression of JavaScript code
You can use tools such as JSLint or jsmin to check and compress code.

Related Article

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.