Skip to content

Instantly share code, notes, and snippets.

@lx7575000
Last active March 3, 2016 11:53
Show Gist options
  • Save lx7575000/f3785a90646f0caf302e to your computer and use it in GitHub Desktop.
Save lx7575000/f3785a90646f0caf302e to your computer and use it in GitHub Desktop.
学习location对象,对其中的search属性进行分离操作。应用ES6语法,对每一部都进行了详细解释。
function getQueryStringArgs(){
  //查询是否有query的参数,如果有就去掉其中的?后返回后续的具体内容 返回type=music&loc=ningbo
  let qs = location.search.length > 0 ? location.search.substring(1) ? '';
  //判断是否有query参数,将各个参数项分开为type=music和loc=ningbo两部分
  let items = qs.length ? qs.split("&") : [];
  let args = {};
  let name = null, value = null, item = null;
  for(let i = 0; i < items.length; i++){
    //分别将各个query项进行键值分离为type和music、loc和ningbo
    item = items[i].split('=');
    //应用了解构
    [name, value] = item;
    
    //保险起见再确认键值是否存在
    if(name.length > 0){
      args[name] = value;
    }
    return args;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment