JavaScript学习总结-技巧、实用函数、简洁方法、编程细节
2015-06-18 14:33
726 查看
整理JavaScript方面的一些技巧,比较实用的函数,常见功能实现方法,仅作参考
变量转换
//edithttp://www.lai18.com
varmyVar="3.14159",
str=""+myVar,//tostring
int=~~myVar,//tointeger
float=1*myVar,//tofloat
bool=!!myVar,/*toboolean-anystringwithlength
andanynumberexcept0aretrue*/
array=[myVar];//toarray
但是转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。
取整同时转换成数值型
//edithttp://www.lai18.com
//字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)
'10.567890'|0
//结果:10
//JS里面的所有数值型都是双精度浮点数,因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算
//|是二进制或,x|0永远等于x;^为异或,同0异1,所以x^0还是永远等于x;至于~是按位取反,搞了两次以后值当然是一样的
'10.567890'^0
//结果:10
-2.23456789|0
//结果:-2
~~-2.23456789
//结果:-2
日期转数值
//JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位
vard=+newDate();//1295698416792
类数组对象转数组
vararr=[].slice.call(arguments)
下面的实例用的更绝
functiontest(){
varres=['item1','item2']
res=res.concat(Array.prototype.slice.call(arguments))//方法1
Array.prototype.push.apply(res,arguments)//方法2
}
进制之间的转换
(int).toString(16);//convertsinttohex,eg12=>"C"
(int).toString(8);//convertsinttooctal,eg.12=>"14"
parseInt(string,16)//convertshextoint,eg."FF"=>255
parseInt(string,8)//convertsoctaltoint,eg."20"=>16
将一个数组插入另一个数组指定的位置
vara=[1,2,3,7,8,9];
varb=[4,5,6];
varinsertIndex=3;
a.splice.apply(a,Array.prototype.concat(insertIndex,0,b));
删除数组元素
vara=[1,2,3,4,5];
a.splice(3,1);//a=[1,2,3,5]
大家也许会想为什么要用splice而不用delete,因为用delete将会在数组里留下一个空洞,而且后面的下标也并没有递减。
判断是否为IE
varie=/*@cc_on!@*/false;
这样一句简单的话就可以判断是否为ie,太。。。
其实还有更多妙的方法,请看下面
//edithttp://www.lai18.com
//貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制
varie=!-[1,];
//利用了IE的条件注释
varie=/*@cc_on!@*/false;
//还是条件注释
varie//@cc_on=1;
//IE不支持垂直制表符
varie='v'=='v';
//原理同上
varie=!+"v1";
学到这个瞬间觉得自己弱爆了。
尽量利用原生方法
要找一组数字中的最大数,我们可能会写一个循环,例如:
varnumbers=[3,342,23,22,124];
varmax=0;
for(vari=0;i<numbers.length;i++){
if(numbers[i]>max){
max=numbers[i];
}
}
alert(max);
其实利用原生的方法,可以更简单实现
varnumbers=[3,342,23,22,124];
numbers.sort(function(a,b){returnb-a});
alert(numbers[0]);
当然最简洁的方法便是:
Math.max(12,123,3,2,433,4);//returns433
当前也可以这样
[xhtml]view plaincopy
Math.max.apply(Math,[12,123,3,2,433,4])//取最大值
Math.min.apply(Math,[12,123,3,2,433,4])//取最小值
生成随机数
Math.random().toString(16).substring(2);//toString()函数的参数为基底,范围为2~36。
Math.random().toString(36).substring(2);
不用第三方变量交换两个变量的值
a=[b,b=a][0];
事件委派
举个简单的例子:html代码如下
<h2>GreatWebresources</h2>
<ulid="resources">
<li><ahref="http://opera.com/wsc">OperaWebStandardsCurriculum</a></li>
<li><ahref="http://sitepoint.com">Sitepoint</a></li>
<li><ahref="http://alistapart.com">AListApart</a></li>
<li><ahref="http://yuiblog.com">YUIBlog</a></li>
<li><ahref="http://blameitonthevoices.com">Blameitonthevoices</a></li>
<li><ahref="http://oddlyspecific.com">Oddlyspecific</a></li>
</ul>
js代码如下:
//Classiceventhandlingexample
(function(){
varresources=document.getElementById('resources');
varlinks=resources.getElementsByTagName('a');
varall=links.length;
for(vari=0;i<all;i++){
//Attachalistenertoeachlink
links[i].addEventListener('click',handler,false);
};
functionhandler(e){
varx=e.target;//Getthelinkthatwasclicked
alert(x);
e.preventDefault();
};
})();
利用事件委派可以写出更加优雅的:
(function(){
varresources=document.getElementById('resources');
resources.addEventListener('click',handler,false);
functionhandler(e){
varx=e.target;//getthelinktha
if(x.nodeName.toLowerCase()==='a'){
alert('Eventdelegation:'+x);
e.preventDefault();
}
};
})();
检测ie版本
var_IE=(function(){
varv=3,div=document.createElement('div'),all=div.getElementsByTagName('i');
while(
div.innerHTML='<!--[ifgtIE'+(++v)+']><i></i><![endif]-->',
all[0]
);
returnv>4?v:false;
}());
javaScript版本检测
你知道你的浏览器支持哪一个版本的Javascript吗?
varJS_ver=[];
(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf&&[].forEach)?JS_ver.push("1.6"):false;
((function(){try{[a,b]=[0,1];returntrue;}catch(ex){returnfalse;}})())?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("LatestJavascriptversionsupported:"+JS_ver.supports());
alert("Supportforversion1.7:"+JS_ver.supports("1.7"));
判断属性是否存在
//BAD:Thiswillcauseanerrorincodewhenfooisundefined
if(foo){
doSomething();
}
//GOOD:Thisdoesn'tcauseanyerrors.However,evenwhen
//fooissettoNULLorfalse,theconditionvalidatesastrue
if(typeoffoo!="undefined"){
doSomething();
}
//BETTER:Thisdoesn'tcauseanyerrorsandinaddition
//valuesNULLorfalsewon'tvalidateastrue
if(window.foo){
doSomething();
}
有的情况下,我们有更深的结构和需要更合适的检查的时候
//UGLY:wehavetoproofexistenceofevery
//objectbeforewecanbesurepropertyactuallyexists
if(window.oFoo&&oFoo.oBar&&oFoo.oBar.baz){
doSomething();
}
其实最好的检测一个属性是否存在的方法为:
if("opera"inwindow){
console.log("OPERA");
}else{
console.log("NOTOPERA");
}
检测对象是否为数组
varobj=[];
Object.prototype.toString.call(obj)=="[objectArray]";
给函数传递对象
functiondoSomething(){
//Leavesthefunctionifnothingispassed
if(!arguments[0]){
returnfalse;
}
varoArgs=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
});
为replace方法传递一个函数
varsFlop="Flop:[Ah][Ks][7c]";
varaValues={"A":"Ace","K":"King",7:"Seven"};
varaSuits={"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");
returnmatch;
});
//stringsFlopnowcontains:
//"Flop:[AceofHearts][KingofSpades][SevenofClubs]"
循环中使用标签
有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法
outerloop:
for(variI=0;iI<5;iI++){
if(somethingIsTrue()){
//Breakstheouterloopiteration
breakouterloop;
}
innerloop:
for(variA=0;iA<5;iA++){
if(somethingElseIsTrue()){
//Breakstheinnerloopiteration
breakinnerloop;
}
}
}
对数组进行去重
/*
*@desc:对数组进行去重操作,返回一个没有重复元素的新数组
*/
functionunique(target){
varresult=[];
loop:for(vari=0,n=target.length;i<n;i++){
for(varx=i+1;x<n;x++){
if(target[x]===target[i]){
continueloop;
}
}
result.push(target[i]);
}
returnresult;
}
或者如下:
Array.prototype.distinct=function(){
varnewArr=[],obj={};
for(vari=0,len=this.length;i<len;i++){
if(!obj[typeof(this[i])+this[i]]){
newArr.push(this[i]);
obj[typeof(this[i])+this[i]]='new';
}
}
returnnewArr;
}
其实最优的方法是这样的
Array.prototype.distinct=function(){
varsameObj=function(a,b){
vartag=true;
if(!a||!b)returnfalse;
for(varxina){
if(!b[x])returnfalse;
if(typeof(a[x])==='object'){
tag=sameObj(a[x],b[x]);
}else{
if(a[x]!==b[x])
returnfalse;
}
}
returntag;
}
varnewArr=[],obj={};
for(vari=0,len=this.length;i<len;i++){
if(!sameObj(obj[typeof(this[i])+this[i]],this[i])){
newArr.push(this[i]);
obj[typeof(this[i])+this[i]]=this[i];
}
}
returnnewArr;
}
使用范例(借用评论):
vararr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];
varnewArr=arr.distinct(function(ele){
returnele.age;
});
查找字符串中出现最多的字符及个数
vari,len,maxobj='',maxnum=0,obj={};
vararr="sdjksfssscfssdd";
for(i=0,len=arr.length;i<len;i++){
obj[arr[i]]?obj[arr[i]]++:obj[arr[i]]=1;
if(maxnum<obj[arr[i]]){
maxnum=obj[arr[i]];
maxobj=arr[i];
}
}
alert(maxobj+"在数组中出现了"+maxnum+"次");
其实还有很多,这些只是我闲来无事总结的一些罢了。
变量转换
//edithttp://www.lai18.com
varmyVar="3.14159",
str=""+myVar,//tostring
int=~~myVar,//tointeger
float=1*myVar,//tofloat
bool=!!myVar,/*toboolean-anystringwithlength
andanynumberexcept0aretrue*/
array=[myVar];//toarray
但是转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。
取整同时转换成数值型
//edithttp://www.lai18.com
//字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)
'10.567890'|0
//结果:10
//JS里面的所有数值型都是双精度浮点数,因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算
//|是二进制或,x|0永远等于x;^为异或,同0异1,所以x^0还是永远等于x;至于~是按位取反,搞了两次以后值当然是一样的
'10.567890'^0
//结果:10
-2.23456789|0
//结果:-2
~~-2.23456789
//结果:-2
日期转数值
//JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位
vard=+newDate();//1295698416792
类数组对象转数组
vararr=[].slice.call(arguments)
下面的实例用的更绝
functiontest(){
varres=['item1','item2']
res=res.concat(Array.prototype.slice.call(arguments))//方法1
Array.prototype.push.apply(res,arguments)//方法2
}
进制之间的转换
(int).toString(16);//convertsinttohex,eg12=>"C"
(int).toString(8);//convertsinttooctal,eg.12=>"14"
parseInt(string,16)//convertshextoint,eg."FF"=>255
parseInt(string,8)//convertsoctaltoint,eg."20"=>16
将一个数组插入另一个数组指定的位置
vara=[1,2,3,7,8,9];
varb=[4,5,6];
varinsertIndex=3;
a.splice.apply(a,Array.prototype.concat(insertIndex,0,b));
删除数组元素
vara=[1,2,3,4,5];
a.splice(3,1);//a=[1,2,3,5]
大家也许会想为什么要用splice而不用delete,因为用delete将会在数组里留下一个空洞,而且后面的下标也并没有递减。
判断是否为IE
varie=/*@cc_on!@*/false;
这样一句简单的话就可以判断是否为ie,太。。。
其实还有更多妙的方法,请看下面
//edithttp://www.lai18.com
//貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制
varie=!-[1,];
//利用了IE的条件注释
varie=/*@cc_on!@*/false;
//还是条件注释
varie//@cc_on=1;
//IE不支持垂直制表符
varie='v'=='v';
//原理同上
varie=!+"v1";
学到这个瞬间觉得自己弱爆了。
尽量利用原生方法
要找一组数字中的最大数,我们可能会写一个循环,例如:
varnumbers=[3,342,23,22,124];
varmax=0;
for(vari=0;i<numbers.length;i++){
if(numbers[i]>max){
max=numbers[i];
}
}
alert(max);
其实利用原生的方法,可以更简单实现
varnumbers=[3,342,23,22,124];
numbers.sort(function(a,b){returnb-a});
alert(numbers[0]);
当然最简洁的方法便是:
Math.max(12,123,3,2,433,4);//returns433
当前也可以这样
[xhtml]view plaincopy
Math.max.apply(Math,[12,123,3,2,433,4])//取最大值
Math.min.apply(Math,[12,123,3,2,433,4])//取最小值
生成随机数
Math.random().toString(16).substring(2);//toString()函数的参数为基底,范围为2~36。
Math.random().toString(36).substring(2);
不用第三方变量交换两个变量的值
a=[b,b=a][0];
事件委派
举个简单的例子:html代码如下
<h2>GreatWebresources</h2>
<ulid="resources">
<li><ahref="http://opera.com/wsc">OperaWebStandardsCurriculum</a></li>
<li><ahref="http://sitepoint.com">Sitepoint</a></li>
<li><ahref="http://alistapart.com">AListApart</a></li>
<li><ahref="http://yuiblog.com">YUIBlog</a></li>
<li><ahref="http://blameitonthevoices.com">Blameitonthevoices</a></li>
<li><ahref="http://oddlyspecific.com">Oddlyspecific</a></li>
</ul>
js代码如下:
//Classiceventhandlingexample
(function(){
varresources=document.getElementById('resources');
varlinks=resources.getElementsByTagName('a');
varall=links.length;
for(vari=0;i<all;i++){
//Attachalistenertoeachlink
links[i].addEventListener('click',handler,false);
};
functionhandler(e){
varx=e.target;//Getthelinkthatwasclicked
alert(x);
e.preventDefault();
};
})();
利用事件委派可以写出更加优雅的:
(function(){
varresources=document.getElementById('resources');
resources.addEventListener('click',handler,false);
functionhandler(e){
varx=e.target;//getthelinktha
if(x.nodeName.toLowerCase()==='a'){
alert('Eventdelegation:'+x);
e.preventDefault();
}
};
})();
检测ie版本
var_IE=(function(){
varv=3,div=document.createElement('div'),all=div.getElementsByTagName('i');
while(
div.innerHTML='<!--[ifgtIE'+(++v)+']><i></i><![endif]-->',
all[0]
);
returnv>4?v:false;
}());
javaScript版本检测
你知道你的浏览器支持哪一个版本的Javascript吗?
varJS_ver=[];
(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf&&[].forEach)?JS_ver.push("1.6"):false;
((function(){try{[a,b]=[0,1];returntrue;}catch(ex){returnfalse;}})())?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("LatestJavascriptversionsupported:"+JS_ver.supports());
alert("Supportforversion1.7:"+JS_ver.supports("1.7"));
判断属性是否存在
//BAD:Thiswillcauseanerrorincodewhenfooisundefined
if(foo){
doSomething();
}
//GOOD:Thisdoesn'tcauseanyerrors.However,evenwhen
//fooissettoNULLorfalse,theconditionvalidatesastrue
if(typeoffoo!="undefined"){
doSomething();
}
//BETTER:Thisdoesn'tcauseanyerrorsandinaddition
//valuesNULLorfalsewon'tvalidateastrue
if(window.foo){
doSomething();
}
有的情况下,我们有更深的结构和需要更合适的检查的时候
//UGLY:wehavetoproofexistenceofevery
//objectbeforewecanbesurepropertyactuallyexists
if(window.oFoo&&oFoo.oBar&&oFoo.oBar.baz){
doSomething();
}
其实最好的检测一个属性是否存在的方法为:
if("opera"inwindow){
console.log("OPERA");
}else{
console.log("NOTOPERA");
}
检测对象是否为数组
varobj=[];
Object.prototype.toString.call(obj)=="[objectArray]";
给函数传递对象
functiondoSomething(){
//Leavesthefunctionifnothingispassed
if(!arguments[0]){
returnfalse;
}
varoArgs=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
});
为replace方法传递一个函数
varsFlop="Flop:[Ah][Ks][7c]";
varaValues={"A":"Ace","K":"King",7:"Seven"};
varaSuits={"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");
returnmatch;
});
//stringsFlopnowcontains:
//"Flop:[AceofHearts][KingofSpades][SevenofClubs]"
循环中使用标签
有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法
outerloop:
for(variI=0;iI<5;iI++){
if(somethingIsTrue()){
//Breakstheouterloopiteration
breakouterloop;
}
innerloop:
for(variA=0;iA<5;iA++){
if(somethingElseIsTrue()){
//Breakstheinnerloopiteration
breakinnerloop;
}
}
}
对数组进行去重
/*
*@desc:对数组进行去重操作,返回一个没有重复元素的新数组
*/
functionunique(target){
varresult=[];
loop:for(vari=0,n=target.length;i<n;i++){
for(varx=i+1;x<n;x++){
if(target[x]===target[i]){
continueloop;
}
}
result.push(target[i]);
}
returnresult;
}
或者如下:
Array.prototype.distinct=function(){
varnewArr=[],obj={};
for(vari=0,len=this.length;i<len;i++){
if(!obj[typeof(this[i])+this[i]]){
newArr.push(this[i]);
obj[typeof(this[i])+this[i]]='new';
}
}
returnnewArr;
}
其实最优的方法是这样的
Array.prototype.distinct=function(){
varsameObj=function(a,b){
vartag=true;
if(!a||!b)returnfalse;
for(varxina){
if(!b[x])returnfalse;
if(typeof(a[x])==='object'){
tag=sameObj(a[x],b[x]);
}else{
if(a[x]!==b[x])
returnfalse;
}
}
returntag;
}
varnewArr=[],obj={};
for(vari=0,len=this.length;i<len;i++){
if(!sameObj(obj[typeof(this[i])+this[i]],this[i])){
newArr.push(this[i]);
obj[typeof(this[i])+this[i]]=this[i];
}
}
returnnewArr;
}
使用范例(借用评论):
vararr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];
varnewArr=arr.distinct(function(ele){
returnele.age;
});
查找字符串中出现最多的字符及个数
vari,len,maxobj='',maxnum=0,obj={};
vararr="sdjksfssscfssdd";
for(i=0,len=arr.length;i<len;i++){
obj[arr[i]]?obj[arr[i]]++:obj[arr[i]]=1;
if(maxnum<obj[arr[i]]){
maxnum=obj[arr[i]];
maxobj=arr[i];
}
}
alert(maxobj+"在数组中出现了"+maxnum+"次");
其实还有很多,这些只是我闲来无事总结的一些罢了。
相关文章推荐
- ExtJs布局详解
- +js实现分页浏览到底部自动加载
- JS实现密码加密(base64, md5, sha1)
- 重新回顾JSP
- JavaScript版拼图小游戏
- 用JS获取地址栏参数的方法
- moment.js中文api
- Extjs编辑单行后 刷新单行
- js比较运算符==与===的区别
- 非常有意思的一个页面加载条js----PACEJS
- Javascript 验证Validator.js 使用全解(转载)
- javascript:让表单 文本框 只读,不可编辑的方法
- Extjs4之 formpanel使用
- 全面理解面向对象的 JavaScript
- bower解决js的依赖管理
- JavaScript 运行机制详解:Event Loop
- ExtJs自学教程(1):从一切API开始
- js小积累
- 浅析js绑定同一个事件依次触发问题系列(一)
- JavaScript探秘:强大的原型和原型链