admin管理员组

文章数量:1341873

I need to make URLs like example?want[]=1,2,3&want[]=1,2,3&want[]=1,2,3

let params = new URLSearchParams();

for(let i in searchArr) {
    params.append('want[]', `${searchArr[i].id},${searchArr[i].quality},${searchArr[i].level}`);
}

console.log(params);

I've verified the given values exists, but it's always showing URLSearchParams {} with no values in console.

Why is it empty?

I need to make URLs like example.?want[]=1,2,3&want[]=1,2,3&want[]=1,2,3

let params = new URLSearchParams();

for(let i in searchArr) {
    params.append('want[]', `${searchArr[i].id},${searchArr[i].quality},${searchArr[i].level}`);
}

console.log(params);

I've verified the given values exists, but it's always showing URLSearchParams {} with no values in console.

Why is it empty?

Share asked Aug 12, 2019 at 19:27 user2722718user2722718 1731 gold badge2 silver badges13 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 8

URLSearchParams is an object. You need to cast it to a String using toString(), like so:

var params = new URLSearchParams();
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');

console.log(params.toString());

(Note: This will URL-encode characters like "[", "]", and ",")

You can access values by using any of these methods available on URLSearchParams

  • getAll() -> For a specific search parameter
  • .entries() -> For all key/value pairs
  • .values() -> For all the values

var params = new URLSearchParams();
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');

console.log(params.getAll('want[]'));
console.log([...params.entries()]);
console.log([...params.values()]);

本文标签: javascriptURLSearchParams always returning emptyStack Overflow