Node 中的 URLSearchParams entries 和 forEach


entries() 簡介 −

此函式返回一個迭代器,允許我們迭代物件中存在的所有條目集合。它基本上為我們提供了一種迭代查詢物件的完整條目集合的工具。

語法

URLSearchParams.entries();

它將返回一個 ES6 型別迭代器,其中包含所有名稱-值對值。

示例

// Defining the parameters as a variable
var params = new URLSearchParams('key1=value1&key2=value2&key3=value3');

// Iterating over the values of params
for(var entry of params.entries()) {
   console.log(entry[0] + ' -> ' + entry[1]);
}

輸出

key1 -> value1
key2 -> value2
key3 -> value3

示例

// Defining the URL as a constant
const params = new URLSearchParams(
   'name=John&age=21');

// Iterating over the values of params
for(var entry of params.entries()) {
   console.log(entry[0] + ' -> ' + entry[1]);
}

輸出

name -> John
age -> 21

forEach(fn[,arg]) 簡介

forEach 下描述的 fn 將呼叫每個名稱-值對,這些對將遍歷此 forEach 迴圈,arg 是在呼叫“fn”時使用的物件。它將在查詢中的每個名稱-值對上被呼叫並呼叫函式。

語法

URLSearchParams.forEach();

它將返回一個 ES6 型別迭代器,其中包含所有鍵上的名稱-值對。

示例

// Defining the URL as a constant
const url = new URL(
   'https://example.com/name=John&age=21');

// Iterating over the values of params
url.searchParams.forEach(function(value,key) {
   console.log(value, key);
});

輸出

name John
age 21

示例

// Defining the parameters as a constant
const myURL = new URL(
   'https://example.com/key1=value1&key2=value2&key3=value3');

// Iterating over the values of params
myURL.searchParams.forEach(
   (value, name, searchParams) => {
      console.log(name, value,
      myURL.searchParams === searchParams);
});

輸出

key1 value1 true
key2 value2 true
key3 value3 true

更新日期:2021-04-28

391 次瀏覽

職業生涯起步

透過完成課程獲得認證

開始
廣告
© . All rights reserved.