Home > Web Front-end > JS Tutorial > 20 practical JavaScript skills to share_javascript skills

20 practical JavaScript skills to share_javascript skills

WBOY
Release: 2016-05-16 16:29:55
Original
1398 people have browsed it

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 some mobile applications (such as PhoneGap or Appcelerator). It also has some services Side implementations, such as NodeJS, Wakanda and other implementations. In addition, many developers choose JavaScript as their entry-level language and use it to make small things such as pop-up windows.

In this article, the author will share with you JavaScript development tips, best practices and other very practical content. Whether you are a front-end developer or a server-side developer, you should take a look at these tips. , they will definitely benefit you.

The code snippets provided in this article have been tested with the latest version of Chrome 30, which uses the V8 JavaScript engine (V8 3.20.17.15).

1. When assigning a value to a variable for the first time, don’t forget the var keyword

Assign a value to an undeclared variable, and the variable will be automatically created as a global variable. In JS development, you should avoid using global variables.

2. Use === to replace ==

And never use = or! =.

Copy code The 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 semicolon as line terminator

It is a good practice to use semicolons where lines terminate. Even if the developer forgets to add a semicolon, the compiler will not have any clue because in most cases, the JavaScript parser will add it automatically.

4. Create constructor

Copy code The code is as follows:

function Person(firstName, lastName){
This.firstName = firstName;
This.lastName = lastName;


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

5. Typeof, instanceof and constructor should be used carefully

Copy code The 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 often referred to as a self-calling anonymous function or an immediately called function expression (LLFE). When the function is created, it will be executed automatically, such as the following:

Copy code The 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 item for the array

Copy code The 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 versatile when you need to generate fake data for testing, such as getting a random value before the minimum salary and the maximum.

Copy code The code is as follows:

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

9. Generate a set of random numbers between the number 0 and the maximum number

Copy code The code is as follows:

var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i ) < max;); // numbers = [0,1,2,3 ... 100]

10. Generate a random set of alphanumeric characters

Copy code The 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. Scramble the digital array

Copy code The code is as follows:

var numbers = [5, 458, 120, -215, 228, 400, 122205, -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, 122205] */

12. String tim function

The trim function can remove whitespace characters from a string and can be used in Java, C#, PHP and other languages.

Copy code The code is as follows:

String.prototype.trim = function(){return this.replace(/^s |s $/g, "");};

13. Array append

Copy code The 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 parameter object to array

Copy code The code is as follows:

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

15. Verify whether a given parameter is a number

Copy code The code is as follows:

function isNumber(n){
Return !isNaN(parseFloat(n)) && isFinite(n);
}

16. Verify that a given parameter is an array

Copy code The code is as follows:

function isArray(obj){
Return Object.prototype.toString.call(obj) === '[object Array]' ;
}

Note that if the toString() method is overridden, you will not get the expected results.
Or you can write like this:

Copy code The code is as follows:

Array.isArray(obj); // its a new Array method

Similarly, if you use multiple frames, you can use instancesof. If there is too much content, the result will also be wrong.

Copy code The 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. Get the maximum and minimum values ​​from the numeric array

Copy code The code is 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);

18. Clear the array

Copy code The code is as follows:

var myArray = [12, 222, 1000];
myArray.length = 0; // myArray will be equal to [].

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

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

Copy code The 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] */

You can also...
Copy code The 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 property.

20. Use the length attribute to shorten the array

As mentioned above to clear the array, developers can also use the length attribute to shorten the array.

Copy code The code is as follows:

var myArray = [12, 222, 1000, 124, 98, 10];
myArray.length = 4; // myArray will be equal to [12, 222, 1000, 124].

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

Copy code The code is as follows:

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1]; // undefined
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template