分类 JAVASCRIPT 下的文章

base32 encoding in javascript

经测试不支持中文,只支持英文字符。

[code language="javascript"]
var baseenc = baseenc || {};
baseenc.b32encode = function(s) {
/* encodes a string s to base32 and returns the encoded string */
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

var parts = [];
var quanta= Math.floor((s.length / 5));
var leftover = s.length % 5;

if (leftover != 0) {
for (var i = 0; i < (5-leftover); i++) { s += '\x00'; }
quanta += 1;
}

for (i = 0; i < quanta; i++) {
parts.push(alphabet.charAt(s.charCodeAt(i*5) >> 3));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5) & 0x07) << 2)
| (s.charCodeAt(i*5+1) >> 6)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+1) & 0x3F) >> 1) ));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+1) & 0x01) << 4)
| (s.charCodeAt(i*5+2) >> 4)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+2) & 0x0F) << 1)
| (s.charCodeAt(i*5+3) >> 7)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+3) & 0x7F) >> 2)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+3) & 0x03) << 3)
| (s.charCodeAt(i*5+4) >> 5)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+4) & 0x1F) )));
}

var replace = 0;
if (leftover == 1) replace = 6;
else if (leftover == 2) replace = 4;
else if (leftover == 3) replace = 3;
else if (leftover == 4) replace = 1;

for (i = 0; i < replace; i++) parts.pop();
for (i = 0; i < replace; i++) parts.push("=");

return parts.join("");
};
[/code]

via

javascript版base64编码和解码

[code language="javascript"]

var base64EncodeChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var base64DecodeChars=new Array(-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1);

function base64_encode(str){var utf16to8=function(s){var out,i,len,c;out="";len=s.length;for(i=0;i<len;i++){c=s.charCodeAt(i);if((c>=0x0001)&&(c<=0x007F)){out+=s.charAt(i)}else if(c>0x07FF){out+=String.fromCharCode(0xE0|((c>>12)&0x0F));out+=String.fromCharCode(0x80|((c>>6)&0x3F));out+=String.fromCharCode(0x80|((c>>0)&0x3F))}else{out+=String.fromCharCode(0xC0|((c>>6)&0x1F));out+=String.fromCharCode(0x80|((c>>0)&0x3F))}}return out};str=utf16to8(str);var out,i,len;var c1,c2,c3;len=str.length;i=0;out="";while(i<len){c1=str.charCodeAt(i++)&0xff;if(i==len){out+=base64EncodeChars.charAt(c1>>2);out+=base64EncodeChars.charAt((c1&0x3)<<4);out+="==";break}c2=str.charCodeAt(i++);if(i==len){out+=base64EncodeChars.charAt(c1>>2);out+=base64EncodeChars.charAt(((c1&0x3)<<4)|((c2&0xF0)>>4));out+=base64EncodeChars.charAt((c2&0xF)<<2);out+="=";break}c3=str.charCodeAt(i++);out+=base64EncodeChars.charAt(c1>>2);out+=base64EncodeChars.charAt(((c1&0x3)<<4)|((c2&0xF0)>>4));out+=base64EncodeChars.charAt(((c2&0xF)<<2)|((c3&0xC0)>>6));out+=base64EncodeChars.charAt(c3&0x3F)}return out}

