JavaScript Application Skills Collection [Recommended]_javascript tips

Source: Internet
Author: User
Tags anonymous closure
Convert to Boolean type
All of the values in JavaScript can be implicitly converted to Boolean types, such as:
Copy Code code as follows:
0 = false; True 1 = = true; True ' = = false//true NULL = = False//True
However, these values are not Boolean types.
So when we compare with three equals numbers:
Copy Code code as follows:
0 = = false; False 1 = = true; False ' = = = false//false NULL = = FALSE//False
The question now is how to convert other types to Boolean types:
Copy Code code as follows:
!! 0 = = false; True!! 1 = = true; True!! ' = = FALSE//true!! NULL = = False//True


assign an initial value to a parameter
There is no notion of overloading in JavaScript, but the parameters of functions in JavaScript are optional, and if you write less than one argument, you will be undefinedReplaced.
Copy Code code as follows:
function Plus (base, added) {return base + added;} plus (2); NaN
In this case, Plus (2)And Plus (2, undefined)is equivalent, 2 + undefinedThe result is NaN
The question now is, how do you assign an initial value if you don't pass the second argument?
Copy Code code as follows:
function Plus (base, added) {added = added | | 1; return base + added;} plus (2); 3 Plus (2, 2); 4


Some netizens mentioned plus (2, 0) = 3; It is true, it seems that this place has to do some special treatment:
Copy Code code as follows:
function Plus (base, added) {added = added | | (added = = 0.0:1); return base + added; }


prevent others from loading your page in an IFRAME
If your site becomes very angry, there are a lot of websites that want to link to your site and even want to embed your Web page through an IFRAME.
This is not fun, then how to prevent such behavior?
Copy Code code as follows:
if (top!== window) {top.location.href = window.location.href;}
This code should be placed on each page of your Head, if you want to know that there is no one in the real world, look at Baidu's blog you know.


string Substitution
String.prototype.replaceFunctions are often confusing to programmers who are familiar with C # or Java.
Like what:
Copy Code code as follows:
"Hello World, Hello World," "Replace" (' World ', ' JavaScript '); The ' result ' is ' Hello JavaScript, Hello World '
ReplaceThe first argument to a function is a regular expression.
If you pass a string to the first argument, only the first matching string found is replaced.
To solve this problem, we can use regular expressions:
Copy Code code as follows:
' Hello World, Hello World '. Replace (/world/g, ' JavaScript '); The result is "Hello JavaScript, hello JavaScript"
We can also specify that the case be ignored when replacing:
Copy Code code as follows:
' Hello World, Hello World '. Replace (/hello/gi, ' Hi '); The result was "Hi World, Hi World"


converting arguments into arrays
Predefined variables in a function argumentsNot a real array, but an array-like object.
It has lengthProperties, but there are no slice, push, sort functions, so how to make argumentsWhat about the functions that have these arrays?
That means how to make argumentsinto a real array?
Copy Code code as follows:
function args () {return [].slice.call (arguments, 0);} args (2, 5, 8); [2, 5, 8]


Specify a second argument for the parseint function
parseintThe number used to convert a string to an integer, which is the syntax:
Copy Code code as follows:
parseint (str, [radix])
The second parameter is optional and is used to specify that the first parameter is binary.
If the second argument is not passed, the following rule is followed:
-> if StrStarting with 0x, it is considered to be 16.
-> if StrStarting with 0, it is considered to be a 8-in system.
-> Otherwise, think is 10 into system.
So the following code will be confusing if you don't know the rules:
Copy Code code as follows:
parseint (' 08 '); 0 parseint (' 08 ', 10); 8

So, for security reasons, be sure to parseintSpecifies a second parameter.

remove an element from an array
Maybe we can get through DeleteTo do:
Copy Code code as follows:
var arr = [1, 2, 3, 4, 5]; Delete Arr[1]; Arr [1, Undefined, 3, 4, 5]
can see that DeleteDoes not really delete an element in the array. The deleted element will be undefinedInstead, the length of the array does not change.

In fact, we can pass the Array.prototype Splicefunction to delete an element from an array, as follows:
Copy Code code as follows:
var arr = [1, 2, 3, 4, 5]; Arr.splice (1, 1); Arr [1, 3, 4, 5]


function is also an object
Functions are also objects in JavaScript because we can add attributes to a function.
Like what:
Copy Code code as follows:
function Add () {return add.count++;} add.count = 0; Add (); 0 Add (); 1 Add (); 2
We are the function AddAdded a CountProperty that is used to record the number of times this function was invoked.

