Home  >  Article  >  Web Front-end  >  JavaScript application skills collection [recommended]_javascript skills

JavaScript application skills collection [recommended]_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:47:30967browse
Convert to Boolean type
All values ​​in JavaScript can be implicitly converted to Boolean type, such as:
Copy code The code is as follows:
0 == false; // true 1 == true; // true '' == false // true null == false // true
But these values ​​are Not of type Boolean.
So when we use three equal signs for comparison:
Copy code The code is as follows:
0 == = false; // false 1 === true; // false '' === false // false null === false // false
The question now is how to convert other types into Boolean types:
Copy code The code is as follows:
!!0 === false; // true !!1 === true; / / true !!'' === false // true !!null === false // true


Assign initial values ​​to parameters
There is no repetition in JavaScript The concept of loading, but the parameters of functions in JavaScript are optional. If one parameter is missing when calling, it will be replaced by undefined.
Copy code The code is as follows:
function plus(base, added) { return base added; } plus(2); // NaN
In this example, plus(2) and plus(2, undefined) are equivalent, and the result of 2 undefined is NaN.
The question now is, if the second parameter is not passed, how to assign an initial value to it?
Copy code The code is 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; This is indeed the case. It seems that this Some special processing needs to be done:
Copy code The code is 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 When a website becomes very popular, many websites will want to link to your website, and even want to embed your web page into its own web page through IFrame.
This is not fun, so how to stop this behavior?
Copy code The code is as follows:
if(top !== window) { top.location.href = window.location .href; }
This code should be placed in the head of each of your pages. If you want to know if anyone is using it in real life, just take a look at Baidu's blog and you will know. The


String replacement
String.prototype.replace function often confuses programmers who are very familiar with C# or Java.
For example:
Copy code The code is as follows:
'Hello world, hello world'.replace('world' , 'JavaScript'); // The result is "Hello JavaScript, hello world"
replaceThe first parameter of the function is a regular expression.
If you pass a string as the first parameter, only the first matching string found is replaced.
To solve this problem, we can use regular expressions:
Copy code The code is as follows:
'Hello world , hello world'.replace(/world/g, 'JavaScript'); // The result is "Hello JavaScript, hello JavaScript"
We can also specify to ignore case when replacing:
Copy code The code is as follows:
'Hello world, hello world'.replace(/hello/gi, 'Hi'); // The result is "Hi world, Hi world"


Convert arguments into an array
The predefined variable arguments in the function is not a real array, but an array-like object.
It has the length attribute, but it does not have functions such as slice, push, sort, etc. So how to make arguments have functions that are only available for these arrays?
In other words, how to make arguments into a real array?
Copy code The code is as follows:
function args() { return [].slice.call(arguments, 0); } args(2, 5, 8); // [2, 5, 8]


Specify the second parameter for the parseInt function
parseInt Used to convert a string into an integer number, the syntax is:
Copy the code The code is as follows:
parseInt( str, [radix])
The second parameter is optional and is used to specify the decimal number of the first parameter.
If the second parameter is not passed, the following rules are followed:
-> If str starts with 0x, it is considered to be hexadecimal.
->If str starts with 0, it is considered to be octal.
-> Otherwise, it is considered to be decimal.
So the following code will be confusing if you don’t know the rules:
Copy the code The code is as follows:
parseInt('08'); // 0 parseInt('08', 10); // 8

So, for safety reasons, you must specify the second parameter for parseInt .

Delete an element from the array
Maybe we can do it by delete:
Copy code The code is as follows:
var arr = [1, 2, 3, 4, 5]; delete arr[1]; arr; // [1, undefined, 3, 4, 5]
As you can see, delete cannot actually delete an element in the array. The deleted elements will be replaced by undefined, and the length of the array will not change.

In fact, we can delete elements in the array through the splice function in Array.prototype, as shown below:
Copy code The code is as follows:
var arr = [1, 2, 3, 4, 5]; arr.splice(1, 1); arr; // [1, 3 , 4, 5]


