a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 195|回复: 2

[专业语言] JAVA专业语言:JavaScript中不可不知的十个小技巧

[复制链接]
发表于 2012-8-4 12:44:44 | 显示全部楼层 |阅读模式
尽管我使用Javascript来做开发有良多年了,但它常有一些让我很惊奇的小特征。对于我来说,Javascript是需要持续不竭的进修的。在这篇文章中,我将列出10个Javascript使用小技巧,首要面向Javascript新手和中级开发者。但愿每个读者都能至少年夜中学到一个有用的技巧。 1.变量转换) v9 J6 q, e5 a* R" [' p
看起来很简单,但据我所看到的,使用机关函数,像Array()或者Number()来进行变量转换是常用的做法。始终使用原始数据类型(有时也称为字面量)来转换变量,这种没有任何额外的影响的做法反而效率更高。9 |- O9 Z6 ]) k# G$ ^) ?
& H: t/ E( ]! d4 z/ J
var myVar   = "3.14159",             str     = ""+ myVar,//  to string             int     = ~~myVar,  //  to integer             float   = 1*myVar,  //  to float             bool    = !!myVar,  /*  to boolean - any string with length                               and any number except 0 are true */           array   = [myVar];  //  to array   转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必需使用机关函数,而且建树正则表达式的时辰要使用/pattern/flags的形式。8 l! h2 f  o; r6 h" V6 D
2.十进制转换为十六进制或者八进制,或者反过来
  b( h0 M; Q: v你是不是写个零丁的函数来转换十六进制(或者八进制)呢?马上停下吧!有更轻易的现成的函数可以用:* P& m5 E6 c1 y! f! y" T9 R% z

* S+ D$ R& k1 z7 K3 b2 h(int).toString(16); // converts int to hex, eg 12 => "C"       (int).toString(8);  // converts int to octal, eg. 12 => "14"       parseInt(string,16) // converts hex to int, eg. "FF" => 255       parseInt(string,8) // converts octal to int, eg. "20" => 16   3.玩转数字
. F. m. n/ Q  w5 i) u除了上一节介绍的之外,这里有更多的措置数字的技巧:- E- B) q* e9 f3 g$ S

