12 very useful JavaScript tips, must-see!

Source: Internet
Author: User
Tags array length

Tip: This article is to organize other people's articles, the author is more, it is difficult to tell who the original author.

1) Use!! Convert a variable to a Boolean type

Sometimes, we need to check that some variables exist, or whether it has valid values, and thus treats their values as true. For such a check, you can use!! (double negation operator), he can automatically convert any type of data to a Boolean value, only 0, NULL, "", Undefined, or Nan will return false, others will return true. See a simple example:

functionAccount (Cash) { This. Cash =cash;  This. Hasmoney =!!Cash;} varAccount =NewAccount (100.50);        Console.log (Account.cash); //100.50Console.log (Account.hasmoney);//true       varEmptyaccount =NewAccount (0);        Console.log (Emptyaccount.cash); //0Console.log (Emptyaccount.hasmoney);//false

2) use + to convert variables into numbers

This conversion is simple, but it only fits into a numeric string, otherwise it returns Nan (not a number). See Example:

function Tonumber (strnumber) {    return +Strnumber;} Console.log (Tonumber (//342
Console.log (Tonumber (' 324s ')); NaN
can also be used to convert a date, return a result as a timestamp
Console.log (+new Date ());

3) Short-circuit condition

This code is often encountered in writing code:

  

if (conected) {    login ();}

You can use && (and connectors) to shorten the code, and the above code can be reduced to

Conected&&login ();

You can also use this method to check whether some properties or methods exist in an object

User&&user.login ();

4) Use | | Set default values

This feature has default parameters in ES6. In order to emulate this feature in a legacy browser, you can use | | (or operator), and the default value as his second argument. If the first parameter returns FALSE, the second parameter is returned as a default value

 

 function   user (name,age) { this . Name = name| | '    Olive Queen ' ;  this . Age = age| | 27;}  var  user1 = new   user (); Console.log (user1.name);  // olive Queen  console.log (user1.age); // 27  var  user2 = new  User (' liming ', 25 // liming  console.log (user2.age); // 25  

5) Cache Arr.length in the loop

  This technique is very simple and can avoid a huge impact on performance when looping through large arrays. For example for loops

var arr = [A/b, ' A ', ' DS ', 4];  for (var i = 0;i<arr.length;i++) {    console.log (arr[i]);}

For the decimal group is OK, the larger array then every time the loop will get arr.length, which will produce a certain delay, in order to avoid this situation, before the start of the For loop cache Arr.length

var arr = [A/b, ' A ', ' DS ', 4]; var len = arr.length;  for (var i = 0;i<len;i++) {    console.log (arr[i]);}

Or

var arr = [A/b, ' A ', ' DS ', 4];  for (var i = 0,len = arr.length;i<len;i++) {    console.log (arr[i]);}

6) Check the properties in the object

This technique is useful when you need to check if certain properties exist, and avoid running undefined functions or properties. This technique can also be used in troubleshooting browser compatibility issues. For example, the perfect way to get elements by ID

if inch document) {    document.queryselector (' #id ');} Else {    document.getElementById (' id ');}

7) Gets the last element of the array

Array. Prototype.slice (begin,end) can be used to crop an array. However, if you do not set a value for the end parameter, the function automatically sets the end to an array length value. If the value of begin is set to copy, the reciprocal element is obtained from the array:

var arr = [1,2,3,4,5];console.log (Arr.slice (-1));//[6]
Console.log (Arr.slice (-2));//[5,6]
Console.log (Arr.slice (-3));//[4,5,6]

8) Array truncation

This technique can lock the size of an array, which is useful for deleting a fixed number of elements in an array.

var arr = [1,2,3,4,5,6,7,8,9,10= 5; Console.log (arr); // [1,2,3,4,5]  = 7; console.log (arr); // [1,2,3,4,5,undefined,undefined]

If the value set by Arr.length is greater than the current array length, the element that is exceeded is allocated as undefined

9) Replacing array elements

var str = ' John John '; Console.log (Str.replace (/hn/, ' nan ')); // Jonan JohnConsole.log (str.replace (/hn/g, ' Nan ')); // Jonan Jonan

This appears to be adding the contents of the regular expression to the array substitution element, the global match G

10) Merging arrays

It is common to merge arrays, use the Array.concat () method, and the string can be considered an array

var str1 = ' Hello '; var str2 = ' world '; Console.log (Str1.concat (str2)); // HelloWorld
var = [STR3];
var STR4 = [4,5,6];
Console.log (Str3.concat (STR4));//[1,2,3,4,5,6]

However, this method is not suitable for large arrays because he creates a new array internally and consumes a lot of memory. The original author recommends the use of Array.push.apply (ARR1,ARR2), but in practice it is found that the returned result is always the length of the last array, not the elements of the array And there are bloggers who have done test experiments on the performance of Array.concat and Array.push.apply. The result shows that the array length of the Array.concat operation is not displayed, and that the array of Array.oush.apply operations differs by browser, and generally cannot exceed 100,000.

Scripting House A friend wrote a "about JS array append array using push.apply problem", to discuss the problem of Array.push.apply, finally using foreach, not only can avoid the problem of the array too large, and from the performance considerations of foreach is also the fastest.

var arr = [1,2,3,4,5,6,7,8,9];arr.foreach (function(a) {    console.log (a);});

However, in IE, the method does not work properly, suggesting that the array does not support this property or this method, ie, the array does not have a foreach method. But you can add a prototype method

    //Array.foreach implementation for IE support:     //Https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach    if(!Array.prototype.forEach) {Array.prototype.forEach=function(callback, Thisarg) {varT, K; if( This==NULL) {                  Throw NewTypeError ("This is a null or not defined"); }              varO = Object ( This); varLen = o.length >>> 0;//Hack to convert O.length to a UInt32            if({}.tostring.call (callback)! = "[Object Function]") {                  Throw NewTypeError (callback + "is not a function"); }              if(thisarg) {T=Thisarg; } k= 0;  while(K <Len) {                  varKvalue; if(kinchO) {Kvalue=O[k];                  Callback.call (T, Kvalue, K, O); } k++;      }          }; }  

11)

12 very useful JavaScript tips, must-see!

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.