Functions are also objects
In JavaScript, functions are also objects because we can add properties to functions.
For example:
Copy code The code is as follows:
function add() { return add.count ; } add. count = 0; add(); // 0 add(); // 1 add(); // 2
We added the count attribute to the function add, using to record the number of times this function is called.

Of course this can be achieved in a more elegant way:
Copy code The code is as follows:
function add() { if(!arguments.callee.count) { arguments.callee.count = 0; } return arguments.callee.count ; } add(); // 0 add(); // 1 add(); / / 2
arguments.callee points to the currently running function.


Maximum value in the array
How to find the maximum value in an array full of numbers, we can simply do it through a loop:
Copy code The code is 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 any other method? We all know that there is a Math object in JavaScript to process numbers:
Copy code The code is as follows:
Math.max(2, 3, 45, 12, 8); // 45
Then, we can find the maximum value in the array like this:
Copy code The code is as follows:
var arr = [2, 3, 45, 12, 8]; Math.max.apply(null, arr); // 45


Add console.log function for IE
Under Firefox and with the support of Firebug, we often use console.log to record some information in the console.
However, this approach will prevent the execution of JavaScript under IE (the same is true when Firebug is not enabled under Firefox), because there is no console object at all at this time.
We can use the following tips to prevent this situation from happening:
Copy code The code is as follows:
if ( typeof(console) === 'undefined') { window.console = { log: function(msg) { alert(msg); } }; } console.log('debug info.');

Is
undefined a reserved keyword in JavaScript?
looks like it, but in fact undefined is not a keyword in JavaScript:
Copy code The code is as follows:
var undefined = 'Hello'; undefined; // 'Hello'
This code may seem strange to you, but it does work. undefined is just JavaScript Just a predefined variable.
Note: Never do this in a JavaScript program, this trick just tells you that this is the case.


Determine whether a variable is undefined
In two cases, a variable is undefined:
1. The variable is declared, but no value is assigned
Copy code The code is as follows:
var name; name === undefined; // true
2. This has never been declared Variable
Copy code The code is as follows:
name2 === undefined; // error – name2 is not defined
In the second case, an error will be thrown, so what if you determine whether a variable is undefined without generating an error?
A general method is provided below:
Copy code The code is as follows:
typeof(name2) == = 'undefined'; // true


Preload images
Preload images is to load images that do not exist on the page so that they can be quickly displayed later using JavaScript .
For example, if you want to display another picture when the mouse moves over a picture:
Copy the code The code is as follows:
var img = new Image(); img.src = "clock2.gif";
Copy code The code is as follows:

So, how to load a set of images? Consider the following code:
Copy code The code is 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 Load the last image, because the other images don't have time to preload when the loop comes.
So the correct way to write it should be:
Copy code The code is 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 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 The code is as follows:
function add(i) { return function() { return i; }; } add(2).toString(); // "function () { return i; }" add(2)(); // 3
add(2) is a function that may obtain the local variable i of the external function.
Reference article


Private variables
We often use naming conventions to indicate whether a variable is a private variable (most commonly used to indicate) :
Copy code The code is 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 The code is as follows:
person._name; // ""
So, how to create a real person in JavaScript What about private variables?
The main trick is to use anonymous functions and closures.
Copy code The code is as follows:
var person = {}; (function() { var _name = ''; person .getName = function() { return _name || 'not defined'; } })(); person.getName(); // "not defined" typeof(person._name); // "undefined"


JavaScript has no block-level context (Scope)
Block-level code in JavaScript has no context. In fact, only functions have their own context.
Copy code The code is 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 The code is as follows:
(function (){ for(var i = 0; i < 2; i ) { } })(); typeof(i) === 'undefined'; // true


