JS中JSON对象常用方法
JSON.parse('{ "name":"runoob", "alexa":10000, "site":"www.runoob.com" }',function(key,value){
console.log(key,value);
});
结果:
参数一:想要转成json对象的字符串,参数二遍历json对象的键和值。
var obj = { "name":"runoob", "alexa":10000, "site":"www.runoob.com"};
var myJSON = JSON.stringify(obj);
需要注意若字符串中含有函数那么转化为json对象后系统回删除对应的函数键和值。
URL参数获取
//方法一:利用字符串截取,循环遍历
function GetRequest(location) {
const url = location.search;
let theRequest = {};
if (url.indexOf("?") != -1) {
let str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
console.log(GetRequest(window.location).id);
//方法二:利用正则表达式,获取单个参数值
function getQueryString(keyName,location) {
const reg = new RegExp("(^|&)" + keyName + "=([^&]*)(&|$)", "i");
var data = location.href.indexOf('#') > -1 ? location.hash.split("?")[1].match(reg) : location.search.substr(1).match(reg);
return data!=null?unescape(data[2]):null;
}