: r6 [( V# Z- H+ z$ @4 C0xFF; // Hex declaration, returns 255       020; // Octal declaration, returns 16       1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000       (1000).toExponential(); // Opposite with previous, returns 1e3       (3.1415).toFixed(3); // Rounding the number, returns "3.142"   4.Javascript版本检测0 `! `, ^1 H: F# a5 l! {8 o+ B
你知道你的浏览器撑持哪一个版本的Javascript吗?如不美观不知道的话,去维诬蔑科查一下Javascript版本表吧。出于某种原因,Javascript 1.7版本的某些特征是没有获得普遍的撑持。不外年夜部门浏览器都撑持了1.8版和1.8.1版的特征。(注:所有的IE浏览器(IE8或者更老的版本)只撑持1.5版的Javascript)这里有一个剧本,既能经由过程检测特征来检测JavaScript版本,它还能搜检特定的Javascript版本所撑持的特征。
/ T1 T) c- X. _- z9 V7 F8 P/ D6 ~4 [9 C1 S- n# B
var JS_ver  = [];          (Number.prototype.toFixed)?JS_ver.push("1.5"):false;       ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;       ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;       ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;       ("".trimLeft)?JS_ver.push("1.8.1"):false;        JS_ver.supports = function()       {            if (arguments[0])                return (!!~this.join().indexOf(arguments[0] +",") +",");            else              return (this[this.length-1]);        }         alert("Latest Javascript version supported: "+ JS_ver.supports());       alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));   5.使用window.name进熟行单会话措置
  n$ W9 i/ y  {" s4 f+ O+ n, {1 n$ h3 L9 Z, |- l
这个是我真的喜欢的工具。您可觉得指定一个字符串作为window.name属性的值,直到您封锁该标签或窗口。虽然我没有供给任何剧本,但我强烈建议您如充实操作这个体例。举例来说,在培植一个网站或应用轨范的时辰,在调试和测试模式之间切换长短常有用的。
回复

使用道具 举报

 楼主| 发表于 2012-8-4 12:44:45 | 显示全部楼层

JAVA专业语言:JavaScript中不可不知的十个小技巧

</p>6.判定属性是否存在) b$ b0 l+ i' M$ F) {
这个问题包含两个方面,既有搜检属性时辰存在,还要获取属性的类型。但我们老是忽略了这些小工作:
1 k$ t( W- i, t7 h- y0 _4 ~) W7 b3 X4 z4 m/ F0 Y
// BAD: This will cause an error in code when foo is undefined        if (foo) {            doSomething();        }               // GOOD: This doesn't cause any errors. However, even when        // foo is set to NULL or false, the condition validates as true        if (typeof foo != "undefined") {            doSomething();        }                // BETTER: This doesn't cause any errors and in addition        // values NULL or false won't validate as true         if (window.foo) {            doSomething();       }  可是,有的情形下,我们有更深的结构和需要更合适的搜检的时辰,可以这样:
8 v$ ]3 f# d0 G6 l8 h9 B+ S  G0 R& B0 f
// UGLY: we have to proof existence of every       // object before we can be sure property actually exists         if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {            doSomething();        }   7.给函数传递参数! S/ [& ~( I# ~$ x6 ]
当函数既有必选又有可选参数的时辰,我们可能是这样做的:
9 G1 G& x1 G8 V$ q0 t% l# o4 ~) ?* e
function doSomething(arg0, arg1, arg2, arg3, arg4) {        ...        }              doSomething('', 'foo', 5, [], false);  而传递一个对象老是比传递一堆的参数更便利:9 }' s& {5 q: ^  J2 o
. x2 |" w9 _2 Y3 j
function doSomething() {             // Leaves the function if nothing is passed            if (!arguments[0]) {               return false;            }                 var oArgs   = arguments[0]                arg0    = oArgs.arg0 || "",                arg1    = oArgs.arg1 || "",                arg2    = oArgs.arg2 || 0,                arg3    = oArgs.arg3 || [],                arg4    = oArgs.arg4 || false;       }             doSomething({            arg1    : "foo",            arg2    : 5,            arg4    : false      });   $ B  n# M5 t! P1 T* e5 c
这只是一个把对象作为参数传递的一个很简单的例子,例如,我们还可以声明一个对象,变量名作为Key,默认值作为Value。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2012-8-4 12:44:46 | 显示全部楼层

JAVA专业语言:JavaScript中不可不知的十个小技巧

</p>8.使用document.createDocumentFragment()- h2 {$ G9 i5 Z! |3 a, A- Z( C1 h
您可能需要动态地追加多个元素到文档中。然而,直接将它们插入到文档中会导致这个文档每次都需要年夜头结构一个,相反的,你应该使用文档碎片,建成后只追加一次:
  _6 v. u2 J( j! B. k! e. M, f) y! T7 g- b& \- S, i2 t
function doSomething(arg0, arg1, arg2, arg3, arg4) {        ...        }              doSomething('', 'foo', 5, [], false);  而传递一个对象老是比传递一堆的参数便利:
6 K  x5 b3 D) F5 K
2 O: B1 I' w( k* ?/ s  k: hfunction createList() {            var aLI = ["first item", "second item", "third item","fourth item", "fith item"];                   // Creates the fragment            var oFrag   = document.createDocumentFragment();                    while (aLI.length) {                var oLI = document.createElement("li");                        // Removes the first item from array and appends it                // as a text node to LI element                oLI.appendChild(document.createTextNode(aLI.shift()));                oFrag.appendChild(oLI);            }                    document.getElementById('myUL').appendChild(oFrag);         }  9.为replace()体例传递一个函数
$ t& ~9 d2 n- V5 P有的时辰你想替代字符串的某个部门为其它的值,最好的体例就是给String.replace()传递一个自力的函数。* R8 ~" q, @6 `# R0 G! @
下面是实此刻线扑克游戏中年夜量输出的一个简单例子:
, ]9 @* h+ j2 U; |6 q0 l4 g0 u9 ~+ u
var sFlop   = "Flop: [Ah] [Ks] [7c]";       var aValues = {"A":"Ace","K":"King",7:"Seven"};       var aSuits  = {"h":"Hearts","s":"Spades","d":"Diamonds","c":"Clubs"};     sFlop   = sFlop.replace(/[w+]/gi, function(match) {            match   = match.replace(match[2], aSuits[match[2]]);            match   = match.replace(match[1], aValues[match[1]] +" of ");                  return match;        });              // string sFlop now contains:        // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"  10.轮回中标签的使用( Y4 t7 d" M4 t1 a8 V
有的时辰,轮回中又嵌套了轮回,你可能想在轮回中退出,则可以用标签:( \7 f8 e1 _2 o/ @3 j
# p" h7 n: [6 ^# v( h! @
outerloop:         for (var iI=0;iI
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-4-29 17:30 , Processed in 0.271477 second(s), 25 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表