Weird NaN
NaN is used to indicate that a value is not a number.
NaN behaves strangely in JavaScript because NaN is not equal to any value (including itself).
Copy code The code is as follows:
NaN === NaN; // false
because the following code may Driving some people crazy:
Copy code The code is as follows:
parseInt('hello', 10); // NaN parseInt('hello', 10) == NaN; // false parseInt('hello', 10) === NaN; // false
So how to check whether a value is NaN?
You can use window. isNaN to judge:
Copy code The code is as follows:
isNaN(parseInt('hello', 10)); // true


True and false values ​​
All values ​​in JavaScript can be implicitly converted to Boolean type.
In conditional judgment, the following values ​​will be automatically converted to false:
null, undefined, NaN, 0, '', false
Therefore, there is no need to make the following complicated judgments :
Copy code The code is as follows:
if(obj === undefined || obj === null) { }
Just do this:
Copy the code The code is as follows:
if(!obj) { }


Modify arguments
For example, add a value to arguments:
Copy code The code is as follows:
function add() { arguments.push('new value'); } add(); // error - arguments.push is not a function
will go wrong because arguments is not a real array and has no push method.
Solution:
Copy code The code is 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, used to generate Boolean type values ​​(Literal):
Copy code The code is as follows:
Boolean(false) === false; // true Boolean('') === false; // true
So, Boolean(0) and !!0are equivalent.
We can also regard Boolean as a constructor and create a Boolean type object through new:
Copy code The code is as follows:
new Boolean(false) === false; // false new Boolean(false) == false; // true typeof(new Boolean(false)); // " object" typeof(Boolean(false)); // "boolean"


Fast string concatenation
We often use to convert shorter Strings are concatenated into one long string, which is fine in most cases.
But if there are a large number of strings that need to be concatenated, this approach will encounter performance problems, especially under IE.
Copy code The code is 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 The code is 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 Firefox It seems that the operator has been optimized, while IE behaves stupidly.

Unary operator
In JavaScript, we can use the unary operator " " before a string. This will convert the string to a number, returning NaN if the conversion fails.
Copy code The code is as follows:
2 '1'; // "21" 2 ( '1' ); // 3
If used in front of a non-string, conversion attempts will be made in the following order:
    Call valueOf() and call toString() to convert it into a number
Copy the code The code is as follows:
new Date; // 1242616452016 new Date === new Date().getTime(); // true new Date() === Number(new Date) // true
Reference article


encodeURI and encodeURIComponent
window.encodeURI function is used to encode a URL, but the following characters will not be encoded: ":", "/", " ;", "?".
window.encodeURIComponent will encode the above characters.
We illustrate with an example:
Copy code The code is 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=/page/home.jsp"
Therefore, we often choose encodeURIComponent when encoding URLs.


table.innerHTML is a read-only attribute under IE
We often fill nodes through the node's innerHTML attribute, such as:
Copy code The code is as follows:
Copy code The code is as follows:
document.getElementById('container1').innerHTML = "Hello World!";
But Setting table.innerHTML under IE will result in an error:
Copy code The code is as follows:
Copy code The code is as follows:
// works well in Firefox, but fail to work in IE document.getElementById('table1').innerHTML = "HelloWorld!< ;/tr>";
In fact, the innerHTML attributes of table, thead, tr, select and other elements are all read-only under IE.

So if you create a table dynamically, the following provides a feasible method:
Copy the code The code is as follows:
Copy code The code is as follows:
document.getElementById('table1').innerHTML = "";

0.1 0.2 != 0.3
JavaScript treats decimals as floating point numbers, so some rounding errors may occur, such as:
Copy code The code is as follows:
0.1 0.2; // 0.30000000000000004
You can specify the rounding decimal through the toFixed method Number of digits:
Copy code The code is as follows:
(0.1 0.2).toFixed(); // "0" ( 0.1 0.2).toFixed(1); // "0.3"
Statement:
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
HelloWorld!