简体   繁体   English

Javascript:按值获取索引

[英]Javascript: Get index by value

I have the following object:我有以下对象:

{1235: "2.03", 1234: "3.05", 1236: "3.05"}

How do I get the index given the key?如何获取给定键的索引?

Example: key = 1236 then index would be "2"示例:key = 1236 然后索引将为“2”

Objects are also called associative arrays.对象也称为关联数组。 Objects typically store a key value, while Arrays typically store just values so the term index does not make sense for objects while it does for for Arrays.对象通常存储键值,而数组通常只存储值,因此术语索引对于对象没有意义,而对于数组则有意义。 In objects you can iterate over keys or fetch values for a particular key.在对象中,您可以迭代键或获取特定键的值。 You might want to rethink the data structure for storing and fetching your data as you may run into browser specific issues (particularly on older browsers or mobile browsers)您可能需要重新考虑用于存储和获取数据的数据结构,因为您可能会遇到浏览器特定的问题(尤其是在旧浏览器或移动浏览器上)

you may want to read the difference associative array versus object in javascript and where to use them at understanding objects vs arrays您可能想阅读javascript 中关联数组与对象的区别以及在理解对象与数组时在哪里使用它们

you can pass also the index if you iterate trough the keys of the object.如果您遍历对象的键,您也可以传递索引。

var obj = {1235: "2.03", 1234: "3.05", 1236: "3.05"};

Object.keys(obj).forEach(function (prop, index) {
  console.log(prop + '_' + index);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM