javascript工具函數彙總2013

function int(str){
    return parseInt(str, 10);
}
/*
 * 判斷目標參數是否Array對象
 */
function isArray(source){
    return '[object Array]' == Object.prototype.toString.call(source);
}
/*
 * 解析目標URL中的參數成json對象
 */
function queryToJson(url){
     var getParams = url.substr(url.indexOf('?') + 1),
        item = getParams.split('&'),
        map = {},key,value,t;
    for(var i=0; i<item.length; i++){
        if(!item[i]){
            continue;
        }
        key = item[i].split('=')[0];
        value = item[i].split('=')[1];
        t = map[key];
        if('undefined' == typeof t){
            map[key] = value;
        }else if(isArray(t)){
            t.push(value);
        }else{
            map[key] = [t,value];
        }
    }
    console.log(map);
}

var url = "http://baidu.com?kwd=ade&action=suggest&kwd=op";
queryToJson(url);

/**
 * 將源對象的所有屬性拷貝到目標對象中
 * 源對象的prototype成員不會拷貝
 */
function extend(target,source){
    for(p in source){
		if(source.hasOwnProperty(p)){
			target[p] = source[p];
		}
	}
	return target;
}
var d = extend({a:1},{a:2,b:3});
console.log(d); //{a:2,b:3}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章