javascript 带有索引、键和值的地图上的每个 jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15327641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:23:09  来源:igfitidea点击:

jquery for each on a map with index, key and value

javascriptjqueryarrayshashmap

提问by by0

If I have data which looks something like this:

如果我有看起来像这样的数据:

x = {"key1":"val1", "key2":"val2", "key3", "val3"};

Is there any standard way to do a for each over them with a function that returns the key, value and index?

是否有任何标准方法可以使用返回键、值和索引的函数为每个对象做一个?

The way I would do it is define an array of keys and use the index to access it, but is there a simpler way?

我这样做的方法是定义一个键数组并使用索引来访问它,但有没有更简单的方法?

something like:

就像是:

$.each(x, function(i, k, v) {
    //... do something here
}

回答by jAndy

Object.keys()linkalong with Array.prototype.forEachlink:

Object.keys()链接Array.prototype.forEach链接

Synopsis

概要

Object.keys( object ).forEach(function( element, index, array ) {
});

Object.keys()returns all own keys as Arrayand .forEach()loops over an array like shown above. Since we get an Arrayfrom Object.keys(), we can of course also apply Array.prototype.sort()on it, and access the keys in any order we like. For instance

Object.keys()将所有自己的键作为Array返回并.forEach()循环遍历一个数组,如上所示。由于我们从获得了一个数组Object.keys(),我们当然也可以对其进行应用Array.prototype.sort(),并以我们喜欢的任何顺序访问键。例如

Object.keys( object ).sort(function( a, b ) {
    return a.localeCompare( b );
}).forEach(function( element, index, array ) {
    console.log( object[ element ] );
});

回答by Dogoku

you can create your own "index" if you will

如果愿意,您可以创建自己的“索引”

var i =0;
$.each(...... {
    /* code */
    i++;
});