JavaScript 学习技巧_javascript技巧
-
转化为Boolean类型
所有JavaScript中的值都能隐式的转化为Boolean类型,比如:但是这些值都不是Boolean类型。0 == false; // true<BR> 1 == true; // true<BR> '' == false // true<BR> null == false // true<BR>
Copier après la connexion
因此当我们使用三个等于号进行比较时:现在的问题是如何将其他类型转化为Boolean类型:0 === false; // false<BR> 1 === true; // false<BR> '' === false // false<BR> null === false // false<BR>
Copier après la connexion!!0 === false; // true<BR> !!1 === true; // true<BR> !!'' === false // true<BR> !!null === false // true<BR>
Copier après la connexion
- 为参数赋初值
JavaScript中没有重载的概念,但是JavaScript中函数的参数都是可选的,如果调用时少写了一个参数,将会被undefined 所代替。在这个例子中,plus(2) 和plus(2, undefined) 是等价的,2 + undefined 的结果是NaN 。function plus(base, added) {<BR> return base + added;<BR> }<BR> plus(2); // NaN<BR>
Copier après la connexion
现在的问题是,如果没有传递第二个参数,如何为它赋初值呢?function plus(base, added) {<BR> added = added || 1;<BR> return base + added;<BR> }<BR> plus(2); // 3<BR> plus(2, 2); // 4<BR>
Copier après la connexion
有网友提到 plus(2, 0) = 3; 的确是这样的,看来这个地方还要做一些特殊处理:function plus(base, added) {<BR> added = added || (added === 0 ? 0 : 1);<BR> return base + added;<BR> }<BR>
Copier après la connexion
- 阻止别人在Iframe中加载你的页面
如果你的网站变得非常有人气的时候,就有很多网站想链接到你的网站,甚至想把你的网页通过IFrame嵌入它自己的网页。
这样就不好玩了,那么如何来阻止这样行为呢?这段代码应该放在你每个页面的head 中,如果你想知道现实中有没人在用,看看baidu的博客你就知道了。if(top !== window) {<BR> top.location.href = window.location.href;<BR> }<BR>
Copier après la connexion
- 字符串替换
String.prototype.replace 函数经常会让那些非常熟悉C#或者Java的程序员感到迷惑。
比如:replace 函数的第一个参数是正则表达式。'Hello world, hello world'.replace('world', 'JavaScript');<BR> // The result is "Hello JavaScript, hello world"<BR>
Copier après la connexion
如果你传递一个字符串到第一个参数,则只有第一个找到的匹配字符串被替换。
为了解决这个问题,我们可以使用正则表达式:我们还可以指定在替换时忽略大小写:'Hello world, hello world'.replace(/world/g, 'JavaScript');<BR> // The result is "Hello JavaScript, hello JavaScript"<BR>
Copier après la connexion'Hello world, hello world'.replace(/hello/gi, 'Hi');<BR> // The result is "Hi world, Hi world"<BR>
Copier après la connexion
- 将arguments转化为数组
函数中的预定义变量arguments 并非一个真正的数组,而是一个类似数组的对象。
它具有length 属性,但是没有slice, push, sort等函数,那么如何使arguments 具有这些数组才有的函数呢?
也就是说如何使arguments 变成一个真正的数组呢?function args() {<BR> return [].slice.call(arguments, 0);<BR> }<BR> args(2, 5, 8); // [2, 5, 8]<BR>
Copier après la connexion
- 为parseInt函数指定第二个参数
parseInt 用来将字符串转化为整形的数字,语法为:其中第二个参数是可选的,用来指定第一个参数是几进制的。parseInt(str, [radix])<BR>
Copier après la connexion
如果没有传递第二个参数,则按照如下规则:
->如果str 以 0x 开头,则认为是16进制。
->如果str 以 0 开头,则认为是8进制。
->否则,认为是10进制。
因此如下的代码将会让人很迷惑,如果你不知道这些规则:parseInt('08'); // 0<BR> parseInt('08', 10); // 8<BR>
Copier après la connexion
所以,安全起见一定要为parseInt 指定第二个参数。
- 从数组中删除一个元素
或许我们可以通过delete 来做到:可以看到,delete 并不能真正的删除数组中的一个元素。删除的元素会被undefined 取代,数组的长度并没有变化。var arr = [1, 2, 3, 4, 5];<BR> delete arr[1];<BR> arr; // [1, undefined, 3, 4, 5]<BR>
Copier après la connexion
事实上,我们可以通过Array.prototype中的splice 函数来删除数组中的元素,如下所示:var arr = [1, 2, 3, 4, 5];<BR> arr.splice(1, 1);<BR> arr; // [1, 3, 4, 5]<BR>
Copier après la connexion
- 函数也是对象
在JavaScript中函数也是对象,因为我们可以为函数添加属性。
比如:我们为函数add 添加了count 属性,用来记录此函数被调用的次数。function add() {<BR> return add.count++;<BR> }<BR> add.count = 0;<BR> add(); // 0<BR> add(); // 1<BR> add(); // 2<BR>
Copier après la connexion
当然这可以通过更优雅的方式来实现:arguments.callee 指向当前正在运行的函数。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>
Copier après la connexion
- 数组中的最大值
如何在全是数字的数组中找到最大值,我们可以简单的通过循环来完成:有没有其他方法?我们都知道JavaScript中有一个Math 对象进行数字的处理: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>
Copier après la connexion然后,我们可以这样来找到数组中最大值:Math.max(2, 3, 45, 12, 8); // 45<BR>
Copier après la connexionvar arr = [2, 3, 45, 12, 8];<BR> Math.max.apply(null, arr); // 45<BR>
Copier après la connexion
- 为IE添加console.log 函数
在Firefox下并有Firebug的支持下,我们经常使用console.log 来在控制台记录一些信息。
但是这种做法在IE下会阻止JavaScript的执行(在Firefox下没有启用Firebug情况下也是一样),因为此时根本没有console 对象存在。
我们可以通过如下小技巧来防止这样情况的发生:if (typeof(console) === 'undefined') {<BR> window.console = {<BR> log: function(msg) {<BR> alert(msg);<BR> }<BR> };<BR> }<BR> console.log('debug info.');<BR>
Copier après la connexion
- undefined 是JavaScript中保留关键字么?
看起来像是的,但实际上undefined并不是JavaScript中的关键字:这段代码可能会让你感到很奇怪,不过它的确能够正常运行,undefined 只是JavaScript中一个预定义的变量而已。var undefined = 'Hello'; <BR> undefined; // 'Hello'<BR>
Copier après la connexion
注:在JavaScript程序中,千万不要这样做,这个技巧只是告诉你有这么一回事而已。
- 判断一个变量是否为undefined
两种情况下,一个变量为undefined:
1. 声明了变量,但是没有赋值2. 从来没有声明过此变量var name; <BR> name === undefined; // true<BR>
Copier après la connexion在第二种情况下,会有一个错误被抛出,那么如果判断一个变量是否为undefined而不产生错误呢?name2 === undefined; // error – name2 is not defined<BR>
Copier après la connexion
下面提供了一种通用的方法:typeof(name2) === ‘undefined'; // true<BR>
Copier après la connexion
- 预加载图片
预加载图片就是加载页面上不存在的图片,以便以后使用JavaScript把它们快速显示出来。
比如你想在鼠标移动到某个图片上时显示另一张图片:var img = new Image(); <BR> img.src = "clock2.gif";<BR>
Copier après la connexion<img src="/static/imghw/default1.png" data-src="clock.gif" class="lazy" alt="" <BR> onmouseover="this.src='clock2.gif';" <BR> onmouseout="this.src=clock.gif';" /><BR>
Copier après la connexion
那么,如何加载一组图片呢?考虑如下代码:实际上,这段代码只能预加载最后的一张图片,因为其他的图片根本没有时间来预加载在循环到来的时候。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>
Copier après la connexion
因此正确的写法应该是: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>
Copier après la connexion
- 闭包(closure)
闭包指的是函数内的局部变量,当函数返回时此变量依然可用。
当你在函数内部定义另外一个函数时,你就创建了一个闭包,一个著名的例子:add(2) 是一个函数,它可能获取外部函数的局部变量i 。function add(i) { <BR> return function() { <BR> return ++i; <BR> }; <BR> } <BR> add(2).toString(); // "function () { return ++i; }" <BR> add(2)(); // 3<BR>
Copier après la connexion
参考文章
- 私有变量
我们经常使用命名规范来标示一个变量是否为私有变量(最常用来标示):下划线前缀用来作为私有变量的约定,但是其他开发人员仍然可以调用此私有变量:var person = { <BR> _name: '', <BR> getName: function() { <BR> return this._name || 'not defined'; <BR> } <BR> }; <BR> person.getName(); // "not defined"<BR>
Copier après la connexion那么,如何在JavaScript中创建一个真正的私有变量呢?person._name; // ""<BR>
Copier après la connexion
主要技巧是使用匿名函数(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>
Copier après la connexion
- JavaScript没有块级上下文(Scope)
JavaScript中块级代码没有上下文,实际上只有函数有自己的上下文。如果想创建一个上下文,可以使用自执行的匿名函数:for(var i = 0; i < 2; i ++) { <br><br> } <BR> i; // 2<BR>
Copier après la connexion(function (){ <BR> for(var i = 0; i < 2; i ++) { <br><br> }<BR> })(); <BR> typeof(i) === 'undefined'; // true<BR>
Copier après la connexion
- 怪异的NaN
NaN用来表示一个值不是数字。
NaN在JavaScript中行为很怪异,是因为那NaN和任何值都不相等(包括它自己)。因为下面的代码可能会让一些人抓狂:NaN === NaN; // false<BR>
Copier après la connexion那么如何来检查一个值是否NaN?parseInt('hello', 10); // NaN <BR> parseInt('hello', 10) == NaN; // false <BR> parseInt('hello', 10) === NaN; // false<BR>
Copier après la connexion
可以使用window.isNaN来判断:isNaN(parseInt('hello', 10)); // true<BR>
Copier après la connexion
- 真值和假值
JavaScript中所有值都能隐式地转化为Boolean类型。
在条件判断中,下面这些值会自动转化为false:
null, undefined, NaN, 0, ‘', false
因此,不需要做如下复杂的判断:而只需要这样做就行了:if(obj === undefined || obj === null) { <BR> }<BR>
Copier après la connexionif(!obj) { <br><br> }<BR>
Copier après la connexion
- 修改arguments
比如,添加一个值到arguments中:这样会出错,因为arguments 不是一个真正的数组,没有push方法。function add() { <BR> arguments.push('new value'); <BR> } <BR> add(); // error - arguments.push is not a function<BR>
Copier après la connexion
解决办法:function add() { <BR> Array.prototype.push.call(arguments, 'new value'); <BR> return arguments; <BR> } <BR> add()[0]; // "new value"<BR>
Copier après la connexion
- Boolean 和 new Boolean
我们可以把Boolean看做是一个函数,用来产生Boolean类型的值(Literal):所以,Boolean(0) 和!!0 是等价的。Boolean(false) === false; // true <BR> Boolean('') === false; // true<BR>
Copier après la connexion
我们也可以把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>
Copier après la connexion
- 快速字符串连接
我们经常使用+ 将较短的字符串连接为一个长字符串,这在大部分的情况下是没问题的。
但是如果有大量的字符串需要连接,这种做法将会遇到性能问题,尤其是在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>
Copier après la connexionvar 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>
Copier après la connexion
可以看到Firefox似乎对+ 操作符进行了优化,而IE则表现的傻乎乎的。
- 一元操作符 +
在JavaScript中,我们可以在字符串之前使用一元操作符“+”。这将会把字符串转化为数字,如果转化失败则返回NaN。
2 + '1'; // "21"<BR> 2 + ( +'1'); // 3<BR>
Copier après la connexion如果把 + 用在非字符串的前面,将按照如下顺序进行尝试转化:
- 调用valueOf()
- 调用toString()
- 转化为数字
参考文章+new Date; // 1242616452016<BR> +new Date === new Date().getTime(); // true<BR> +new Date() === Number(new Date) // true<BR>
Copier après la connexion
- encodeURI和encodeURIComponent
window.encodeURI函数用来编码一个URL,但是不会对以下字符进行编码:“:”, “/”, “;”, “?”.
window.encodeURIComponent则会对上述字符进行编码。
我们通过一个例子来说明:因此,在对URL进行编码时我们经常会选择 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>
Copier après la connexion
- table.innerHTML在IE下是只读属性
我们经常通过节点的innerHTML 属性来填充节点,比如:<div id="container1"> </div><BR>
Copier après la connexion但是在IE下设置table.innerHTML 将会导致错误:document.getElementById('container1').innerHTML = "Hello World!";
Copier après la connexion<table id="table1"> </table><BR>
Copier après la connexion实际上,table, thead, tr, select等元素的innerHTML属性在IE下都是只读的。// works well in Firefox, but fail to work in IE<BR> document.getElementById('table1').innerHTML = "<tr><td>Hello</td><td>World!</td></tr>";<BR>
Copier après la connexion
那么如果动态的创建一个table呢,下面提供了一种可行的方法:<div id="table1"> </div><BR>
Copier après la connexiondocument.getElementById('table1').innerHTML = "<table><tr><td>Hello</td><td>World!</td></tr></table>";<BR>
Copier après la connexion
- 0.1+0.2 != 0.3
JavaScript将小数作为浮点数对待,所以可能会产生一些四舍五入的错误,比如:你可以通过toFixed方法指定四舍五入的小数位数:0.1 + 0.2; // 0.30000000000000004
Copier après la connexion(0.1 + 0.2).toFixed(); // "0"<BR> (0.1 + 0.2).toFixed(1); // "0.3"
Copier après la connexion
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);

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

