当前位置:网站首页>Several efficient APIs commonly used in inventory operation URL
Several efficient APIs commonly used in inventory operation URL
2022-07-28 13:57:00 【Maic】
Usually in real projects , No matter what you do data 、 or dom, We need to be familiar with some browser Of API, or js Native gives us extended API, We are familiar with these API, In a sense , Some efficient API and Method It will often solve many difficult and miscellaneous problems encountered in your project .
This article is only about URL Commonly used API, I hope I can bring a little thought and help in your project .
Text begins ...
location object
Under the console ,window.location Get browser address URL Related information
// window.location
/*
https://www.baidu.com/s?wd=Reflect.%20defineProperty&rsv_spt=1#123
*/
const { href, origin, host, port, protocol,pathname, hash, search } = window.location;
console.log(href) // Get the entire URL xxx
console.log(origin); // agreement + domain name + port https://www.baidu.com
console.log(host); // Host name + Port number (http perhaps https The port number will be omitted ) www.baidu.com
console.log(port); // '' http Default port 80 https Default port 443
console.log(protocol); // agreement https:
console.log(pathname); // In addition to the routing address path of the domain name
console.log(hash); // Path belt # Parameters of
console.log(search); // Address ? All the following parameters
stay location.search、location.hash、location.origin、location.href It is usually a few high-frequency parameter methods to obtain the current address in the project , But note that only location.origin This is read-only , other API It's all readable and writable
URL
stay js Create an address in , Use scenarios , Take a chestnut , We use it URL Simulate the address of the current page
const url = new URL('https://www.baidu.com/s?wd=Reflect.%20defineProperty&rsv_spt=1#123');
console.log(url.search); // ?wd=Reflect.%20defineProperty&rsv_spt=1
console.log(url.hash); // #123
console.log(url.origin); // https://www.baidu.com
console.log(url.href);// 'https://www.baidu.com/s?wd=Reflect.%20defineProperty&rsv_spt=1#123'
URL The properties in the address of this native construct are the same as location Get the general properties on the address are basically the same . The only difference is ,location More replace And reload Method ,URL Besides having location The general properties of , No, replace And reload Method , But it has a way to get parameters searchParamsAPI
...
console.log(url.searchParams);
// { 'wd' => 'Reflect. defineProperty', 'rsv_spt' => '1' }
console.log(url.searchParams.toString());
// wd=Reflect.+defineProperty&rsv_spt=1
searchParams
Get... Quickly URL Method of carrying parameters in , This is in URL The built address is very convenient . For example, now there is a need , I need to convert the parameters of an address to key And value The key/value pair .
In the past, our practice was like this
function formateQueryUrl () {
const { search } = window.location;
// With ? Division , obtain url The real parameters on
const [, searchStr] = search.split('?');
// With & Parameters before and after segmentation
const arr = searchStr.split('&');
const ret = {};
arr.forEach(v => {
const [key, val] = v.split('=');
ret[key] = val
});
return ret;
}
Now we can make more efficient use of URL Of searchParams
// With the above formateQueryUrl Method equivalence
function eazyFormateQueryUrl() {
const url = new URL(window.location);
return Object.fromEntries(url.searchParams.entries())
}
// If the current browser address https://www.badu.com?a=1&b=2
// {a:1,b:2}
This eazyFormateQueryUrl Is the method simple , Two lines of code will do the formatting url Parameters in , And easily convert a string of string parameters into objects
Note that the above method we used Object.fromEntries And url.searchParams.entries(), Actually url.searchParams The constructor of URLSearchParams, and URLSearchParams It is a system with iterator Functional API, So you can for...of perhaps entries operation .
At the same time, we should pay attention to fromEntries, Let's take a look at this API, Usually we don't often use , Generally, we are entries Much more operation , But actually fromEntries Is to restore the object entries operation , Here we take advantage of this .
Take a chestnut
const ret = {name: 'Maic', public: 'Web Technology academy '};
const arr = Object.entries(ret);
console.log(arr)
// [['name', 'Maic'], ['public', 'Web Technology academy ']]
If you want to arr Restore to previous objects , Then you must think of the circular approach , Like this
...
const target = {};
arr.forEach(item => {
const [key, val] = item;
target[key] = val;
});
console.log(target);
// {name: 'Maic', public: 'Web Technology academy '}
In fact, there is no need to cycle , Native Object Provides a API, It can be entries Restore the data to the previous . Then we can simply implement
const ret = {name: 'Maic', public: 'Web Technology academy '};
const arr = Object.entries(ret);
/* const target = {};
arr.forEach(item => {
const [key, val] = item;
target[key] = val;
});
*/
// Equivalent to
const target = Object.fromEntries(arr)
// {name: 'Maic', public: 'Web Technology academy '}
Because of that , We used fromEntries That's the characteristic of , Skillfully transfer the original data to the object .
about URL, We also need to be able to dynamically add paths , Like a chestnut below
function locationByNamePath (path) {
const { origin } = window.location;
const url = new URL(path, origin);
window.location.href = url.href;
}
locationByNamePath('/index.html');
// https://www.baidu.com/index.html
locationByNamePath('/about.html');
// https://www.baidu.com/about.html
URLSearchParams
This API Is a native constructor , You can get the address ? The following parameter information
Take a chestnut
var urlSearch = new URLSearchParams(window.location.search);
console.log(`${urlSearch}`);
// Open the baidu , Enter a keyword to search on the console , The console copies the broken code , You can see that
URLSearchParams Incoming string
const search = new URLSearchParams('a=1&b=2&c=3');
console.log(search.toString()) // a=1&b=2&c=3
Equivalent to
const search = new URLSearchParams(window.location.search);
console.log(search.toString()) // a=1&b=2&c=3
URLSearchParams Pass in array , Convert an object to url Parameters , Usually in ajaxget When requesting splicing parameters , It could be useful
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
console.log(search2.toString());
//a=1&b=2&c=3
$.ajax({
url: `xxxx?${search2}`,
methods: 'get'
})
When we use fetch Native api When asked ,new URLSearchParams It can be used as body Parameters
const params = {
name: 'maic',
password: '123456'
}
fetch('https://baidu.com', {
methods: 'POST',
body: new URLSearchParams(params)
})
We know URLSearchParams Features that have iterator properties , So it's like Map、Set Same as Add or delete check change Characteristics of
check get Get parameter value
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
console.log(search2.get('a')); // 1
console.log(search2.get('b')); // 2
console.log(search2.get('c')); // 3
increase append, Add a parameter
...
search2.append('d', 'hello')
// a=1&b=2&c=3&d=hello
Delete delete Delete a parameter
...
search2.delete('a');
console.log(search2.toString());
//b=2&c=3
Change set Modify the parameters
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
search2.set('a', '666')
console.log(`${search2}`);
// a=666&b=2&c=3&d=hello
Whether there is has Judge whether there is key
...
console.log(search2.has('a')); // true
obtain URLSearchParams be-all key perhaps value
new URLSearchParams({a:1,b:2,c:3}).keys(),new URLSearchParams({a:1,b:2,c:3}).values()
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
const keys = Array.from(search2.keys());
console.log(keys);
// ['a', 'b', 'c']
const values = Array.from(search2.values());
// ['1', '2', '3']
about URLSearchParams It can be transmitted character string , It can be object or Array , When we get URLSearchParams Of key, Call directly xxx.keys() Or is it xxx.values(), But the value taken out in this way is an iterator , You need to use Array.from Transfer the .
Restore URLSearchParams Parameters
...
Object.fromEntries(search2.entries());
// {a:1,b:2,c:3}
summary
locationOften gethostname、origin、search、hashetc.URLestablish url, And havesearchParamsobtain url Medium?Later parameters- utilize
URLSearchParamsEfficient formattingurlParameters , Two lines of code realize the formatting?Parameters URLSearchParamsThisAPIYou can get it directly url Parameters , And provideAdd or delete check change[append、delete、get、set、has] Method
边栏推荐
- .net for subtraction, intersection and union of complex type sets
- leetcode-深度优先与广度优先遍历
- R language uses LM function to build linear regression model and subset function to specify subset of data set to build regression model (use floor function and length function to select the former pa
- C language: optimized merge sort
- word打字时后面的字会消失是什么原因?如何解决?
- Li Kou sword finger offer 51. reverse order pairs in the array
- 算法---不同路径(Kotlin)
- 第六章 支持向量机
- Operator3 - design an operator
- DOJNOIP201708奶酪题解
猜你喜欢

DXF reading and writing: align the calculation of the position of the dimension text in the middle and above

安全保障基于软件全生命周期-NetworkPolicy应用

记一次COOKIE的伪造登录

30 day question brushing plan (III)

How to check if the interface cannot be adjusted? I didn't expect that the old bird of the 10-year test was planted on this interview question

【飞控开发基础教程7】疯壳·开源编队无人机-SPI(气压计数据获取)
JWT login authentication + token automatic renewal scheme, well written!

30天刷题训练(一)

Record a fake login of cookie

Org.apache.ibatis.exceptions.toomanyresultsexception
随机推荐
Record a fake login of cookie
Li Kou sword finger offer 51. reverse order pairs in the array
R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
严格模式——let和const——箭头函数——解构赋值——字符串模板symbol——Set和Map——生成器函数
30 day question brushing plan (II)
C language: random number + quick sort
数据库系统原理与应用教程(062)—— MySQL 练习题:操作题 32-38(六)
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
Tutorial on the principle and application of database system (059) -- MySQL exercise questions: operation questions 1-10 (III)
30天刷题计划(二)
数据库系统原理与应用教程(059)—— MySQL 练习题:操作题 1-10(三)
了解BFC特性,轻松实现自适应布局
DXF读写:标注样式组码中文说明
数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题
Dojnoip201708 cheese solution
Debezium series: major changes and new features of 2.0.0.beta1
【LVGL事件(Events)】事件代码
R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间(设置conf.level参数指定置信水平、置信区间的大小)
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置palette参数自定义不同水平小提琴图的边框颜色
30 day question brushing plan (III)