function base64_decode(str){var c1,c2,c3,c4;var i,len,out;len=str.length;i=0;out="";while(i<len){do{c1=base64DecodeChars[str.charCodeAt(i++)&0xff]}while(i<len&&c1==-1);if(c1==-1)break;do{c2=base64DecodeChars[str.charCodeAt(i++)&0xff]}while(i<len&&c2==-1);if(c2==-1)break;out+=String.fromCharCode((c1<<2)|((c2&0x30)>>4));do{c3=str.charCodeAt(i++)&0xff;if(c3==61)return out;c3=base64DecodeChars[c3]}while(i<len&&c3==-1);if(c3==-1)break;out+=String.fromCharCode(((c2&0XF)<<4)|((c3&0x3C)>>2));do{c4=str.charCodeAt(i++)&0xff;if(c4==61)return out;c4=base64DecodeChars[c4]}while(i<len&&c4==-1);if(c4==-1)break;out+=String.fromCharCode(((c3&0x03)<<6)|c4)}var utf8to16=function(s){var out,i,len,c;var char2,char3;out="";len=s.length;i=0;while(i<len){c=s.charCodeAt(i++);switch(c>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:out+=s.charAt(i-1);break;case 12:case 13:char2=s.charCodeAt(i++);out+=String.fromCharCode(((c&0x1F)<<6)|(char2&0x3F));break;case 14:char2=s.charCodeAt(i++);char3=s.charCodeAt(i++);out+=String.fromCharCode(((c&0x0F)<<12)|((char2&0x3F)<<6)|((char3&0x3F)<<0));break}}return out};return utf8to16(out)}

[/code]

Firefox和chrome的Media Player Plugin不触发PlayStateChange的解决办法

在网页里面插入了下面的播放器代码:

[code language="html"]
<OBJECT style="float:right;" id="MediaPlayer" width="192" height="216" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="application/x-oleobject">
<PARAM NAME="URL" VALUE="mms://211.89.225.104/cnr001">
<PARAM NAME="SendPlayStateChangeEvents" VALUE="True">
<PARAM NAME="AutoStart" VALUE="False">
<PARAM name="uiMode" value="mini">
<PARAM name="PlayCount" value="1">
<EMBED TYPE="application/x-mplayer2" CLSID={6BF52A52-394A-11D3-B153-00C04F79FAA6} SRC="mms://211.89.225.104/cnr001" ID="MediaPlayer" NAME="MediaPlayer" WIDTH=200 HEIGHT=50 VOLUME=-1 RATE=1.0></EMBED>
</OBJECT>[/code]

chrome里面怎么都不会触发playStateChange事件,找了很久的资料,原来要这样才能捕获这个事件:

function OnDSPlayStateChangeEvt(state){
//这个参数state你就可以用了,就是页面中的播放器的状态
//handler
}

OnDSPlayStateChangeEvt没有用到播放器的ID什么的,不知道放两个播放器会是一种什么情况。还有一些其它的事件和这个类同OnDSPlayStateChangeEvt,把红色的换成其它事件的名字就行了。很诡异的调用。

解决在iframe页面里使用了DD_belatedPNG后显示空白的bug

IE6不支持png的图片,DD_belatedPNG这个js脚本可以使png图片或背景透明,http://www.dillerdesign.com/experiment/DD_belatedPNG/。但在使用过程中发现一个问题,当页面嵌在iframe里面时,显示的是空白,什么都看不到,问题出现在下面这个地方:

if(a.currentStyle.position=="static"){a.style.position="relative"}

这里的a元素没有排除HTML节点,把HTML的position也设为relative了,改为下面的代码即可解决问题:

if(a.currentStyle.position=="static"){if(a.nodeName!='HTML') a.style.position="relative"}

下面是修改过的完整的代码,你也可以自行修改。

