JavaScript Chine 44 Strokes "practical" _javascript tips

Source: Internet
Author: User
Tags anonymous array length eval json 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 recruiting people in the market.

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!=.

[Ten] = =/is  false
[ten] = =/is  true
' = = =  /Is true ' ' = = 0/>[]  = = 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 (https://davidwalsh.name/javascript-semicolons).

5. Use Object Builder

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

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

8, from the array of random access to members

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.

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

10, generate a numeric array from 0 to the specified value

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

11. Generate Random alphanumeric strings

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

var numbers = [5, 458, -215, 228, 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

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 = [, "foo", {name "Joe"}, -2458];
var array2 = ["Doe", 555];
Array.prototype.push.apply (Array1, array2);
/* Array1 value is [A, "foo", {name "Joe"}, -2458, "Doe", 555, 100] * *

15. Converting objects 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 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 the browser, you can also use instanceof, but if the context is too complex, there may be an error.

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 constructor has been lost, instanceof result will be abnormal
//constructor is arr instanceof Array that cannot be shared across frame
;//False

18, get the maximum and minimum values in the array

var numbers = [5, 458, -215, 228, 122205, -85411]; 
var maxinnumbers = Math.max.apply (Math, numbers); 
var mininnumbers = Math.min.apply (Math, numbers);

19, empty the array

var myarray = [A, 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:

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2154, 119]; 
Items.length; Return one 
items[3];//return True 
items.length/// 
* Items result is [A, 548, ' a ', undefined X1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] * *

and should:

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2154, 119]; 
Items.length; Return one 
items.splice (3,1); 
Items.length; Return/ 
* 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:

var myarray = [A, 222, 1000, 124, N, ten]; 
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.

Myarray.length = 10; The new array length is 
myarray[myarray.length-1];//undefined

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

var foo = ten; 
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.

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

23, make the map () function method to the data loop

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

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

0.1 + 0.2 = = 0.3/is false 
9007199254740992 + 1/are equal to 9007199254740992
9007199254740992 + 2/are Equa L 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.

for (var name in object) { 
  if (Object.hasownproperty (name)) { 
    //does something with name
  } 
}

27. Comma operator

var a = 0; 
var B = (a++,); 
Console.log (a); A would be equal to 1 
console.log (b);//b. Equal to 99

28. Temporary storage of variables for calculation and query

In the jquery selector, you can temporarily store the entire DOM element.

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

Isfinite (0/0); False
isfinite ("foo");//False
Isfinite ("ten");//True
isfinite (a)  ; True
isfinite (undefined);//False
isfinite ();  False
isfinite (null);//True, when paying special attention

30, to avoid the use of negative numbers in the array index

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

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.

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:

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

But:

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:

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:

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

But by:

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:

function GetCategory (age) { 
  var category = ""; 
  Switch (true) {case 
    isNaN (age): 
      category = ' not ' age '; 
      break; 
    Case (age >=): 
      category = "old"; 
      break; 
    Case (age <=): 
      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:

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

39. HTML Field conversion function

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:

var object = [' foo ', ' Bar '], I; 
for (i = 0, len = object.length i <len; i++) { 
  try { 
    //doing something that throws a exception 
  } 
  Cat CH (e) {  
    //Handle exception 
  } 
}

and should:

var object = [' foo ', ' Bar '], I; 
try { 
  for (i = 0, len = object.length i <len; i++) { 
    //does something that throws a exception 
  } 
}< C22/>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 ():

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.

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:

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

This can be replaced by:

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.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

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.