javascript编程代码笔记

1. 快速排序算法

  1. 方法一
function quicksort(n,left,right){
  var p;
  if(left<right){
    p = position(n,left,right);
    quicksort(n,left,p-1);
    quicksort(n,p+1,right);
  }
}

function position(n,left,right){
  var temp = n[left];
  while(left<right){
    while(left<right&&n[right]>temp)
      right--;
    if(left<right)
      n[left++]=n[right];
    while(left<right&&n[left]<temp)
      left++;
    if(left<right)
      n[right--]=n[left];
  }
  n[left]=temp;
  return left;
}

var a =[50, 32, 11, 16, 32, 24, 99, 57, 100];
quicksort(a,0,a.length-1)
console.log(a);
  1. 方法二
function quickSort(arr,left,right){
  var p;
  if(left<right){
    p=position(arr,left,right);
    quicksort(arr,left,p-1);
    quicksort(arr,p+1,right);
  }
  function position(arr,left,right){
    var temp=arr[left];
    while(left<right){
      while(left<right&&arr[right]>temp) right--;
      if(left<right) arr[left++]=arr[right];
      while(left<right&&arr[left]<temp) left++;
      if(left<right) arr[right--]=arr[left];
    }
    arr[left] =temp;
    return left;
  }
}

2. 深度克隆clone(继承)

var cloneObj = function(obj){
    var str, newobj = obj.constructor === Array ? [] : {};
    if(typeof obj !== 'object'){
        return;
    } else if(window.JSON){
        str = JSON.stringify(obj), //系列化对象
        newobj = JSON.parse(str); //还原
    } else {
        for(var i in obj){
            newobj[i] = typeof obj[i] === 'object' ? 
            cloneObj(obj[i]) : obj[i]; 
        }
    }
    return newobj;
};

//测试
var obj = {a: 0, b: 1, c: 2};
var arr = [0, 1, 2];
//执行深度克隆
var newobj = cloneObj(obj);
var newarr = cloneObj(arr);

//对克隆后的新对象进行成员删除
delete newobj.a;
newarr.splice(0,1);
console.log(obj, arr, newobj, newarr);
结果: {a: 0, b: 1, c: 2}, [0, 1, 2], {b: 1, c: 2}, [1, 2];
*/

3. 找出字符串或者数组中出现相同字符, 并且打印出次数最多的次数和字符

var str = "abcdefgaddda";  
var obj = {};  
for (var i = 0, l = str.length; i < l; i++) {  
  var key = str[i];  
  if (!obj[key]) {  
    obj[key] = 1;  
  } else {  
    obj[key]++;  
  }  
}  

var max = -1;  
var max_key = "";  
var key;  
for (key in obj) {  
  if (max < obj[key]) {  
    max = obj[key];  
    max_key = key;  
  }  
}  
alert("max:" + max + " max_key:" + max_key);

4. 解析url为json数据格式

function getUrl(url){
  //var arr=url.split('?')[1].split('&'); 
  var arr = [];
  var a3= [];
  arr = url.split("?");
  a1 = arr[1];
  a2 = a1.split("&");
  obj = {};
  for(var i=0;i<a2.length;i++){
    a3[i] = a2[i].split("=");
    obj[a3[i][0]] = a3[i][1];
  }
return obj;

}
var url= "URL:http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e";
//console.log(getUrl(url));



var getjson = function(url) {
  var a = [];
  var obj = {};
  var a = url.split('?')[1].split('&');
  for (var i = 0; i < a.length; i++) {
    var b[i] = a[i].split('=');
    obj[b[i][0]] = b[i][1];
  }
  return obj;
}

getjson(url);

5. 通用事件注册函数

var obj = document.getElementById("p");
var type = click;
function fun() {}

function addEvent(obj, type, fun) {
  if (obj.addEventListener) {
    obj.addEventListener(type, fun, false);
  } else if (obj.attachEvent) {
    obj.attachEvent("on" + type, fun);
  } else {
    obj["on" + type] = fun;
  }
}

6. 写一个获取url中参数的值的函数

function getRequest() {
  var url = window.location.search;
  var oRequest = new Object();
  if (url.indexOf('?') !== -1) {
    url = url.substr(1); // 取得?以后的字符串
    var reqArr = url.split('&');
    for (var i = 0; i < reqArr.length; i++) {
      oRequest[(reqArr[i].split('='))[0]] = unescape((reqArr[i].split('='))[1]);
    }
  }
  return oRequest;
}