[code language="javascript"]
/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.8a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/
var DD_belatedPNG={ns:"DD_belatedPNG",imgSize:{},delay:10,nodesFixed:0,createVmlNameSpace:function(){if(document.namespaces&&!document.namespaces[this.ns]){document.namespaces.add(this.ns,"urn:schemas-microsoft-com:vml")}},createVmlStyleSheet:function(){var b,a;b=document.createElement("style");b.setAttribute("media","screen");document.documentElement.firstChild.insertBefore(b,document.documentElement.firstChild.firstChild);if(b.styleSheet){b=b.styleSheet;b.addRule(this.ns+"\\:*","{behavior:url(#default#VML)}");b.addRule(this.ns+"\\:shape","position:absolute;");b.addRule("img."+this.ns+"_sizeFinder","behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;");this.screenStyleSheet=b;a=document.createElement("style");a.setAttribute("media","print");document.documentElement.firstChild.insertBefore(a,document.documentElement.firstChild.firstChild);a=a.styleSheet;a.addRule(this.ns+"\\:*","{display: none !important;}");a.addRule("img."+this.ns+"_sizeFinder","{display: none !important;}")}},readPropertyChange:function(){var b,c,a;b=event.srcElement;if(!b.vmlInitiated){return}if(event.propertyName.search("background")!=-1||event.propertyName.search("border")!=-1){DD_belatedPNG.applyVML(b)}if(event.propertyName=="style.display"){c=(b.currentStyle.display=="none")?"none":"block";for(a in b.vml){if(b.vml.hasOwnProperty(a)){b.vml[a].shape.style.display=c}}}if(event.propertyName.search("filter")!=-1){DD_belatedPNG.vmlOpacity(b)}},vmlOpacity:function(b){if(b.currentStyle.filter.search("lpha")!=-1){var a=b.currentStyle.filter;a=parseInt(a.substring(a.lastIndexOf("=")+1,a.lastIndexOf(")")),10)/100;b.vml.color.shape.style.filter=b.currentStyle.filter;b.vml.image.fill.opacity=a}},handlePseudoHover:function(a){setTimeout(function(){DD_belatedPNG.applyVML(a)},1)},fix:function(a){if(this.screenStyleSheet){var c,b;c=a.split(",");for(b=0;b<c.length;b++){this.screenStyleSheet.addRule(c[b],"behavior:expression(DD_belatedPNG.fixPng(this))")}}},applyVML:function(a){a.runtimeStyle.cssText="";this.vmlFill(a);this.vmlOffsets(a);this.vmlOpacity(a);if(a.isImg){this.copyImageBorders(a)}},attachHandlers:function(i){var d,c,g,e,b,f;d=this;c={resize:"vmlOffsets",move:"vmlOffsets"};if(i.nodeName=="A"){e={mouseleave:"handlePseudoHover",mouseenter:"handlePseudoHover",focus:"handlePseudoHover",blur:"handlePseudoHover"};for(b in e){if(e.hasOwnProperty(b)){c[b]=e[b]}}}for(f in c){if(c.hasOwnProperty(f)){g=function(){d[c[f]](i)};i.attachEvent("on"+f,g)}}i.attachEvent("onpropertychange",this.readPropertyChange)},giveLayout:function(a){a.style.zoom=1;if(a.currentStyle.position=="static"){if(a.nodeName!='HTML') a.style.position="relative"}},copyImageBorders:function(b){var c,a;c={borderStyle:true,borderWidth:true,borderColor:true};for(a in c){if(c.hasOwnProperty(a)){b.vml.color.shape.style[a]=b.currentStyle[a]}}},vmlFill:function(e){if(!e.currentStyle){return}else{var d,f,g,b,a,c;d=e.currentStyle}for(b in e.vml){if(e.vml.hasOwnProperty(b)){e.vml[b].shape.style.zIndex=d.zIndex}}e.runtimeStyle.backgroundColor="";e.runtimeStyle.backgroundImage="";f=true;if(d.backgroundImage!="none"||e.isImg){if(!e.isImg){e.vmlBg=d.backgroundImage;e.vmlBg=e.vmlBg.substr(5,e.vmlBg.lastIndexOf('")')-5)}else{e.vmlBg=e.src}g=this;if(!g.imgSize[e.vmlBg]){a=document.createElement("img");g.imgSize[e.vmlBg]=a;a.className=g.ns+"_sizeFinder";a.runtimeStyle.cssText="behavior:none; position:absolute; left:-10000px; top:-10000px; border:none; margin:0; padding:0;";c=function(){this.width=this.offsetWidth;this.height=this.offsetHeight;g.vmlOffsets(e)};a.attachEvent("onload",c);a.src=e.vmlBg;a.removeAttribute("width");a.removeAttribute("height");document.body.insertBefore(a,document.body.firstChild)}e.vml.image.fill.src=e.vmlBg;f=false}e.vml.image.fill.on=!f;e.vml.image.fill.color="none";e.vml.color.shape.style.backgroundColor=d.backgroundColor;e.runtimeStyle.backgroundImage="none";e.runtimeStyle.backgroundColor="transparent"},vmlOffsets:function(d){var h,n,a,e,g,m,f,l,j,i,k;h=d.currentStyle;n={W:d.clientWidth+1,H:d.clientHeight+1,w:this.imgSize[d.vmlBg].width,h:this.imgSize[d.vmlBg].height,L:d.offsetLeft,T:d.offsetTop,bLW:d.clientLeft,bTW:d.clientTop};a=(n.L+n.bLW==1)?1:0;e=function(b,p,q,c,s,u){b.coordsize=c+","+s;b.coordorigin=u+","+u;b.path="m0,0l"+c+",0l"+c+","+s+"l0,"+s+" xe";b.style.width=c+"px";b.style.height=s+"px";b.style.left=p+"px";b.style.top=q+"px"};e(d.vml.color.shape,(n.L+(d.isImg?0:n.bLW)),(n.T+(d.isImg?0:n.bTW)),(n.W-1),(n.H-1),0);e(d.vml.image.shape,(n.L+n.bLW),(n.T+n.bTW),(n.W),(n.H),1);g={X:0,Y:0};if(d.isImg){g.X=parseInt(h.paddingLeft,10)+1;g.Y=parseInt(h.paddingTop,10)+1}else{for(j in g){if(g.hasOwnProperty(j)){this.figurePercentage(g,n,j,h["backgroundPosition"+j])}}}d.vml.image.fill.position=(g.X/n.W)+","+(g.Y/n.H);m=h.backgroundRepeat;f={T:1,R:n.W+a,B:n.H,L:1+a};l={X:{b1:"L",b2:"R",d:"W"},Y:{b1:"T",b2:"B",d:"H"}};if(m!="repeat"||d.isImg){i={T:(g.Y),R:(g.X+n.w),B:(g.Y+n.h),L:(g.X)};if(m.search("repeat-")!=-1){k=m.split("repeat-")[1].toUpperCase();i[l[k].b1]=1;i[l[k].b2]=n[l[k].d]}if(i.B>n.H){i.B=n.H}d.vml.image.shape.style.clip="rect("+i.T+"px "+(i.R+a)+"px "+i.B+"px "+(i.L+a)+"px)"}else{d.vml.image.shape.style.clip="rect("+f.T+"px "+f.R+"px "+f.B+"px "+f.L+"px)"}},figurePercentage:function(d,c,f,a){var b,e;e=true;b=(f=="X");switch(a){case"left":case"top":d[f]=0;break;case"center":d[f]=0.5;break;case"right":case"bottom":d[f]=1;break;default:if(a.search("%")!=-1){d[f]=parseInt(a,10)/100}else{e=false}}d[f]=Math.ceil(e?((c[b?"W":"H"]*d[f])-(c[b?"w":"h"]*d[f])):parseInt(a,10));if(d[f]%2===0){d[f]++}return d[f]},fixPng:function(c){c.style.behavior="none";var g,b,f,a,d;if(c.nodeName=="BODY"||c.nodeName=="TD"||c.nodeName=="TR"){return}c.isImg=false;if(c.nodeName=="IMG"){if(c.src.toLowerCase().search(/\.png$/)!=-1){c.isImg=true;c.style.visibility="hidden"}else{return}}else{if(c.currentStyle.backgroundImage.toLowerCase().search(".png")==-1){return}}g=DD_belatedPNG;c.vml={color:{},image:{}};b={shape:{},fill:{}};for(a in c.vml){if(c.vml.hasOwnProperty(a)){for(d in b){if(b.hasOwnProperty(d)){f=g.ns+":"+d;c.vml[a][d]=document.createElement(f)}}c.vml[a].shape.stroked=false;c.vml[a].shape.appendChild(c.vml[a].fill);c.parentNode.insertBefore(c.vml[a].shape,c)}}c.vml.image.shape.fillcolor="none";c.vml.image.fill.type="tile";c.vml.color.fill.on=false;g.attachHandlers(c);g.giveLayout(c);g.giveLayout(c.offsetParent);c.vmlInitiated=true;g.applyVML(c)}};try{document.execCommand("BackgroundImageCache",false,true)}catch(r){}DD_belatedPNG.createVmlNameSpace();DD_belatedPNG.createVmlStyleSheet();
[/code]

