《JS高级程序设计》笔记 —— 解析查询字符串

今天在继续翻阅《JS高级程序设计》的时候,正好翻到location对象这一小节,其中有一部分就是讲的解析查询字符串。看到这个内容立马想到了做去哪儿秋招笔试题的时候有这么一道题。
去哪儿笔试没有过自己还是一直都挺心塞的,可能当时也写得不好吧,现在看到这个内容赶紧记下来。

函数的功能就是为了能逐个访问每个查询字符串参数,返回一个包含所有参数的对象。

 

function getQueryStringArgs(){

    //利用location.search属性先提取出URL中的查询字符串,这个字符串包含“?”开头,所以返回时要去掉第一个字符
    var qs = (location.search.length>0 ? location.search.substring(1) : "") 

    var args = {}  //保存数据的对象

    var items = qs.length ? qs.split("&") : []  //拆分每个字符串参数

    var item = null,
        name = null,
        value = null

    var len = items.length

    for(var i=0;i<len;i++){
        //遍历,逐个将每一项添加到args对象中
        item = items[i].split("=")
        name = decodeURIComponent(item[0])
        value = decodeURIComponent(item[1])

        if(name.length){
            args[name] = value
        }
    }

    return args
}

  

 

  

 

posted @ 2016-10-02 16:03  scoop_zm  阅读(263)  评论(0编辑  收藏  举报