JavaScript - Array entries() 方法



在 JavaScript 中,Array.entries() 方法创建一个新的数组迭代器对象,该对象返回指定数组中每个索引的键值对。其中,每个键值对表示一个索引/值对。键是数组中元素的“索引”,值是相应的数组元素。

此方法不会更改或修改原始数组;而是返回一个包含键值对的数组迭代器对象。

语法

以下是 JavaScript Array entries() 方法的语法:

array.entries();

参数

此方法不接受任何参数。

返回值

一个新的数组迭代器对象,其中包含数组中每个索引的键/值对。

示例

示例 1

在以下示例中,我们使用 entries() 方法迭代数组“animals”中的每个元素,并将索引和值作为键/值对打印。

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];

      for (const i of animals.entries()) {
         document.write(i + "<br>");
      }
   </script>
</body>
</html>

输出

正如我们在输出中看到的,数组元素被打印为键/值对。

0,Lion
1,Cheetah
2,Tiger
3,Elephant
4,Dinosaur

示例 2

在这里,我们迭代指定数组中的每个元素,解构键(索引)和值(动物),并以格式化字符串打印它们。

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];

      for (const [index, animal] of animals.entries()) {
         document.write(`Index: ${index}, Name: ${animal}<br>`);
      }
   </script>
</body>
</html>

输出

正如我们在输出中看到的,数组元素被打印为键(索引)和值(动物)对。

Index: 0, Name: Lion
Index: 1, Name: Cheetah
Index: 2, Name: Tiger
Index: 3, Name: Elephant
Index: 4, Name: Dinosaur
广告

© . All rights reserved.