JavaScript 中的 For..In 循环 - 键值对 [英] For..In loops in JavaScript - key value pairs

查看:22
本文介绍了JavaScript 中的 For..In 循环 - 键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法在 JavaScript 中执行类似 PHP foreach 循环的操作.我正在寻找的功能类似于这个 PHP Snippet:

I was wondering if there's a way to do something like a PHP foreach loop in JavaScript. The functionality I'm looking for is something like this PHP Snippet:

foreach($data as $key => $value) { }

我正在查看 JS for..in 循环,但似乎没有办法指定 as.如果我使用正常" for 循环 (for(var i = 0; i < data.length; i++) 执行此操作,有没有办法获取键 => 值对?

I was looking at the JS for..in loop, but there seems to be no way to specify the as. If I do this with a 'normal' for loop (for(var i = 0; i < data.length; i++), is there a way to grab the key => value pairs?

推荐答案

如果你可以在本地使用 ES6 或者使用 Babel(js 编译器),您可以执行以下操作:

If you can use ES6 natively or with Babel (js compiler) then you could do the following:

const test = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(test)) {
  console.log(key, value);
}

这将打印出这个输出:

a 1
b 2
c 3

Object.entries() 方法返回给定对象自己的可枚举属性 [key, value] 对的数组,其顺序与 afor...in 循环 (区别在于 for-in 循环也枚举原型链中的属性).

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

  • Object.entries documentation
  • for...of documentation
  • Destructuring assignment documentation
  • Enumerability and ownership of properties documentation

希望有帮助!=)

这篇关于JavaScript 中的 For..In 循环 - 键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