google maps api教程(一):用google maps生成向导生成即时地图

用google maps生成向导生成即时地图。google提供了一个向导来生成google maps的代码片段,你可以把它放入到你的网站页面中。点击此处转到向导页,并按照里面的3个简单的步骤操作。

1、定制地图的长宽、缩放级别、中心位置、中心位置的链接地址、中心位置的地址说明。当点击中心位置的那个箭头时会显示这些信息。

2、输入你网站的网址,以便生成一个API key。

3、点击生成按钮就可以生成代码了。

最后把生成的代码复制到您自己的网页中就可以使用了,以下为生成的代码例子:

[code language="javascript"]
<!-- ++Begin Map Search Control Wizard Generated Code++ -->
<!--
// Created with a Google AJAX Search Wizard
// http://code.google.com/apis/ajaxsearch/wizards.html
-->

<!--
// The Following div element will end up holding the map search control.
// You can place this anywhere on your page
-->
<div id="mapsearch">
<span style="color:#676767;font-size:11px;margin:10px;padding:4px;">Loading...</span>
</div>

<!-- Maps Api, Ajax Search Api and Stylesheet
// Note: If you are already using the Maps API then do not include it again
// If you are already using the AJAX Search API, then do not include it
// or its stylesheet again
//
// The Key Embedded in the following script tags is designed to work with
// the following site:
// http://junstyle.me
-->
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAurOz_u21LMSjFODxuxTsbxSWkWNcz8otOi80ukkm5C_9fVjCfhS7lPl_eE2MldQL6fDI9jugOBzLoA"
type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&source=uds-msw&key=ABQIAAAAurOz_u21LMSjFODxuxTsbxSWkWNcz8otOi80ukkm5C_9fVjCfhS7lPl_eE2MldQL6fDI9jugOBzLoA"
type="text/javascript"></script>
<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
</style>

