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

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

问题描述

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

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 循环,但似乎没有办法将指定为。如果我使用'normal'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?

推荐答案

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

hasOwnProperty 用于检查您的 target 确实有这个属性,而不是从它的原型继承它。稍微简单一点:

hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

它只检查 k 不是方法(好像目标数组你'会收到很多提醒的方法,例如 indexOf push pop 等。)

It just checks that k is not a method (as if target is array you'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)

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

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