-
Convert to Boolean type
All values in JavaScript can be implicitly converted to Boolean type, such as: 0 == false; // true<br>
1 == true; // true<br>
'' == false // true<br>
null == false // true<br>
Copy after login
But these values are not Boolean type.
So when we use three equal signs for comparison: 0 === false; // false<br>
1 === true; // false<br>
'' === false // false<br>
null === false // false<br>
Copy after login
The question now is how to convert other types into Boolean types: !!0 === false; // true<br>
!!1 === true; // true<br>
!!'' === false // true<br>
!!null === false // true<br>
Copy after login
-
Assign initial values to parameters
There is no concept of overloading in JavaScript, but the parameters of functions in JavaScript are optional. If one parameter is missing when calling, it will be undefined. In this example, function plus(base, added) {<br>
return base + added;<br>
}<br>
plus(2); // NaN<br>
Copy after login
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?
function plus(base, added) {<br>
added = added || 1;<br>
return base + added;<br>
}<br>
plus(2); // 3<br>
plus(2, 2); // 4<br>
Copy after login
Some netizens mentioned plus(2, 0) = 3; This is indeed the case. It seems that this place needs some special treatment:
function plus(base, added) {<br>
added = added || (added === 0 ? 0 : 1);<br>
return base + added;<br>
}<br>
Copy after login
- Prevent others from loading your page in an Iframe If your website becomes very popular, there will be many websites that want to link to your website, or even your web page. Embed its own web page via IFrame.
This is not fun, so how to stop this behavior?
This code should be placed in the if(top !== window) {<br>
top.location.href = window.location.href;<br>
}<br>
Copy after login
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.
- String Replacement
String.prototype.replace The function often confuses programmers who are very familiar with C# or Java. For example:
'Hello world, hello world'.replace('world', 'JavaScript');<br>
// The result is "Hello JavaScript, hello world"<br>
Copy after login
replace The 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:
We can also specify to ignore case when replacing: 'Hello world, hello world'.replace(/world/g, 'JavaScript');<br>
// The result is "Hello JavaScript, hello JavaScript"<br>
Copy after login
'Hello world, hello world'.replace(/hello/gi, 'Hi');<br>
// The result is "Hi world, Hi world"<br>
Copy after login
- Convert arguments into array The predefined variable in the function
arguments 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? function args() {<br>
return [].slice.call(arguments, 0);<br>
}<br>
args(2, 5, 8); // [2, 5, 8]<br>
Copy after login
- Specify the second parameter for the parseInt function
parseInt is used to convert a string into an integer number. The syntax is: The second parameter is Optional, used to specify the decimal number of the first parameter. parseInt(str, [radix])<br>
Copy after login
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 these rules:
parseInt('08'); // 0<br>
parseInt('08', 10); // 8<br>
Copy after login
So, be sure to specify the second parameter for
parseInt to be on the safe side.
- Delete an element from the array Maybe we can do it through
delete: As you can see, var arr = [1, 2, 3, 4, 5];<br>
delete arr[1];<br>
arr; // [1, undefined, 3, 4, 5]<br>
Copy after login
delete doesn’t really work Deletes an element from 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: var arr = [1, 2, 3, 4, 5];<br>
arr.splice(1, 1);<br>
arr; // [1, 3, 4, 5]<br>
Copy after login
- Functions are also objects In JavaScript, functions are also objects because we can add properties to functions.
For example:
We added the function add() {<br>
return add.count++;<br>
}<br>
add.count = 0;<br>
add(); // 0<br>
add(); // 1<br>
add(); // 2<br>
Copy after login
count attribute to the function add to record the number of times this function has been called.
Of course this can be achieved in a more elegant way:
function add() {<br>
if(!arguments.callee.count) {<br>
arguments.callee.count = 0;<br>
}<br>
return arguments.callee.count++;<br>
}<br>
add(); // 0<br>
add(); // 1<br>
add(); // 2<br>
Copy after login
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:
Is there any other method? We all know that there is a var arr = [2, 3, 45, 12, 8];<br>
var max = arr[0];<br>
for(var i in arr) {<br>
if(arr[i] > max) {<br>
max = arr[i];<br>
}<br>
}<br>
max; // 45<br>
Copy after login
Math object in JavaScript to process numbers: Then, we can find the maximum value in the array like this: Math.max(2, 3, 45, 12, 8); // 45<br>
Copy after login
var arr = [2, 3, 45, 12, 8];<br>
Math.max.apply(null, arr); // 45<br>
Copy after login
- Add console.log function for IE With the support of Firebug under Firefox, we often use
console.log to control The station records some information. 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 prevent this from happening with the following tips:
if (typeof(console) === 'undefined') {<br>
window.console = {<br>
log: function(msg) {<br>
alert(msg);<br>
}<br>
};<br>
}<br>
console.log('debug info.');<br>
Copy after login
Is
-
undefined a reserved keyword in JavaScript? It looks like it, but in fact undefined is not a keyword in JavaScript:
This code may make you feel strange, but it does work normally, var undefined = 'Hello'; <br>
undefined; // 'Hello'<br>
Copy after login
undefined It’s just a predefined variable in JavaScript. Note: Never do this in a JavaScript program, this trick just tells you that this is the case.
-
判断一个变量是否为undefined
两种情况下,一个变量为undefined:
1. 声明了变量,但是没有赋值 var name; <br>
name === undefined; // true<br>
Copy after login
2. 从来没有声明过此变量 name2 === undefined; // error – name2 is not defined<br>
Copy after login
在第二种情况下,会有一个错误被抛出,那么如果判断一个变量是否为undefined而不产生错误呢?
下面提供了一种通用的方法: typeof(name2) === ‘undefined'; // true<br>
Copy after login
-
预加载图片
预加载图片就是加载页面上不存在的图片,以便以后使用JavaScript把它们快速显示出来。
比如你想在鼠标移动到某个图片上时显示另一张图片: var img = new Image(); <br>
img.src = "clock2.gif";<br>
Copy after login
<img src="clock.gif" src="clock.gif" alt="" <BR>
onmouseover="this.src='clock2.gif';" <BR>
onmouseout="this.src=clock.gif';" /><br>
Copy after login
那么,如何加载一组图片呢?考虑如下代码: var source = ['img1.gif','img2.gif']; <br>
var img = new Image(); <br>
for(var i = 0; i < source.length; i++) { <BR>
img.src = source[i]; <BR>
}<BR>
Copy after login
实际上,这段代码只能预加载最后的一张图片,因为其他的图片根本没有时间来预加载在循环到来的时候。
因此正确的写法应该是: var source = ['img1.gif','img2.gif']; <BR>
for(var i = 0; i < source.length; i++) { <BR>
var img = new Image(); <BR>
img.src = source[i]; <BR>
}<BR>
Copy after login
- 闭包(closure)
闭包指的是函数内的局部变量,当函数返回时此变量依然可用。
当你在函数内部定义另外一个函数时,你就创建了一个闭包,一个著名的例子:
function add(i) { <BR>
return function() { <BR>
return ++i; <BR>
}; <BR>
} <BR>
add(2).toString(); // "function () { return ++i; }" <BR>
add(2)(); // 3<BR>
Copy after login
add(2) 是一个函数,它可能获取外部函数的局部变量i 。
参考文章
- 私有变量
我们经常使用命名规范来标示一个变量是否为私有变量(最常用来标示): var person = { <BR>
_name: '', <BR>
getName: function() { <BR>
return this._name || 'not defined'; <BR>
} <BR>
}; <BR>
person.getName(); // "not defined"<BR>
Copy after login
下划线前缀用来作为私有变量的约定,但是其他开发人员仍然可以调用此私有变量: person._name; // ""<BR>
Copy after login
那么,如何在JavaScript中创建一个真正的私有变量呢?
主要技巧是使用匿名函数(anonymous function)和闭包(closure)。 var person = {}; <BR>
(function() { <BR>
var _name = ''; <BR>
person.getName = function() { <BR>
return _name || 'not defined'; <BR>
} <BR>
})(); <br><br>
person.getName(); // "not defined" <BR>
typeof(person._name); // "undefined"<BR>
Copy after login
- JavaScript没有块级上下文(Scope)
JavaScript中块级代码没有上下文,实际上只有函数有自己的上下文。 for(var i = 0; i < 2; i ++) { <br><br>
} <BR>
i; // 2<BR>
Copy after login
如果想创建一个上下文,可以使用自执行的匿名函数: (function (){ <BR>
for(var i = 0; i < 2; i ++) { <br><br>
}<BR>
})(); <BR>
typeof(i) === 'undefined'; // true<BR>
Copy after login
- 怪异的NaN
NaN用来表示一个值不是数字。
NaN在JavaScript中行为很怪异,是因为那NaN和任何值都不相等(包括它自己)。 NaN === NaN; // false<BR>
Copy after login
因为下面的代码可能会让一些人抓狂: parseInt('hello', 10); // NaN <BR>
parseInt('hello', 10) == NaN; // false <BR>
parseInt('hello', 10) === NaN; // false<BR>
Copy after login
那么如何来检查一个值是否NaN?
可以使用window.isNaN来判断: isNaN(parseInt('hello', 10)); // true<BR>
Copy after login
- 真值和假值
JavaScript中所有值都能隐式地转化为Boolean类型。
在条件判断中,下面这些值会自动转化为false:
null, undefined, NaN, 0, ‘', false
因此,不需要做如下复杂的判断: if(obj === undefined || obj === null) { <BR>
}<BR>
Copy after login
而只需要这样做就行了: if(!obj) { <br><br>
}<BR>
Copy after login
- 修改arguments
比如,添加一个值到arguments中: function add() { <BR>
arguments.push('new value'); <BR>
} <BR>
add(); // error - arguments.push is not a function<BR>
Copy after login
这样会出错,因为arguments 不是一个真正的数组,没有push方法。
解决办法: function add() { <BR>
Array.prototype.push.call(arguments, 'new value'); <BR>
return arguments; <BR>
} <BR>
add()[0]; // "new value"<BR>
Copy after login
- Boolean 和 new Boolean
我们可以把Boolean看做是一个函数,用来产生Boolean类型的值(Literal): Boolean(false) === false; // true <BR>
Boolean('') === false; // true<BR>
Copy after login
所以,Boolean(0) 和!!0 是等价的。
我们也可以把Boolean看做是一个构造函数,通过new 来创建一个Boolean类型的对象: new Boolean(false) === false; // false <BR>
new Boolean(false) == false; // true <BR>
typeof(new Boolean(false)); // "object" <BR>
typeof(Boolean(false)); // "boolean"<BR>
Copy after login
- 快速字符串连接
我们经常使用+ 将较短的字符串连接为一个长字符串,这在大部分的情况下是没问题的。
但是如果有大量的字符串需要连接,这种做法将会遇到性能问题,尤其是在IE下。
var startTime = new Date();<BR>
var str = '';<BR>
for (var i = 0; i < 50000; i++) {<BR>
str += i;<BR>
}<BR>
alert(new Date() - startTime); // Firefox - 18ms, IE7 - 2060ms<BR>
Copy after login
var startTime = new Date();<BR>
var arr = [];<BR>
for (var i = 0; i < 100000; i++) {<BR>
arr.push(i);<BR>
}<BR>
var str = arr.join("");<BR>
alert(new Date() - startTime); // Firefox - 38ms, IE7 - 280ms<BR>
Copy after login
可以看到Firefox似乎对+ 操作符进行了优化,而IE则表现的傻乎乎的。
- 一元操作符 +
在JavaScript中,我们可以在字符串之前使用一元操作符“+”。这将会把字符串转化为数字,如果转化失败则返回NaN。
2 + '1'; // "21"<BR>
2 + ( +'1'); // 3<BR>
Copy after login
如果把 + 用在非字符串的前面,将按照如下顺序进行尝试转化:
- 调用valueOf()
- 调用toString()
- 转化为数字
+new Date; // 1242616452016<BR>
+new Date === new Date().getTime(); // true<BR>
+new Date() === Number(new Date) // true<BR>
Copy after login
参考文章
- encodeURI和encodeURIComponent
window.encodeURI函数用来编码一个URL,但是不会对以下字符进行编码:“:”, “/”, “;”, “?”.
window.encodeURIComponent则会对上述字符进行编码。
我们通过一个例子来说明: 'index.jsp?page='+encodeURI('/page/home.jsp'); // "index.jsp?page=/page/home.jsp"<BR>
'index.jsp?page='+encodeURIComponent('/page/home.jsp'); // "index.jsp?page=%2Fpage%2Fhome.jsp"<BR>
Copy after login
因此,在对URL进行编码时我们经常会选择 encodeURIComponent。
- table.innerHTML在IE下是只读属性
我们经常通过节点的innerHTML 属性来填充节点,比如: <div id="container1"> </div><br>
Copy after login
document.getElementById('container1').innerHTML = "Hello World!";
Copy after login
但是在IE下设置table.innerHTML 将会导致错误: <table id="table1"> </table><br>
Copy after login
// works well in Firefox, but fail to work in IE<br>
document.getElementById('table1').innerHTML = "<tr><td>Hello</td><td>World!</td></tr>";<br>
Copy after login
实际上,table, thead, tr, select等元素的innerHTML属性在IE下都是只读的。
那么如果动态的创建一个table呢,下面提供了一种可行的方法: <div id="table1"> </div><br>
Copy after login
document.getElementById('table1').innerHTML = "<table><tr><td>Hello</td><td>World!</td></tr></table>";<br>
Copy after login
-
0.1+0.2 != 0.3
JavaScript将小数作为浮点数对待,所以可能会产生一些四舍五入的错误,比如: 0.1 + 0.2; // 0.30000000000000004
Copy after login
你可以通过toFixed方法指定四舍五入的小数位数: (0.1 + 0.2).toFixed(); // "0"<br>
(0.1 + 0.2).toFixed(1); // "0.3"
Copy after login
javascript 是一种区分大小写的程序语言.
定义数组:
var strweek= new Array(7);
问号表达式
var i= (condition)?A:B;
相当于if-else 语句;condition 成立 执行A ,不成立执行B;
switch 语句
var i=3;
var result="";
swithck(i);
{
case 1;
result="First";
case 2;
result="Second";
case 3;
result="Three";
break;
}
Date类
getDate() getYear() getMont()
getMinutes() getHours() getSeconds()
setTimeout("fution()",1000);