AI Hentai Generator
Générez AI Hentai gratuitement.

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment utiliser WebSocket et JavaScript pour mettre en œuvre un système de reconnaissance vocale en ligne Introduction : Avec le développement continu de la technologie, la technologie de reconnaissance vocale est devenue une partie importante du domaine de l'intelligence artificielle. Le système de reconnaissance vocale en ligne basé sur WebSocket et JavaScript présente les caractéristiques d'une faible latence, d'un temps réel et d'une multiplateforme, et est devenu une solution largement utilisée. Cet article explique comment utiliser WebSocket et JavaScript pour implémenter un système de reconnaissance vocale en ligne.

WebSocket et JavaScript : technologies clés pour réaliser des systèmes de surveillance en temps réel Introduction : Avec le développement rapide de la technologie Internet, les systèmes de surveillance en temps réel ont été largement utilisés dans divers domaines. L'une des technologies clés pour réaliser une surveillance en temps réel est la combinaison de WebSocket et de JavaScript. Cet article présentera l'application de WebSocket et JavaScript dans les systèmes de surveillance en temps réel, donnera des exemples de code et expliquera leurs principes de mise en œuvre en détail. 1. Technologie WebSocket

Introduction à l'utilisation de JavaScript et de WebSocket pour mettre en œuvre un système de commande en ligne en temps réel : avec la popularité d'Internet et les progrès de la technologie, de plus en plus de restaurants ont commencé à proposer des services de commande en ligne. Afin de mettre en œuvre un système de commande en ligne en temps réel, nous pouvons utiliser les technologies JavaScript et WebSocket. WebSocket est un protocole de communication full-duplex basé sur le protocole TCP, qui peut réaliser une communication bidirectionnelle en temps réel entre le client et le serveur. Dans le système de commande en ligne en temps réel, lorsque l'utilisateur sélectionne des plats et passe une commande

