- Convert to Boolean type
All values in JavaScript can be implicitly converted to the Boolean type, for example: 0 == false; // true
1 == true; // true
'' == false // true
null == false // true
However, these values are not of the Boolean type.
Therefore, when we use three equal signs for comparison: 0 === false; // false
1 === true; // false
'' === false // false
null === false // false
The question now is how to convert other types to the Boolean Type: !!0 === false; // true
!!1 === true; // true
!!'' === false // true
!!null === false // true
- Assign initial values to parameters
JavaScript does not support overload, but function parameters in JavaScript are optional.Undefined. function plus(base, added) {
return base + added;
}
plus(2); // NaN
In this example,Plus (2)AndPlus (2, undefined)Is equivalent,2 + undefinedThe result isNaN.
Now the question is, if the second parameter is not passed, how can we assign an initial value to it? function plus(base, added) {
added = added || 1;
return base + added;
}
plus(2); // 3
plus(2, 2); // 4
Some netizens mentioned that plus (2, 0) = 3; indeed, it seems that some special processing needs to be done in this place: function plus(base, added) {
added = added || (added === 0 ? 0 : 1);
return base + added;
}
- Prevent others from loading your page in Iframe
If your website becomes very popular, many websites want to link to your website, or even embed your webpage into its own Webpage Through IFrame.
This is not fun, so how can we prevent such behavior? if(top !== window) {
top.location.href = window.location.href;
}
This code should be placed on every page of yourHeadIf you want to know that no one is using the baidu blog, you will know.
- String replacement
String. prototype. replaceFunctions often confuse programmers who are very familiar with C # or Java.
For example: '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 to the first parameter, only the matching string found in the first parameter is replaced.
To solve this problem, we can use a regular expression: 'Hello world, hello world'.replace(/world/g, 'JavaScript');
// The result is "Hello JavaScript, hello JavaScript"
We can also specify that case sensitivity is ignored during replacement: 'Hello world, hello world'.replace(/hello/gi, 'Hi');
// The result is "Hi world, Hi world"
- Convert arguments to an array
Predefined variables in the functionArgumentsIt is not a real array, but an object similar to an array.
It hasLengthAttribute, but there are no slice, push, sort and other functions, so how to makeArgumentsWhat about functions with these arrays?
That is, how to makeArgumentsInto a real array? function args() {
return [].slice.call(arguments, 0);
}
args(2, 5, 8); // [2, 5, 8]
- Specify the second parameter for the parseInt function.
ParseIntThe number used to convert a string to an integer. Syntax: parseInt(str, [radix])
The second parameter is optional and used to specify the first parameter in hexadecimal notation.
If the second parameter is not passed, follow the following rules:
-> IfStrStarting with 0x, it is considered as hexadecimal.
-> IfStrStarting with 0, it is considered to be in octal format.
-> Otherwise, it is considered to be in decimal format.
The following code will be confusing if you do not know the rules: parseInt('08'); // 0
parseInt('08', 10); // 8
Therefore, to ensure security, you mustParseIntSpecify the second parameter.
- Deletes an element from an array.
Maybe we can useDeleteTo: var arr = [1, 2, 3, 4, 5];
delete arr[1];
arr; // [1, undefined, 3, 4, 5]
As you can see,DeleteIt cannot really delete an element in the array. The deleted element will beUndefinedThe length of the array does not change.
In fact, we can useSpliceFunction to delete elements in the array, as shown below: 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 attributes for functions.
For example: function add() {
return add.count++;
}
add.count = 0;
add(); // 0
add(); // 1
add(); // 2
For functionsAddAddedCountAttribute to record the number of times this function is called.
Of course, this can be achieved in a more elegant way: function add() {
if(!arguments.callee.count) {
arguments.callee.count = 0;
}
return arguments.callee.count++;
}
add(); // 0
add(); // 1
add(); // 2
Arguments. calleePoint to the currently running function.
- Maximum Value in the array
How to find the maximum value in an array of all numbers can be simply done through loops: 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 way? We all know that JavaScript hasMathObjects to process numbers: Math.max(2, 3, 45, 12, 8); // 45
Then, we can find the maximum value in the array as follows: var arr = [2, 3, 45, 12, 8];
Math.max.apply(null, arr); // 45
- Add for IEConsole. logFunction
We often use Firebug in Firefox.Console. logTo record some information in the console.
However, this method will block JavaScript Execution in IE (the same is true if Firebug is not enabled in Firefox), because there is noConsoleObject exists.
We can use the following tips to prevent such a situation: if (typeof(console) === 'undefined') {
window.console = {
log: function(msg) {
alert(msg);
}
};
}
console.log('debug info.');
- UndefinedIs it a reserved keyword in JavaScript?
It looks like yes, but in fact undefined is not a keyword in JavaScript: var undefined = 'Hello';
undefined; // 'Hello'
This code may surprise you, but it does work properly,UndefinedIt's just a predefined variable in JavaScript.
Note: In JavaScript programs, do not do this. This technique only tells you the same thing.
- Determines whether a variable is undefined.
In either case, a variable is undefined:
1. variables are declared, but no value is assigned. var name;
name === undefined; // true
2. This variable has never been declared name2 === undefined; // error – name2 is not defined
In the second case, an error is thrown. If a variable is undefined and no error is generated?
The following provides a general method: typeof(name2) === ‘undefined'; // true
- Preload Images
Preload images are images that do not exist on the page, so that they can be quickly displayed using JavaScript later.
For example, if you want to show another image when you move the mouse over an image: var img = new Image();
img.src = "clock2.gif";
onmouseover="this.src='clock2.gif';"
onmouseout="this.src=clock.gif';" />
So how to load a group of images? Consider the following code: 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 pre-load the last image, because other images do not have time to pre-load when the loop comes.
Therefore, the correct statement should be: var source = ['img1.gif','img2.gif'];
for(var i = 0; i < source.length; i++) {
var img = new Image();
img.src = source[i];
}
- Closure (closure)
Closure refers to the local variable in the function. This variable is still available when the function returns.
When you define another function inside the function, you create a closure, a famous example:
function add(i) {
return function() {
return ++i;
};
}
add(2).toString(); // "function () { return ++i; }"
add(2)(); // 3
Add (2)Is a function that may obtain local variables of an external function.I.
References
- Private variable
We often use naming conventions to indicate whether a variable is a private variable (most commonly used ): var person = {
_name: '',
getName: function() {
return this._name || 'not defined';
}
};
person.getName(); // "not defined"
The underline prefix is used as a convention for private variables, but other developers can still call this private variable: person._name; // ""
So, how to create a real private variable in JavaScript?
The main technique is to use an anonymous function and a closure ). 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. In fact, only functions have their own context. for(var i = 0; i < 2; i ++) {
}
i; // 2
To create a context, use the self-executed anonymous function: (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 acts strangely in JavaScript because NaN is not equal to any value (including itself ). NaN === NaN; // false
The following code may drive some people crazy: 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 determine: isNaN(parseInt('hello', 10)); // true
- True and false values
All values in JavaScript can be implicitly converted to the Boolean type.
In condition determination, the following values are automatically converted to false:
Null, undefined, NaN, 0, '', false
Therefore, the following complex judgment is not required: if(obj === undefined || obj === null) {
}
You only need to do this: if(!obj) {
}
- Modify arguments
For example, add a value to arguments: function add() {
arguments.push('new value');
}
add(); // error - arguments.push is not a function
This will cause errors becauseArgumentsIt is not a real array and there is no push method.
Solution: function add() {
Array.prototype.push.call(arguments, 'new value');
return arguments;
}
add()[0]; // "new value"
- Boolean and new Boolean
We can regard Boolean as a function to generate a Boolean value (Literal ): Boolean(false) === false; // true
Boolean('') === false; // true
So,Boolean (0)And!! 0Is equivalent.
We can also regard Boolean as a constructor.NewCreate a Boolean object: new Boolean(false) === false; // false
new Boolean(false) == false; // true
typeof(new Boolean(false)); // "object"
typeof(Boolean(false)); // "boolean"
- Fast string connection
We often use+Concatenate a short string into a long string, which is normal in most cases.
However, if a large number of strings need to be connected, this method will encounter performance problems, especially in IE.
var startTime = new Date();
var str = '';
for (var i = 0; i < 50000; i++) {
str += i;
}
alert(new Date() - startTime); // Firefox - 18ms, IE7 - 2060ms
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
As you can see, Firefox seems to be+The operator is optimized, While IE is dumb.
- Unary operator +
In JavaScript, we can use the unary operator "+" before the string ". This will convert the string to a number. If the conversion fails, NaN is returned.
2 + '1'; // "21"
2 + ( +'1'); // 3
If + is used before a non-string, the conversion will be attempted in the following order:
- Call valueOf ()
- Call toString ()
- Convert to number
+new Date; // 1242616452016
+new Date === new Date().getTime(); // true
+new Date() === Number(new Date) // true
References
- EncodeURI and encodeURIComponent
The window. encodeURI function is used to encode a URL, but does not encode the following characters: ":", "/", ";", "?".
Window. encodeURIComponent encodes the preceding characters.
Here is an example: '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"
Therefore, we often choose encodeURIComponent when encoding the URL.
- Table. innerHTML is a read-only attribute in IE.
We often useInnerHTMLAttribute to fill nodes, such: <div id="container1"> </div>
document.getElementById('container1').innerHTML = "Hello World!";
But set it in IETable. innerHTMLThis will cause an error:<table id="table1"> </table>
// works well in Firefox, but fail to work in IE
document.getElementById('table1').innerHTML = "<tr><td>Hello</td><td>World!</td></tr>";
In fact, the innerHTML attributes of table, thead, tr, select, and other elements are read-only in IE.
If you create a table dynamically, the following provides a feasible method:<div id="table1"> </div>
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 some rounding errors may occur, such:0.1 + 0.2; // 0.30000000000000004
You can use the toFixed method to specify the number of decimal places: (0.1 + 0.2).toFixed(); // "0"
(0.1 + 0.2).toFixed(1); // "0.3"
Javascript is a case-sensitive programming language.
It is equivalent to the if-else statement; the condition is set to execute A, and the condition is not set to execute B;