For..In loops in javascript - key value pairs

来源:互联网 发布:网络教育报考条件 编辑:程序博客网 时间:2024/06/13 09:41

http://stackoverflow.com/questions/7241878/for-in-loops-in-javascript-key-value-pairs


1. for(var key in dict)

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

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]);    }}

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

2. Object.keys(dict).forEach(key, function(){})

Object.keys(obj).forEach(function (key) {   // do something with obj[key]});

0 0
原创粉丝点击