20 Practical JavaScript tips for sharing _javascript tips

Source: Internet
Author: User
Tags array length alphanumeric characters

As we all know, JavaScript is a very popular programming language, developers use it not only to develop a dazzling web program, you can use it to develop a number of mobile applications (such as PhoneGap or Appcelerator), it also has some service-side implementations, such as Nodejs, Wakanda and other implementations. In addition, many developers will choose JavaScript as an introductory language, using it to make small things like pop-up windows.

In this article, the authors will share the very practical content of the JavaScript development tips, best practices, and so on, whether you're a front-end developer or a server developer, you should take a look at these tips that will definitely benefit you.

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

1. When assigning values to variables for the first time, don't forget the VAR keyword

Assign a value to an undeclared variable that is automatically created as a global variable, and you should avoid using global variables in JS development.

2. Use = = = Replace = =

and never use = or! =

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. Use semicolons as line terminator characters

It is a good practice to use semicolons where the line terminates, even if the developer forgets to add a semicolon, the compiler will not have any hints because in most cases the JavaScript parser will automatically add.

4. Creating constructors

Copy Code code as follows:

function person (firstName, lastName) {
This.firstname = FirstName;
This.lastname = LastName;
}

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

5. Careful use should be made of typeof, Instanceof and constructor

Copy Code code 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 an anonymous function called self invocation or a function expression (Llfe) is called immediately. The function is executed automatically when it is created, like this:

Copy Code code as follows:

(function () {
Some private code that'll be executed automatically
})();
(function (a,b) {
var result = A+b;
return result;
}) (10,20)

7. Create a random item for the array

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

8. Get a random number in a specific range

The following code is very generic, when you need to generate a fake data for testing, such as getting a random value before the minimum wage and the maximum.

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

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

}

11. Disrupt the array of numbers

Copy Code code as follows:

var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
Numbers = Numbers.sort (function () {return math.random ()-0.5});
/* The array numbers'll is equal for example to [120, 5, 228,-215, 400, 458,-85411, 122205] * * *

12. String Tim function

The Trim function can remove white space characters from strings and can be used in many languages, such as Java, C #, and PHP.

Copy Code code as follows:

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

13. Array Append

Copy Code code as follows:

var array1 = [, "foo", {name "Joe"},-2458];

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

14. Convert a Parameter object to an array

Copy Code code as follows:

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

15. Verify that a given parameter is a number

Copy Code code as follows:

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

16. Verify that a given parameter is an array

Copy Code code 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 result.
Or you can write this:

Copy Code code as follows:

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

Similarly, if you use multiple frames, you can use InstancesOf, and if the content is too much, the result will also be wrong.

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]

Instanceof won't work correctly, MyArray loses his constructor
constructor is not shared between frames
Arr instanceof Array; False

17. Get maximum and minimum values from a numeric 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);

18. Empty the array

Copy Code code as follows:

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

19. Do not delete items from the array with delete

Developers can use split to delete an array item instead of using Delete. Instead of deleting items that are not defined in the array, you might as well use delete instead.

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 would be equal to [548, "a", undefinedx1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] * *

can also ...
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 would be equal to [548, "a", 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] * *

The Delete method should delete an object property.

20. Use the Length property to shorten the array

As the empty array mentioned above, developers can also use the length property to shorten 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].

If you define an array of length values that are too high, the length of the array will change, and some undefined values will be populated into the array, and the length property of the array is not read-only.

Copy Code code 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.