<!-- Map Search Control and Stylesheet -->
<script type="text/javascript">
window._uds_msw_donotrepair = true;
</script>
<script src="http://www.google.com/uds/solutions/mapsearch/gsmapsearch.js?mode=new"
type="text/javascript"></script>
<style type="text/css">
@import url("http://www.google.com/uds/solutions/mapsearch/gsmapsearch.css");
</style>

<style type="text/css">
.gsmsc-mapDiv {
height : 275px;
}

.gsmsc-idleMapDiv {
height : 275px;
}

#mapsearch {
width : 365px;
margin: 10px;
padding: 4px;
}
</style>
<script type="text/javascript">
function LoadMapSearchControl() {

var options = {
zoomControl : GSmapSearchControl.ZOOM_CONTROL_ENABLE_ALL,
title : "Googleplex",
url : "http://www.google.com/corporate/index.html",
idleMapZoom : GSmapSearchControl.ACTIVE_MAP_ZOOM,
activeMapZoom : GSmapSearchControl.ACTIVE_MAP_ZOOM
}

new GSmapSearchControl(
document.getElementById("mapsearch"),
"1600 Amphitheatre Parkway, Mountain View, CA",
options
);

}
// arrange for this function to be called during body.onload
// event processing
GSearch.setOnLoadCallback(LoadMapSearchControl);
</script>
<!-- ++End Map Search Control Wizard Generated Code++ -->
[/code]

把以上的代码放置到你的页面的body之间,不要放在head里面。

本文参考自:http://econym.org.uk/gmap/wizard.htm

javascript中的getYear()在firefox下的问题

JS getYear在firefox下有问题

用了JS的getYear()方法,但是发现生成的代码竟然有108(本应该是2008),发现这是firefox下的问题。在 Firefox 里面 getYear 返回的是 "当前年份-1900" 的值,而IE里面则:当today的年份小于2000的时候,和firefox一样。当today的年份大于等于2000的时候 在返回的基础上额外加上1900 如:today年份是1999 返回99(同firefox) today年份是2000 返回100+1900=2000 所以最好用 getFullYear或者getUTCFullYear 去获取完整的年份 var year = today.getFullYear();在IE,FireFox都适用。

