One, JavaScript tips

Source: Internet
Author: User

1. Don't forget var when declaring variables

2. Equal comparison please use = = = instead of = =

3.undefined, NULL, 0, False, NaN, ' ' (empty string) are false values at the end of the line sealed number

3. Be careful with TypeOf, Instanceof and constructor
The ambiguous relationship between the JavaScript prototype chain and the instanceof operator
Introduction and usage of typeof and instanceof
Triangular relationships between prototype, constructor, and __proto__ in JavaScript
Iife. Refer to JavaScript Execute function expression immediately (iife)

4. Get any element of an array
var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2145, 119];
var Randomitem = Items[math.floor (Math.random () * items.length)];

5. Get any value in a range
var x = Math.floor (Math.random () * (Max-min + 1)) + min;

6. Generate an array of 0~max ([0, 1, 2 ... max])
var a = [], max = 100;
for (var i = 0; A.push (i++) <= Max;);

7. Generate arbitrary-length strings (characters include A-Z 0-9)
function Generaterandomalphanum (len) {
var rdmstring = ";
for (; rdmstring.length < len; rdmstring + = Math.random (). toString (+). substr (2));
return rdmstring.substr (0, Len);
"

8. Array Chaos sequence
var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
Numbers = Numbers.sort (function () {return math.random ()-0.5});
There is a better way than the sort (fisher-yates shuffle), specifically refer to discuss

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

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

10. Converting a pseudo-array to an array
var Argarray = Array.prototype.slice.call (arguments);

11. Judging numbers
function Isnumber (n) {
Return!isnan (parsefloat (n)) && isfinite (n);
}

12. Determine the correct posture of arrays in the array see JavaScript
① getting the array's maximum value
var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
var maxinnumbers = Math.max.apply (Math, numbers);
var mininnumbers = Math.min.apply (Math, numbers);

② emptying an array
var myArray = [12, 222, 1000];
myarray.length = 0; MyArray'll is equal to [].
Delete an array element please do not use Delete, but use splice

③ intercepting an array
var myArray = [12, 222, 1000, 124, 98, 10];
Myarray.length = 4; MyArray'll is equal to [12, 222, 1000, 124].

④ Decimal Reservation (Note that the ToFixed method returns a string value)
var num = 2.443242342;
num = num.tofixed (4); num'll be equal to 2.4432

⑤ floating point problem
0.1 + 0.2 = = = 0.3//Is False
9007199254740992 + 1//is equal to 9007199254740992
9007199254740992 + 2//is equal to 9007199254740994

for (var name in object) {
if ( Object.hasownproperty (name) {
//Do Something with name
}
}

⑦ comma operator
var a = 0;
var B = (a++,);
console.log (a);//A'll be equal to 1
console.log (b);//b is equal to

⑧ cache data (avoid querying the same DOM multiple times)
var navright = document.queryselector (' #right ');
var navup = Document.queryselector (' # Up ');

isfinite (0/0); False
isfinite ("foo");//False
isfinite ("ten");//True
Span style= "color: #ff0000; Font-family: in italics; font-size:16px; " >isfinite (10); True
isfinite (undefined);//False
isfinite ();//False
isfinite (NULL); True!!!

13.json serialization and deserialization
var person = {name: ' Saad ', age:26, department: {id:15, Name: ' R '}};
/* Stringfromperson is equal to "{" Name " : "Saad", "age": +, "department": {"ID": "Name": "R/r}}" */
var personfromstring = Json.parse (Stringfromperson);

14. Avoid using the eval () and function () constructors. To avoid double evaluation, see High performance JavaScript programming practice
avoid using With
avoid traversing array elements with for-in
setinterval () setTimeout () parameters use a function instead of a string. Avoid double evaluation, ibid.
use Switch-case instead of a long list of if-else. This remains to be seen, the good part says to try not to use switch-case statements.

HTML entity encoding
function escapehtml (text) {
var replacements= {"<": "&lt;", ">": "&gt;", "&": "&amp;", "" ":" &quot; "};
Return Text.replace (/[<>& "]/g, function (character) {
return Replacements[character];
});
}

15. Avoid using try-catch-finally in loops
It is not good to write like this:
var object = [' foo ', ' Bar '], I;
for (i = 0, len = object.length; I <len; i++) {
try {
//Do something this throws an exception
}
catch (e) {
//Handle Exception
}
}
this should be the case:
var object = [' foo ', ' Bar '], I;
try {
for (i = 0, len = object.length; I <len; i++) {
//Do something this throws an exception
}
}
catch (e) {
//Handle Exception
}

16.AJAX Set Request timeout (SetTimeout set request Timeout abort AJAX)
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 ();

One, JavaScript tips

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.