20 practical JavaScript skills and 20 JavaScript skills

Source: Internet
Author: User

20 practical JavaScript skills and 20 JavaScript skills

As we all know, JavaScript is a very popular programming language. developers can use it not only to develop dazzling Web programs, but also to develop mobile applications (such as PhoneGap or Appcelerator ), it also has some Server implementations, such as NodeJS, Wakanda, and Other implementations. In addition, many developers will select JavaScript as the entry language and use it to make small things such as pop-up windows.

In this article, the author will share some useful things such as tips and best practices for JavaScript development. Whether you are a front-end developer or a server-side developer, let's take a look at these tips, they will definitely benefit you.

All the code snippets provided in this article have been tested in the latest version of Chrome 30. This browser uses the V8 JavaScript Engine (V8 3.20.17.15 ).

1. When assigning values to variables for the first time, do not forget the var keyword.

Assign a value to an undeclared variable, which is automatically created as a global variable. In JS development, avoid using global variables.

2. Use = replace =

And never use = or! =.

Copy codeThe Code is as follows:
[10] = 10 // is false
[10] = 10 // is true
'10' = 10 // is true
'10' = 10 // is false
[] = 0 // is true
[] = 0 // is false
''= False // is true but true =" a "is false
''= False // is false

3. Use a semicolon to end a line

Using semicolons at the end of a row is a good habit. Even if a developer forgets the plus sign, the compiler will not prompt anything, because in most cases, the JavaScript parser will automatically add it.

4. Create a constructor

Copy codeThe Code is as follows:
Function Person (firstName, lastName ){
This. firstName = firstName;
This. lastName = lastName;
}

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

5. Be careful when using typeof, instanceof, and constructor

Copy codeThe Code is as follows:
Var arr = ["a", "B", "c"];
Typeof arr; // return "object"
Arr instanceof Array // true
Arr. constructor (); // []

6. Create a Self-calling function

This is usually called an anonymous function called by yourself or call a function expression (LLFE) immediately ). The function is automatically executed when it is created, for example, the following:
Copy codeThe Code is as follows:
(Function (){
// Some private code that will be executed automatically
})();
(Function (a, B ){
Var result = a + B;
Return result;
}) (10, 20)

7. Create a random entry for the Array

Copy codeThe Code is as follows:
Var items = [12,548, 'A', 2, 5478, 'foo', 8852, 'doe ', 2145,119];

Var randomItem = items [Math. floor (Math. random () * items. length)];

8. Obtain a random number in a specific range

The following code is very common. When you need to generate a false data for testing, such as obtaining a random value before the minimum wage and maximum.
Copy codeThe Code is as follows:
Var x = Math. floor (Math. random () * (max-min + 1) + min;

9. Generate a random number between the number 0 and the maximum number.

Copy codeThe Code is as follows:
Var numbersArray = [], max = 100;

For (var I = 1; numbersArray. push (I ++) <max;); // numbers = [100,...]

10. Generate a group of random letters and numbers

Copy codeThe Code is as follows:
Function generateRandomAlphaNum (len ){
Var rdmstring = "";
For (; rdmString. length <len; rdmString + = Math. random (). toString (36). substr (2 ));
Return rdmString. substr (0, len );

}

11. Disrupt the number Array

Copy codeThe Code is as follows:
Var numbers = [5,458,120,-215,228,400,122 205,-85411];
Numbers = numbers. sort (function () {return Math. random ()-0.5 });
/* The array numbers will be equal for example to [120, 5,228,-215,400,458,-85411,122] */

12. String tim Function

The trim function can delete white spaces of strings and can be used in multiple languages such as Java, C #, and PHP.

Copy codeThe Code is as follows:
String. prototype. trim = function () {return this. replace (/^ \ s + | \ s + $/g ,"");};

13. array appending

Copy codeThe Code is as follows:
Var array1 = [12, "foo", {name "Joe"},-2458];

Var array2 = ["Doe", 555,100];
Array. prototype. push. apply (array1, array2 );
/* Array1 will be equal to [12, "foo", {name "Joe"},-2458, "Doe", 555,100] */

14. Convert the parameter object to an array

Copy codeThe Code is as follows:
Var argArray = Array. prototype. slice. call (arguments );

15. Verify that a given parameter is a number

Copy codeThe Code is as follows:
Function isNumber (n ){
Return! IsNaN (parseFloat (n) & isFinite (n );
}

16. Verify that a given parameter is an array

Copy codeThe Code is as follows:
Function isArray (obj ){
Return Object. prototype. toString. call (obj) = '[object Array]';
}

Note that if the toString () method is overwritten, you will not get the expected results.
Or you can write:
Copy codeThe Code is as follows:
Array. isArray (obj); // its a new Array method

Similarly, if you use multiple frames, you can use instancesof. if the content is too large, the results will also fail.

Copy codeThe Code is 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]

// Instanceof will not work correctly, myArray loses his constructor
// Constructor is not shared between frames
Arr instanceof Array; // false

17. obtain the maximum and minimum values from the number array.

Copy codeThe Code is as follows:
Var numbers = [5,458,120,-215,228,400,122 205,-85411];
Var maxInNumbers = Math. max. apply (Math, numbers );
Var minInNumbers = Math. min. apply (Math, numbers );

18. Clear the Array

Copy codeThe Code is as follows:
Var myArray = [12,222,100 0];
MyArray. length = 0; // myArray will be equal to [].

19. Do not use delete to delete items from the array.

Developers can use split instead of delete to delete array items. Instead of deleting undefined items in the array, use delete instead.

Copy codeThe Code is as follows:
Var items = [12,548, 'A', 2, 5478, 'foo', 8852, 'doe ', 2154,119];
Items. length; // return 11
Delete items [3]; // return true
Items. length; // return 11
/* Items will be equal to [12,548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,119] */

Or ......
Copy codeThe Code is as follows:
Var items = [12,548, 'A', 2, 5478, 'foo', 8852, 'doe ', 2154,119];
Items. length; // return 11
Items. splice (3, 1 );
Items. length; // return 10
/* Items will be equal to [12,548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,119] */

The delete method should delete an object attribute.

20. Use the length attribute to shorten the Array

As mentioned above, developers can also use the length attribute to shorten the array.
Copy codeThe Code is as follows:
Var myArray = [12,222,100 0, 124, 98, 10];
MyArray. length = 4; // myArray will be equal to [12,222,100 0, 124].

If the length value of the defined array is too high, the length of the array will change and some undefined values will be filled into the array. The length attribute of the array is not read-only.

Copy codeThe Code is as follows:
MyArray. length = 10; // the new array length is 10
MyArray [myArray. length-1]; // undefined

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.