[·Òë]High Performance JavaScript(013)
Conditionals Ìõ¼þ±í´ïʽ
Similar in nature to loops, conditionals determine how execution flows through JavaScript. The traditional argument of whether to use if-else statements or a switch statement applies to JavaScript just as it does to other languages. Since different browsers have implemented different flow control optimizations, it is not always clear which technique to use.
ÓëÑ»·ÏàËÆ£¬Ìõ¼þ±í´ïʽ¾ö¶¨JavaScriptÔËÐÐÁ÷µÄ×ßÏò¡£ÆäËûÓïÑÔʹÓÃif-else»òÕßswitch±í´ïʽµÄ´«Í³¹ÛµãÒ²ÊÊÓÃÓÚJavaScript¡£ÓÉÓÚ²»Í¬µÄä¯ÀÀÆ÷Õë¶ÔÁ÷³Ì¿ØÖƽøÐÐÁ˲»Í¬µÄÓÅ»¯£¬Ê¹ÓÃÄÄÖÖ¼¼Êõ²¢²»×ÜÊǺÜÇå³þ¡£
if-else Versus switch if-elseÓëswitch±È½Ï
The prevailing theory on using if-else versus switch is based on the number of conditions being tested: the larger the number of conditions, the more inclined you are to use a switch instead of if-else. This typically comes down to which code is easier to read. The argument is that if-else is easier to read when there are fewer conditions and switch is easier to read when the number of conditions is large. Consider the following:
ʹÓÃif-else»òÕßswitchµÄÁ÷ÐÐÀíÂÛÊÇ»ùÓÚ²âÊÔÌõ¼þµÄÊýÁ¿£ºÌõ¼þÊýÁ¿½Ï´ó£¬ÇãÏòÓÚʹÓÃswitch¶ø²»ÊÇif-else¡£Õâͨ³£¹é½áµ½´úÂëµÄÒ×¶ÁÐÔ¡£ÕâÖÖ¹ÛµãÈÏΪ£¬Èç¹ûÌõ¼þ½ÏÉÙʱ£¬if-elseÈÝÒ×ÔĶÁ£¬¶øÌõ¼þ½Ï¶àʱswitch¸üÈÝÒ×ÔĶÁ¡£¿¼ÂÇÏÂÃæ¼¸µã£º
if (found){
//do something
} else {
//do something else
}
switch(found){
case true:
//do something
break;
default:
//do something else
}
Though both pieces of code perform the same task, many would argue that the if-else statement is much easier to read than the switch. Increasing the number of conditions, however, usually reverses that opinion:
ËäÈ»Á½¸ö´úÂë¿éʵÏÖͬÑùÈÎÎñ£¬ºÜ¶àÈË»áÈÏΪif-else±í´ïʽ±Èwitch±í´ïʽ¸üÈÝÒ×ÔĶÁ¡£Èç¹ûÔö¼ÓÌõ¼þÌåµÄÊýÁ¿£¬Í¨³£»áŤתÕâÖֹ۵㣺
if (color == "red"){
//do
Ïà¹ØÎĵµ£º
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>five-in-a-raw</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
  ......
JavascriptÊý¾ÝÀàÐÍ
ÓÉÓÚjavascriptÊÇÈõÀàÐÍÓïÑÔ£¬¼´¶¨Òå±äÁ¿Ê±²»±ØÉùÃ÷ÆäÀàÐÍ
¡£µ«Õâ²¢²»Òâζ×űäÁ¿Ã»ÓÐÀàÐÍ¡£ÒòΪ¸³ÖµÊ±»á×Ô¶¯Æ¥ÅäÊý¾ÝÀàÐÍ£¡
ĿǰÓõ½µÄ»ù±¾Êý¾ÝÀàÐÍ
number
boolean
string
var i
i="test";//Õâʱi¾Í³ÉÁËstringÀàÐÍ
var i
i=4;//Õâʱi¾Í³ÉÁËnumberÀàÐÍ
³£ÓöÔÏóÀàÐÍ<object> ......
typeof ÊÇJavaScriptµÄÔËËã·û
——·µ»ØÒ»¸öÓÃÀ´±íʾ±í´ïʽµÄÊý¾ÝÀàÐ͵Ä×Ö·û´®
typeof[(] expression [)] //typeofÓï·¨ÖеÄÔ²À¨ºÅÊÇ¿ÉÑ¡Ïî
typeof ÔËËã·û@import url(../html-vss/msdnie4a.css);
typeof
ÔËËã·û°ÑÀàÐÍÐÅÏ¢µ±×÷×Ö·û´®·µ»Ø¡£typeof
·µ»ØÖµÓÐÁ ......
µÚËÄÕ Algorithms and Flow Control Ëã·¨ºÍÁ÷³Ì¿ØÖÆ
The overall structure of your code is one of the main determinants as to how fast it will execute. Having a very small amount of code doesn't necessarily mean that it will run quickly, and having a large amount of code ......