Of course this can be done in a more elegant way:
Copy Code code as follows:
function Add () {if (!arguments.callee.count) {arguments.callee.count = 0;} return arguments.callee.count++;} add (); 0 Add (); 1 Add (); 2
Arguments.calleePoint to the function that is currently running.


the maximum value in an array
How to find the maximum value in an array full of numbers, we can do it simply by looping:
Copy Code code as follows:
var arr = [2, 3, 45, 12, 8]; var max = arr[0]; for (var i in arr) {if (Arr[i] > max) {max = arr[i];} Max; 45
Is there another way? We all know that there is one in JavaScript MathObjects are processed numerically:
Copy Code code as follows:
Math.max (2, 3, 45, 12, 8); 45
We can then find the maximum value in the array:
Copy Code code as follows:
var arr = [2, 3, 45, 12, 8]; Math.max.apply (null, arr); 45


Add console.log function to IE
Under Firefox and with the support of firebug, we often use Console.logTo record some information in the console.
But this practice in IE will prevent JavaScript execution (under Firefox is not enabled Firebug case is the same), because at this time there is no ConsoleObject exists.
We can use the following tips to prevent this from happening:
Copy Code code as follows:
if (typeof (console) = = ' undefined ') {window.console = {log:function (msg) {alert (msg);};} console.log (' Debug info. ');


is undefined a reserved keyword in javascript?
It looks like it, but in fact undefined is not a keyword in javascript:
Copy Code code as follows:
var undefined = ' Hello '; Undefined ' Hello '
This code may make you feel weird, but it does work, undefinedJust a predefined variable in JavaScript.
Note: In JavaScript programs, do not do this, the trick is simply to tell you that there is such a thing.


to determine whether a variable is undefined
In both cases, a variable is undefined:
1. Declared variable, but no value assigned
Copy Code code as follows:
var name; name = = = undefined; True
2. This variable has never been declared
Copy Code code as follows:
Name2 = = undefined; Error–name2 is not defined
In the second case, an error is thrown, so if you judge whether a variable is undefined without generating an error?
A common approach is provided below:
Copy Code code as follows:
typeof (name2) = = ' undefined '; True


Pre-loading pictures
Pre-loading pictures are loads of pictures that don't exist on the page so they can be quickly displayed using JavaScript later.
For example, if you want to show another picture when you move the mouse over a picture:
Copy Code code as follows:
var img = new Image (); IMG.SRC = "Clock2.gif";
Copy Code code as follows:

So how do you load a set of pictures? Consider the following code:
Copy Code code as follows:
var Source = [' img1.gif ', ' img2.gif ']; var img = new Image (); for (var i = 0; i < source.length i++) {img.src = Source[i];}
In fact, this code can only preload the last picture, because the other pictures have no time to preload when the loop arrives.
So the correct wording should be:
Copy Code code as follows:
var Source = [' img1.gif ', ' img2.gif ']; for (var i = 0; i < source.length i++) {var img = new Image (); img.src = Source[i];}


Closure (closure)
A closure refers to a local variable within a function, which is still available when the function returns.
When you define another function inside a function, you create a closure, a famous example:
Copy Code code as follows:
function Add (i) {return function () {return ++i;};} Add (2). toString (); "function () {return ++i;}" Add (2) (); 3
Add (2)is a function that can get local variables of external functions I
Reference articles


Private Variable
We often use naming conventions to indicate whether a variable is a private variable (most commonly used to indicate):
Copy Code code as follows:
var person = {_name: ", Getname:function () {return This._name | | ' Not defined '; } }; Person.getname (); "Not defined"
The underscore prefix is used as a convention for private variables, but other developers can still call this private variable:
Copy Code code as follows:
Person._name; // ""
So, how do you create a real private variable in javascript?
The main trick is to use anonymous functions (anonymous function) and closures (closure).
Copy Code code as follows:
var person = {}; (function () {var _name = '; person.getname = function () {return _name | | ' Not defined '; } })(); Person.getname (); "Not Defined" typeof (Person._name); "Undefined"


JavaScript does not have block-level context (Scope)
In JavaScript, block-level code has no context, and in fact only functions have their own context.
Copy Code code as follows:
for (var i = 0; i < 2; i + +) {} I; 2
If you want to create a context, you can use a self executing anonymous function:
Copy Code code as follows:
(function () {for (var i = 0; i < 2; i + +) {}}) (); typeof (i) = = ' undefined '; True


the Strange Nan
Nan is used to indicate that a value is not a number.
Nan behaves strangely in JavaScript because the Nan is not equal to any value (including itself).
Copy Code code as follows:
Nan = = nan; False
Because the following code may cause some people to freak out:
Copy Code code as follows:
parseint (' Hello ', 10); Nan parseint (' Hello ', ten) = = Nan; False parseint (' Hello ', ten) = = NaN; False
So how do you check to see if a value is Nan?
You can use Window.isnan to determine:
Copy Code code as follows:
isNaN (parseint (' Hello ', 10)); True


truth and False values
All values in JavaScript can be implicitly converted to a Boolean type.
In conditional judgments, the following values are automatically converted to false:
null, undefined, NaN, 0, ', False
Therefore, there is no need to make the following complex judgments:
Copy Code code as follows:
if (obj = = Undefined | | obj = = NULL) {}
And that's all you have to do:
Copy Code code as follows:
if (!obj) {}


Modify Arguments
For example, add a value to the arguments:
Copy Code code as follows:
function Add () {Arguments.push (' new value ');} add (); Error-arguments.push is not a function
This is going to go wrong because argumentsNot a real array, no push method.
Solution:
Copy Code code as follows:
function Add () {Array.prototype.push.call (arguments, ' new value '); return arguments} add () [0]; "New Value"


Boolean and new Boolean
We can think of Boolean as a function to produce a Boolean value (Literal):
Copy Code code as follows:
Boolean (false) = = false; True Boolean (') = = false; True
So Boolean (0)And !! 0is equivalent.
We can also think of Boolean as a constructor, by NewTo create a Boolean type of object:
Copy Code code as follows:
New Boolean (false) = = false; False new Boolean (false) = = false; True typeof (New Boolean (false)); "Object" typeof (Boolean (false)); "Boolean"


Quick string concatenation
We often use +Concatenate a shorter string into a long string, which is not a problem in most cases.
However, if you have a large number of strings that need to be connected, this approach will encounter performance problems, especially under IE.
Copy Code code as follows:
var starttime = new Date (); var str = '; for (var i = 0; i < 50000 i++) {str + i;} alert (New Date ()-starttime); Firefox-18ms, ie7-2060ms
Copy Code code as follows:
var starttime = new Date (); var arr = []; for (var i = 0; i < 100000 i++) {Arr.push (i);} var str = Arr.join (""); Alert (new Date ()-starttime); Firefox-38ms, ie7-280ms

You can see that Firefox seems to +Operators are optimized, while IE behaves foolishly.

Unary operator +
In
JavaScript, we can use the unary operator "+" before the string. This converts the string to a number and returns Nan if the conversion fails.
Copy Code code as follows:
2 + ' 1 '; "21" 2 + (+ ' 1 '); 3
If you use + in front of the non string, you will try the transformation in the following order:
    call valueof () call ToString () to convert to a number
Copy Code code as follows:
+new Date; 1242616452016 +new Date = = new Date (). GetTime (); True +new date () = = number (new Date)//True
Reference articles


encodeURI and encodeURIComponent
The Window.encodeuri function is used to encode a URL, but does not encode the following characters: ":", "/", ";", "?".
Window.encodeuricomponent will encode the above characters.
We illustrate by an example:
Copy Code code as follows:
' Index.jsp?page= ' +encodeuri ('/page/home.jsp '); "index.jsp?page=/page/home.jsp" ' index.jsp?page= ' +encodeuricomponent ('/page/home.jsp '); "Index.jsp?page=%2fpage%2fhome.jsp"
As a result, we often choose encodeuricomponent when encoding URLs.


table.innerhtml is read-only property under IE
We often pass through the nodes InnerHTMLproperty to populate the node, for example:
Copy Code code as follows:
<div id= "Container1" > </div>
Copy Code code as follows:
document.getElementById (' Container1 '). InnerHTML = "Hello world!";
But in IE settings table.innerhtmlWill cause an error:
Copy Code code as follows:
<table id= "table1" > </table>
Copy Code code as follows:
Works on Firefox, but fail to work in IE document.getElementById (' table1 '). InnerHTML = "<tr><td>hello& Lt;/td><td>world!</td></tr> ";
In fact, the innerHTML attributes of table, THEAD, TR, select, etc. are read-only under IE.

So if you create a table dynamically, here's a possible way to do this:
Copy Code code as follows:
<div id= "table1" > </div>
Copy Code code as follows:
document.getElementById (' table1 '). InnerHTML = "<table><tr><td>hello</td><td>world! </td></tr></table> ";


0.1+0.2!= 0.3
JavaScript treats decimals as floating-point numbers, so you may have some rounding errors, such as:
Copy Code code as follows:
0.1 + 0.2; 0.30000000000000004
You can specify the number of decimal places rounded by the Tofixed method:
Copy Code code as follows:
(0.1 + 0.2). toFixed (); "0" (0.1 + 0.2). toFixed (1); "0.3"
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.