Comment utiliser WebSocket et JavaScript pour mettre en œuvre un système de réservation en ligne. À l'ère numérique d'aujourd'hui, de plus en plus d'entreprises et de services doivent fournir des fonctions de réservation en ligne. Il est crucial de mettre en place un système de réservation en ligne efficace et en temps réel. Cet article explique comment utiliser WebSocket et JavaScript pour implémenter un système de réservation en ligne et fournit des exemples de code spécifiques. 1. Qu'est-ce que WebSocket ? WebSocket est une méthode full-duplex sur une seule connexion TCP.

Taper des symboles sur un clavier d’ordinateur est quelque chose que nous rencontrons souvent lors de l’utilisation quotidienne d’un ordinateur. La plupart du temps, les symboles que nous utilisons sont des symboles demi-chasse, qui sont des symboles anglais, tels que ",", "." et "!". Mais parfois, nous devons également utiliser des symboles pleine chasse, tels que les symboles chinois ",", ".", "!". Les symboles pleine chasse seront plus beaux lors de la composition, ce qui donnera au texte un aspect plus chinois. Aujourd'hui, nous allons apprendre à saisir des symboles pleine chasse sur le clavier pour donner à vos documents un aspect plus professionnel et standardisé. Tout d'abord, comprenons un

JavaScript et WebSocket : Construire un système efficace de prévisions météorologiques en temps réel Introduction : Aujourd'hui, la précision des prévisions météorologiques revêt une grande importance pour la vie quotidienne et la prise de décision. À mesure que la technologie évolue, nous pouvons fournir des prévisions météorologiques plus précises et plus fiables en obtenant des données météorologiques en temps réel. Dans cet article, nous apprendrons comment utiliser la technologie JavaScript et WebSocket pour créer un système efficace de prévisions météorologiques en temps réel. Cet article démontrera le processus de mise en œuvre à travers des exemples de code spécifiques. Nous

Tutoriel JavaScript : Comment obtenir le code d'état HTTP, des exemples de code spécifiques sont requis Préface : Dans le développement Web, l'interaction des données avec le serveur est souvent impliquée. Lors de la communication avec le serveur, nous devons souvent obtenir le code d'état HTTP renvoyé pour déterminer si l'opération a réussi et effectuer le traitement correspondant en fonction de différents codes d'état. Cet article vous apprendra comment utiliser JavaScript pour obtenir des codes d'état HTTP et fournira quelques exemples de codes pratiques. Utilisation de XMLHttpRequest

Utilisation : En JavaScript, la méthode insertBefore() est utilisée pour insérer un nouveau nœud dans l'arborescence DOM. Cette méthode nécessite deux paramètres : le nouveau nœud à insérer et le nœud de référence (c'est-à-dire le nœud où le nouveau nœud sera inséré).
