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

URLSearchParams() 接口是用来解析和处理 URL 参数的 API,目前最新的浏览器和 Node 都支持它。请用 class URLSearchParams {} 语法实现一个该接口的 polyfill,考虑到时间因素,答题者只需实现下面列举的要求即可 #556

Open
Rashomon511 opened this issue Aug 30, 2019 · 0 comments

Comments

@Rashomon511
Copy link
Owner

// 构造函数支持传入 URL 参数串
searchParams = new URLSearchParams("foo=1&bar=2") 

// 构造函数也支持传入一个包含参数键值对的对象
searchParams = new URLSearchParams({foo: "1", bar: "2"})

// 实例支持 get()、set()、has()、append() 四个方法
console.log(searchParams.get("foo")) // "1"
searchParams.set("foo", "10") 
console.log(searchParams.has("bar")) // true
searchParams.append("foo", "100") 

// 实例支持 toString() 方法
console.log(searchParams.toString()) // "foo=10&bar=2&foo=100"

// 实例支持 for-of 迭代
for(const [key, value] of searchParams) {
  console.log([key, value])
  // ["foo", "10"]
  // ["bar", "2"]
  // ["foo", "100"]
}
class URLSearchParams {
  #searchParams = []

  constructor(init) {
    if (typeof init === "string") {
      this.#searchParams = init.split("&").map(kv => kv.split("="))
    } else {
      this.#searchParams = Object.entries(init)
    }
  }

  get(key) {
    const param = this.#searchParams.find(param => param[0] === key)
    return param && param[1]
  }

  set(key, value) {
    const param = this.#searchParams.find(param => param[0] === key)

    if (param) {
      param[1] = value
    } else {
      this.#searchParams.push([key, value])
    }
  }

  has(key) {
    return this.#searchParams.some(param => param[0] === key)
  }

  append(key, value) {
    this.#searchParams.push([key, value])
  }

  toString() {
    return this.#searchParams.map(param => param.join("=")).join("&")
  }

  *[Symbol.iterator]() {
    yield* this.#searchParams
  }
} 
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