如:(js代码)

var today = new Date();

var fullyear = today.getFullYear();

var year = today.getYear();

document.write(fullyear + "<br>");

document.write(year + "<br>");

结果:

2010

110

一个求时间差的方法

function DateDiff(sDate1,sDate2){
//sDate1和sDate2是年-月-日格式
var arrDate,objDate1,objDate2,intDays;
arrDate=sDate1.split("-");
objDate1=new Date(arrDate[1]+'-'+arrDate[2]+'-'+arrDate[0]);//转换为月-日-年格式
arrDate=sDate2.split("-");
objDate2=new Date(arrDate[1]+'-'+arrDate[2]+'-'+arrDate[0]);
intDays=parseInt(Math.abs(objDate1-objDate2)/1000/60/60/24); //把相差的毫秒数转换为天数
return intDays;
}
alert(DateDiff("2007-1-1","2008-1-1"));

javascript获取某个月的天数

Javascript里面的new Date("xxxx/xx/xx")这个日期的构造方法有一个妙处,当你传入的是"xxxx/xx/0"(0号)的话,得到的日期是"xx"月的前一个月的最后一天("xx"月的最大取值是69,题外话),如果传入"1999/13/0",会得到"1998/12/31"。而且最大的好处是当你传入"xxxx/3/0",会得到xxxx年2月的最后一天,它会自动判断当年是否是闰年来返回28或29,不用自己判断,太方便了!!所以,我们想得到选择年选择月有多少天的话,只需要

var d=new Date("选择年/选择月+1/0");

alert(d.getDate());

下面是使用Javascript编写的获取某年某月有多少天的getDaysInOneMonth(year, month)方法:

function getDaysInOneMonth(year, month){
month = parseInt(month,10)+1;
var d= new Date(year+"/"+month+"/0");
return d.getDate();
}

javascript里面的小数计算出现近似值的解决办法

在javascript里面,小数只能进行相似计算,例如:5.06+1.30,你得到的结果会是6.359999999999999,但有的小数计算又是正确的,如果计算出现了近似值,你可以用如下的方法计算:
[code language="javascript"]
var number1 = 5.06;
var number2 = 1.30;
var sum = (number1 * 100 + number2 * 100) / 100; //sum=6.36,不是一个近似值
[/code]
这样计算可以得到一个准确的结果。

javascript代码优化

一、字符串的连接

通常我们进行字符串连接是这样的:

var veryLongMessage =
'This is a long string that due to our strict line length limit of' +
maxCharsPerLine +
' characters per line must be wrapped. ' +
percentWhoDislike +
'% of engineers dislike this rule. The line length limit is for ' +
' style purposes, but we don't want it to have a performance impact.' +
' So the question is how should we do the wrapping?';

可以用如下的数字代替:

var veryLongMessage =
['This is a long string that due to our strict line length limit of',
maxCharsPerLine,
' characters per line must be wrapped. ',
percentWhoDislike,
'% of engineers dislike this rule. The line length limit is for ',
' style purposes, but we don't want it to have a performance impact.',
' So the question is how should we do the wrapping?'
].join();

二、通过助手函数生成字符串

通过把字符串生成器传递到函数中来构造一个长字符串,要避免临时的String结果,例如,假设函数buildMenuItemHtml_ 需要用文字串(literal)和变量来构造String,并在内部使用了String构造器.而不是如下方式使用:
var strBuilder = [];
for (var i = 0, length = menuItems.length; i < length; i++) {
strBuilder.push(this.buildMenuItemHtml_(menuItems[i]));
}
var menuHtml = strBuilder.join();

推荐如下方式:

var strBuilder = [];
for (var i = 0, length = menuItems.length; i < length; i++) {
this.buildMenuItem_(menuItems[i], strBuilder);
}
var menuHtml = strBuilder.join();

三、定义类方法(Defining class methods)

