Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

解析查询字符串函数封装实现 #16

Open
shiiiiiiji opened this issue May 17, 2018 · 1 comment
Open

解析查询字符串函数封装实现 #16

shiiiiiiji opened this issue May 17, 2018 · 1 comment

Comments

@shiiiiiiji
Copy link
Owner

shiiiiiiji commented May 17, 2018

js高程(第三版)实现源码

function getQueryStringArgs(){
	// 取得查询字符串并去掉开头的问号
	var qs = (location.search.length > 0 ? location.search.substring(1) : ""),

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

		// 取得每一项
		items = qs.length ? qs.split("&") : [],
		item = null,
		name = null,
		value = null,

		// 在 for 循环中使用
		i = 0,
		len = items.length;

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

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

	return args;
}
@shiiiiiiji
Copy link
Owner Author

支付宝jsapi实现版本:

/**
 * 获取 url 上的全部传参并转成对象
 * @method parseQueryString
 * @param  {String}          queryString
 * @return {Object}          location.search 对应的键值对象
 */
parseQueryString: function parseQueryString(queryString) {
  var result = {};
  var searchStr = queryString || window.location.search;
  var bool = {
    true: true,
    false: false
  };
  var kv;
  searchStr = searchStr.indexOf('?') === 0 ? searchStr.substr(1) : searchStr;
  searchStr = searchStr ? searchStr.split('&') : '';
  for (var i = 0; i < searchStr.length; i++) {
    kv = searchStr[i].split('=');
    kv[1] = decodeURIComponent(kv[1]);
    //Boolean
    kv[1] = __isUndefined(bool[kv[1]]) ? kv[1] : bool[kv[1]];
    //Number
    //kv[1] = +kv[1] + '' === kv[1] ? +kv[1] : kv[1];
    result[kv[0]] = kv[1];
  }
  _apiRemoteLog('parseQueryString');
  return result;
}

@shiiiiiiji shiiiiiiji changed the title 解析查询字符串封装 解析查询字符串函数封装实现 May 17, 2018
@shiiiiiiji shiiiiiiji removed the CODE label Oct 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant