四道腾讯的javascript面试题
今天整理自己的文件夹时,发现了曾经面试腾讯实习生时的被问挂了的面试题,我将它们整理好了供大家借鉴。当时要求的是手写代码。汗啊,我那时弱爆了!
1,将给定数组转换为一个随机数组
1 Array.prototype.shuffle=function(){ 2 var resultArr=[]; 3 var len=this.length; 4 5 while(len){ 6 var _index=parseInt(Math.random()*len); 7 resultArr.push(this[_index]);//每次取得数组中一个字符,放到新的数组中 8 for(var i=_index;i<len;i++){//后面的向前移动 9 this[i]=this[i+1]; 10 } 11 len--; 12 } 13 return resultArr; 14 } 15 var a=new Array('1','2','3','4','5','6'); 16 alert(a.shuffle());
2,统计给定字符串里的各个字符出现的次数
1 var a="aassdddffffffffggghhhjjjkkkll"; 2 function counts(str){ 3 var obj={}; 4 for(var i=0;i<str.length;i++){ 5 if(!obj[str[i]]){ 6 obj[str[i]]=1; 7 }else{ 8 obj[str[i]]++; 9 } 10 11 } 12 return obj; 13 } 14 15 console.log(counts(a));//Object {a: 2, s: 2, d: 3, f: 8, g: 3…}
3,判断js代码加载完成
1 function dynamicLoad() 2 { 3 var _doc=document.getElementsByTagName('head')[0]; 4 var script=document.createElement('script'); 5 6 script.setAttribute('type','text/javascript'); 7 script.setAttribute('src','jquery.js'); 8 9 _doc.appendChild(script); 10 //非ie ie, 11 script.onload=script.onreadystatechange=function(){ 12 //非ie ie,该值不确定 13 if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){ 14 alert('done'); 15 script.onload=script.onreadystatechange=null; 16 } 17 } 18 }
4,实现三列布局:
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta charset="utf-8"/> 5 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 6 <style> 7 #side { background: #99FF99; height: 300px; width: 120px; float: left; } 8 #main { background: #99FFFF; height: 300px; width: auto; margin-left: 120px; } 9 #main-left{ background:red;float:left; width:200px; height:300px;} 10 #main-right{ margin-left:200px; height:300px; width:auto;} 11 </style> 12 </head> 13 <body> 14 <div id="side">此处为左边部分</div> 15 <div id="main"> 16 <div id="main-left">右边的左列</div> 17 <div id="main-right">右边的右列</div> 18 19 </div> 20 </body> 21 </html>
开心一刻: