你可能不知道的10个JavaScript小技巧 作者:梦想

超级大笨狼 2010-09-21 05:47:29
加精
你可能不知道的10个JavaScript小技巧

作者:梦想
出处:http://www.cnblogs.com/lhb25
欢迎转载,请在文章页面明显位置给出原文链接。

尽管我使用Javascript来做开发有很多年了,但它常有一些让我很惊讶的小特性。对于我来说,Javascript是需要持续不断的学习的。在这篇文章中,我将列出10个Javascript使用小技巧,主要面向Javascript新手和中级开发者。希望每个读者都能至少从中学到一个有用的技巧。

1.变量转换
看起来很简单,但据我所看到的,使用构造函数,像Array()或者Number()来进行变量转换是常用的做法。始终使用原始数据类型(有时也称为字面量)来转换变量,这种没有任何额外的影响的做法反而效率更高。

view sourceprint?
1 var myVar = "3.14159",

2 str = ""+ myVar,// to string

3 int = ~~myVar, // to integer

4 float = 1*myVar, // to float

5 bool = !!myVar, /* to boolean - any string with length

6 and any number except 0 are true */

7 array = [myVar]; // to array
转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,而且创建正则表达式的时候要使用/pattern/flags的形式。


2.十进制转换为十六进制或者八进制,或者反过来
你是不是写个单独的函数来转换十六进制(或者八进制)呢?马上停下吧!有更容易的现成的函数可以用:

view sourceprint?
1 (int).toString(16); // converts int to hex, eg 12 => "C"

2 (int).toString(8); // converts int to octal, eg. 12 => "14"

3 parseInt(string,16) // converts hex to int, eg. "FF" => 255

4 parseInt(string,8) // converts octal to int, eg. "20" => 16
3.玩转数字
除了上一节介绍的之外,这里有更多的处理数字的技巧

view sourceprint?
1 0xFF; // Hex declaration, returns 255

2 020; // Octal declaration, returns 16

3 1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000

4 (1000).toExponential(); // Opposite with previous, returns 1e3

5 (3.1415).toFixed(3); // Rounding the number, returns "3.142"
4.Javascript版本检测
你知道你的浏览器支持哪一个版本的Javascript吗?如果不知道的话,去维基百科查一下Javascript版本表吧。出于某种原因,Javascript 1.7版本的某些特性是没有得到广泛的支持。不过大部分浏览器都支持了1.8版和1.8.1版的特性。(注:所有的IE浏览器(IE8或者更老的版本)只支持1.5版的Javascript)这里有一个脚本,既能通过检测特征来检测JavaScript版本,它还能检查特定的Javascript版本所支持的特性。

view sourceprint?
01 var JS_ver = [];

02 (Number.prototype.toFixed)?JS_ver.push("1.5"):false;

03 ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;

04 ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;

05 ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;

06 ("".trimLeft)?JS_ver.push("1.8.1"):false;

07 JS_ver.supports = function()

08 {

09   if (arguments[0])

10     return (!!~this.join().indexOf(arguments[0] +",") +",");

11   else

12     return (this[this.length-1]);

13 }

14 alert("Latest Javascript version supported: "+ JS_ver.supports());

15 alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));
5.使用window.name进行简单会话处理
这个是我真的喜欢的东西。您可以为指定一个字符串作为window.name属性的值,直到您关闭该标签或窗口。虽然我没有提供任何脚本,但我强烈建议您如充分利用这个方法。举例来说,在建设一个网站或应用程序的时候,在调试和测试模式之间切换是非常有用的。

6.判断属性是否存在
这个问题包含两个方面,既有检查属性时候存在,还要获取属性的类型。但我们总是忽略了这些小事情:

view sourceprint?
01 // BAD: This will cause an error in code when foo is undefined

02 if (foo) {

03   doSomething();

04 }

05 // GOOD: This doesn't cause any errors. However, even when

06 // foo is set to NULL or false, the condition validates as true

07 if (typeof foo != "undefined") {

08   doSomething();

09 }

10 // BETTER: This doesn't cause any errors and in addition

11 // values NULL or false won't validate as true

12 if (window.foo) {

13   doSomething();

14 }
但是,有的情况下,我们有更深的结构和需要更合适的检查的时候,可以这样:

view sourceprint?
1 // UGLY: we have to proof existence of every

2 // object before we can be sure property actually exists

3 if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {

4   doSomething();

5 }
7.给函数传递参数
当函数既有必选又有可选参数的时候,我们可能是这样做的:

view sourceprint?
1 function doSomething(arg0, arg1, arg2, arg3, arg4) {

2   ...

3 }

4 doSomething('', 'foo', 5, [], false);
而传递一个对象总是比传递一堆的参数更方便:

view sourceprint?
01 function doSomething() {

02   // Leaves the function if nothing is passed

03   if (!arguments[0]) {

04   return false;

05   }

06   var oArgs = arguments[0]

07   arg0 = oArgs.arg0 || "",

08   arg1 = oArgs.arg1 || "",

09   arg2 = oArgs.arg2 || 0,

10   arg3 = oArgs.arg3 || [],

11   arg4 = oArgs.arg4 || false;

12 }

