[·Òë]High Performance JavaScript(025)
µÚ°ËÕ Programming Practices ±à³Ìʵ¼ù
Every programming language has pain points and inefficient patterns that develop over time. The appearance of these traits occurs as people migrate to the language and start pushing its boundaries. Since 2005, when the term "Ajax" emerged, web developers have pushed JavaScript and the browser further than it was ever pushed before. As a result, some very specific patterns emerged, both as best practices and as suboptimal ones. These patterns arise because of the very nature of JavaScript on the Web.
ÿÖÖ±à³ÌÓïÑÔ¶¼ÓÐÍ´µã£¬¶øÇÒµÍÐ§Ä£Ê½Ëæ×Åʱ¼äµÄÍÆÒÆ²»¶Ï·¢Õ¹¡£ÆäÔÒòÔÚÓÚ£¬Ô½À´Ô½¶àµÄÈËÃÇ¿ªÊ¼Ê¹ÓÃÕâÖÖÓïÑÔ£¬²»¶ÏÀ©ÖÖËüµÄ±ß½ç¡£×Ô2005ÄêÒÔÀ´£¬µ±ÊõÓï“Ajax”³öÏÖʱ£¬ÍøÒ³¿ª·¢Õß¶ÔJavaScriptºÍä¯ÀÀÆ÷µÄÍÆ¶¯×÷ÓÃÔ¶³¬¹ýÒÔÍù¡£Æä½á¹ûÊdzöÏÖÁËһЩ·Ç³£¾ßÌåµÄģʽ£¬¼´ÓÐÓÅÐãµÄ×ö·¨Ò²ÓÐÔã¸âµÄ×ö·¨¡£ÕâЩģʽµÄ³öÏÖ£¬ÊÇÒòÎªÍøÂçÉÏJavaScriptµÄÐÔÖʾö¶¨µÄ¡£
Avoid Double Evaluation ±ÜÃâ¶þ´ÎÆÀ¹À
JavaScript, like many scripting languages, allows you to take a string containing code and execute it from within running code. There are four standard ways to accomplish this: eval(), the Function() constructor, setTimeout(), and setInterval(). Each of these functions allows you to pass in a string of JavaScript code and have it executed. Some examples:
JavaScriptÓëÐí¶à½Å±¾ÓïÑÔÒ»Ñù£¬ÔÊÐíÄãÔÚ³ÌÐòÖлñȡһ¸ö°üº¬´úÂëµÄ×Ö·û´®È»ºóÔËÐÐËü¡£ÓÐËÄÖÖ±ê×¼·½·¨¿ÉÒÔʵÏÖ£ºeval()£¬Function()¹¹ÔìÆ÷£¬setTimeout()ºÍsetInterval()¡£Ã¿¸öº¯ÊýÔÊÐíÄã´«ÈëÒ»´®JavaScript´úÂ룬ȻºóÔËÐÐËü¡£ÀýÈ磺
var num1 = 5,
num2 = 6,
//eval() evaluating a string of code
result = eval("num1 + num2"),
//Function() evaluating strings of code
sum = new Function("arg1", "arg2", "return arg1 + arg2");
//setTimeout() evaluating a string of code
setTimeout("sum = num1 + num2", 100);
//setInterval() evaluating a string of code
setInterval("sum = num1 + num2", 100);
Whenever you're evaluating Jav
Ïà¹ØÎĵµ£º
±¾ÎÄÖ÷ÒªÊdzöÓÚÓÐÅóÓÑʹÓÃÎÒÔÀ´Ð´µÄautocompleteµÄJS¿Ø¼þ¡£µ±Êý¾ÝÁ¿´óµÄʱºò£¬»á³öÏÖЧÂʼ«ÆäÂýµÄÇé¿ö£¬ÎÒÔÚÕâ¶Îʱ¼ä×ö³öµÄһЩ²âÊÔÒ²¼°Ò»Ð©¾Ñ飬Óë´ó¼Ò·ÖÏí£¬Èç¹ûÓдíµÄµØ·½£¬»¹ÇëÖ¸³ö¡£
¾¹ý²âÊÔ£¬ÎÒÃǻᷢÏÖÈçϵÄÇé¿ö»òÕß˵µÄ½áÂÛ£¬Èç¹ûÄúµÄ²âÊÔ½á¹ûÓëÎҵIJ»·û£¬Çë˵Ã÷ÔÒò£¬ÒÔ±ãÏ໥ѧϰ¡£
1£©µ±Ò»¸ö½Ï´óµÄHTML×Ö· ......
³£¹æµÄ·½·¨Êǽ«ÄêÔÂÈÕÈ¡³ö£¬È»ºó·Ö±ðÅжϷ¶Î§£¬È»ºó¾ÍÅжÏÈòÄê2ÔµÄÌìÊý
¿ÉÒÔͨ¹ýnew Date(string)µÄ¹¹Ô죬±È½ÏÄêÔÂÈÕ×Ö·ûÊÇ·ñ·¢Éú±ä»¯Åжϡ£
function CheckDate(text) {
if (!text) return false;
text = text.replace(/[\/-]0?/g, "/");
if (!text.match(/^\d{4}\/\d{1,2}\/\d{1,2}$/)) return true;
......
function total(){
var i=0;
for(j=1;j<=20;j++)
{
var step="step"+j;
if(document.getElementById(step)){
if(document.getElementById(step).checked==true)
{
i=i+parseInt(document.getElementById(step).value);
}
}
}
document.getElementById("total").innerHTML = i;
}
function Resetvalue(){
......
Data Format Conclusions Êý¾Ý¸ñʽ×ܽá
Favor lightweight formats in general; the best are JSON and a character-delimited custom format. If the data set is large and parse time becomes an issue, use one of these two techniques:
×ܵÄÀ´ËµÔ½ÇáÁ¿¼¶µÄ¸ñʽԽºÃ£¬× ......