下面的代码是低效率的,每生成一次baz.Bar对象,就会为其生成一个方法和闭包.
baz.Bar = function() {
// 构造函数, constructor body
this.foo = function() {
// 方法,method body
};
}

推荐方式是:
baz.Bar = function() {
// 构造函数,constructor body
};

baz.Bar.prototype.foo = function() {
//方法, method body
};

这种方式,不管有多少个baz.Bar对象生成,仅仅只建立一个方法foo且没有产生闭包.

四、初始化实例变量(Initializing instance variables)

在原型(prototype)上用值类型[value type](而不是引用类型[reference type])声明或初始化实例变量.这避免了在每次调用构造函数时运行不必要的初始化代码.(有些情况下是不能这样做的:实例变量的初始值依赖于构造参数或是在构造时的其它状态的变量(some other state at time of construction))
例子:
foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};

推荐的写法:
foo.Bar = function() {
this.prop3_ = [];
};
foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';

五、避开闭包的陷阱(Avoiding pitfalls with closures)

闭包是JavaScript的一个强大且有用的特色;但是它有几个缺点:
1,它们是常见的内存泄漏源
2,生成闭包明显的比生成不是闭包的内部函数慢,比调用静态函数更慢.例如
function setupAlertTimeout() {
var msg = 'Message to alert';
window.setTimeout(function() { alert(msg); }, 100);
}

上面比下面的写法要慢:(上面的代码产生了闭包)
function setupAlertTimeout() {
window.setTimeout(function() {
var msg = 'Message to alert';
alert(msg);
}, 100);
}

上面比下面的写法要慢:
function alertMsg() {
var msg = 'Message to alert';
alert(msg);
}

function setupAlertTimeout() {
window.setTimeout(alertMsg, 100);
}

3,它们增加了变量的作用域(scope chain)的层次.当浏览器解析属性的时候,将会检查所有层次的作用域.见下面的例子:
var a = 'a';
function createFunctionWithClosure() {
var b = 'b';
return function () {
var c = 'c';
a;
b;
c;
};
}

var f = createFunctionWithClosure();
f();

当执行f方法的时候,引用a比引用b慢,引用b比引用c慢.
IE中闭包更多信息可以查看 IE+JScript Performance Recommendations Part 3: JavaScript Code inefficiencies

六、避免用with(Avoiding with)

在你代码中避免用with.它对性能有负面影响,因为它修改了作用域,在其它作用域查找变量的开销很大.

七、避免浏览器的内存泄露(Avoiding browser memory leaks)

内存泄露是web应用程序普遍存在的问题,它会产生巨大的性能危害(hit).随着浏览器内存使用增加,你的web应用程序,用户系统其它部分操作,将变的慢起来.大部分web应用程序的内存泄露是因为在 JavaScript脚本和Dom之间生成了循环引用(例如:javascript脚本和IE com结构之间,javascript脚本和Firefox xpcom结构之间)
下面是避免内存泄漏一些经验法则

使用事件系统关联事件处理函数(Use an event system for attaching event handlers)
大部分的循环引用模式[DOM 元素-->事件处理函数(event handler)-->闭包(closure scope)-->DOM元素].为了避免这个问题,可以用经过充分测试事件系统(event system)来关联事件处理函数(event handlers),例如:Google doctype,Dojo,JQuery
另外,在IE中使用用内联事件函数(inline event handlers)会导致另一种的类型的泄露.这不是通常的循环引用类型的泄露,而是由内部临时匿名脚本对象产生的泄露.详细信息,请看文章"DOM insertin Order Leak Model"和例子JavaScript Kit tutorial.
避免扩展(expando)属性
扩展(expando)属性是把任意JavaScript的属性附加的到DOM元素上,这是循环引用产生的根源.你可以不产生内存泄露来扩展 (expando)属性,但是这是很容易产生内存泄露的.泄露模式是[DOM元素-->扩展(via expando)-->中间对象(intermediary object)-->DOM元素].最好是避免使用用它们.如果你用到它们,仅可使用原始类型(primitive types)作为值.如果不是原始类型,当扩展(expando)属性不在使用的时候,要把它置为空.可以参考文章"Circular References"