13 doSomething({

14   arg1 : "foo",

15   arg2 : 5,

16   arg4 : false

17 });
这只是一个把对象作为参数传递的一个很简单的例子,例如,我们还可以声明一个对象,变量名作为Key,默认值作为Value。

8.使用document.createDocumentFragment()
您可能需要动态地追加多个元素到文档中。然而,直接将它们插入到文档中会导致这个文档每次都需要重新布局一个,相反的,你应该使用文档碎片,建成后只追加一次:

view sourceprint?
01 function createList() {

02   var aLI = ["first item", "second item", "third item",

03   "fourth item", "fith item"];

04   // Creates the fragment

05   var oFrag = document.createDocumentFragment();

06   while (aLI.length) {

07     var oLI = document.createElement("li");

08     // Removes the first item from array and appends it

09     // as a text node to LI element

10     oLI.appendChild(document.createTextNode(aLI.shift()));

11     oFrag.appendChild(oLI);

12   }

13   document.getElementById('myUL').appendChild(oFrag);

14 }
9.为replace()方法传递一个函数
有的时候你想替换字符串的某个部分为其它的值,最好的方法就是给String.replace()传递一个独立的函数。下面是一个简单例子:

view sourceprint?
01 var sFlop = "Flop: [Ah] [Ks] [7c]";

02 var aValues = {"A":"Ace","K":"King",7:"Seven"};

03 var aSuits = {"h":"Hearts","s":"Spades",

04 "d":"Diamonds","c":"Clubs"};

05 sFlop = sFlop.replace(/\[\w+\]/gi, function(match) {

06   match = match.replace(match[2], aSuits[match[2]]);

07   match = match.replace(match[1], aValues[match[1]] +" of ");

08   return match;

09 });

10 // string sFlop now contains:

11 // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
10.循环中标签的使用
有的时候,循环中又嵌套了循环,你可能想在循环中退出,则可以用标签:

view sourceprint?
01 outerloop:

02 for (var iI=0;iI<5;iI++) {

03   if (somethingIsTrue()) {

04   // Breaks the outer loop iteration

05   break outerloop;

06   }

07   innerloop:

08   for (var iA=0;iA<5;iA++) {

09     if (somethingElseIsTrue()) {

10     // Breaks the inner loop iteration

11     break innerloop;

12   }

13   }

14 }
...全文
19258 521 打赏 收藏 转发到动态 举报
写回复
用AI写文章
521 条回复
切换为时间正序
请发表友善的回复…
发表回复
c592933519 2013-04-22
  • 打赏
  • 举报
回复
果断收藏!!!!
网络科技 2013-04-02
  • 打赏
  • 举报
回复
企鹅片尾曲 2013-04-01
  • 打赏
  • 举报
回复
求详细列子,新手表示看不懂。。。。
「已注销」 2012-11-16
  • 打赏
  • 举报
回复
随机3位字符串 Math.random().toFixed(3).slice(2) 随机4位字符串 Math.random().toFixed(4).slice(2) 随机5位字符串 Math.random().toFixed(5).slice(2)
z_lover 2012-08-02
  • 打赏
  • 举报
回复
学习了
jay_借口 2011-08-11
  • 打赏
  • 举报
回复
标记 感谢楼主分享
晴空87 2011-08-05
  • 打赏
  • 举报
回复
学习学习
q461088983 2011-04-07
  • 打赏
  • 举报
回复
好东西好东西
yyl1992830 2011-04-07
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20110407/15/77fca383-d4b3-44b1-951d-01c1549216d8.html?58013 接口问题
yimengqi55 2011-04-07
  • 打赏
  • 举报
回复
[Quote=引用 48 楼 falizixun2 的回复:]

小测了一下,发现了些小问题:
4 float = 1*myVar, // to float //这个结果都是number,而不是float;
7 array = [myVar]; // to array //这个的结果是object,而不是array;
目前就测试了前面几个简单的,只发现这几个不符合描述!
[/Quote]
array用alert()弹出来的话,是显示为OBJ,如果alert(array[0])这样就会出现值了
  • 打赏
  • 举报
回复
很好。。我喜欢 。。我开始javascript的了
snc2010 2011-03-24
  • 打赏
  • 举报
回复
果然高手!
Exodia 2011-03-01
  • 打赏
  • 举报
回复
[Quote=引用 48 楼 falizixun2 的回复:]

小测了一下,发现了些小问题:
4 float = 1*myVar, // to float //这个结果都是number,而不是float;
7 array = [myVar]; // to array //这个的结果是object,而不是array;
目前就测试了前面几个简单的,只发现这几个不符合描述!
[/Quote]

别和我说你说typeof测试的。。。。。。。。
zyb51 2011-02-28
  • 打赏
  • 举报
回复
好东西.留名方便以后看
小妹917 2011-02-28
  • 打赏
  • 举报
回复
还不错的
clear 2011-02-27
  • 打赏
  • 举报
回复
LKK 2011-02-27
  • 打赏
  • 举报
回复
收藏先。。
fricke 2011-02-19
  • 打赏
  • 举报
回复
有些东西闻所未闻,太感谢了
xiaoyu666666 2011-02-16
  • 打赏
  • 举报
回复
谢谢楼主分享!
hanmiit 2011-02-16
  • 打赏
  • 举报
回复
真是好东西~~谢谢了~~
加载更多回复(449)

87,904

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