7. JS中的数据类型? 如何断定一个变量是否是String类型

var str = new String("abcd");
console.log(typeof str); // object
console.log(str instanceof String);
console.log(str.constructor == String);
console.log(Object.prototype.toString.call(str) === "[object String]"); // true

var str1 = "abcd";

console.log(typeof str1); // string
console.log(Object.prototype.toString.call(str1) === "[object String]"); // true*/

8. 请实现, 鼠标点击页面中的任意标签, alert该标签的名称.( 注意兼容性)

document.onclick = function(e) {
  var e = e || window.event;
  var obj = e.target || e.srcElement;
  alert(obj.tagName.toLowerCase());
}

9. js异步加载的三种解决方案

(1) defer,只支持IE 
<script type="text/javascript" defer="defer"> 
alert(document.getElementById("p1").firstChild.nodeValue); 
</script> 
(2) async:
<script type="text/javascript" src="demo_async.js" async="async"></script> 
(3) 创建script,插入到DOM中,加载完毕后callBack,见代码:
function loadScript(url, callback){
    var script = document.createElement("script");
    script.type = "text/javascript";
    if(script.readyState){//IE
        script.onreadystatechange = function(){
            if(script.readyState == "loaded" ||
                script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    }else{//firefox,safari,chrome,opera
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.body.appendChild(script);
}

10. 二分搜索,从数组中找到findvalue

function binarySearch(arr,start,end,findvalue){
  var arr = arr.sort(function(a,b){return a-b});
  var mid=Math.floor((start+end)/2);
  var midvalue = arr[mid];
  if(midvalue==findvalue){
    return mid;
  }else if(findvalue<midvalue){
    binarySearch(arr,start,mid-1,findvalue);
  }else if(findvalue>midvalue){
    binarySearch(arr,mid+1,end,findvalue);
  }else{
    return -1;
  } 
}

11. javascript保留两位小数

num.toFixed(2);

function toDecimal(x) {    
  var f = parseFloat(x)
  if(isNaN(f)){
    return false;
  }
  var f = Math.round(x*100)/100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if(rs<0){
    rs=s.length;
    s+='.';
  }
  while(s.length<=rs+2){
    s+='0';
  }
  return s;          
}   

12. 编写一个方法 求一个字符串的字节长度;英文占一个, 中文占两个

方法一:
function getStrlen(str) {
  var len = str.length;
  var re = /[\u4e00-\u9fa5]/;
  for(var i=0;i<str.length;i++){
    if(re.test(str.charAt(i)))
      len++;
  }
  return len;
}
方法二:
function getStrlen(str){
  var len= str.length;
  for(var i=0;i<str.length;i++){
    if(str.charCodeAt(i)>255)
      len++;
  }
  return len;
}

13. 编写一个方法 去掉一个数组的重复元素

function delRepeat(arr){
  var a = [];
  for(var i=0,l=arr.length;i<l;i++){
    if(arr.indexOf(arr[i])==i){
      a.push(arr[i])
    }
  }
  return a;
}

14. JavaScript中如何检测一个变量是一个String类型? 请写出函数实现

typeof(obj) == 'string';
obj.constructor == String;
obj instanceof String;

15. 鼠标点击页面中的任意标签, alert该标签的名称.( 注意兼容性)

方法一: DOM0级事件
document.onclick = function(e){
  var e = e||window.event;
  var target = e.target || e.srcElement;
  console.log(target.tagName.toLowerCase());
}
方法二: DOM2级事件
事件代理
function callback(e) {
  var e = e || window.event;
  var target = e.target || e.srcElement;
  console.log(target.tagName);
}

if (document.addEventListener) {
  document.addEventListener('click', callback, false)
} else if (document.attachEvent) {
  document.attachEvent('onclick', callback)
} else {
  document['onclick'] = callback;
}

打赏此文

如果您觉得本站的内容对您有所帮助,您可以扫描下面的二维码小额支付请我喝杯茶,感谢!打赏记录
支付宝
微信
承诺:凡打赏捐助的朋友,留言备注自己的邮箱,在打赏捐助时间点的6个月内,本站会每周邮件推送原创专业技术博文,供大家学习和参考!

留下评论

All fields marked (*) are required