繁体   English   中英

如何选择对象内的第n个项目

[英]How to select nth item inside the object

假设您无法通过像objectName.objectItem这样的点表示法访问对象内的某个项目,即它随时间具有随机名称。 有没有办法像第二项一样交替访问它?

如何从这个对象中获取item2,只知道它是第二个项目?:

something: {
  item1: "text",
  item2: "text",
  item3: "text:,
  ...
}

在javascript对象中不修复键的顺序。

你可以试试

var secondKey = Object.keys(something)[1]; //fetched the key at second index
alert(something[secondKey ]);

对象键没有顺序,但您可以定义自己的二进制关系来对键进行排序。

比如说,你只考虑以"item"开头的键和一个数字后缀如item23 ,然后你可以根据自己的定义将其转换为数字23并确定item23是数组中的第23个项目。

请注意,这是完全随意的,只有在目前为止,您希望它在您的代码中是如此。

也就是说,您可以实现一个过滤所有键的函数(仅考虑以"item"开头的那些键),将数字后缀解析为数字,然后将其与您想要的项目的索引进行比较。

这段代码正是我想你想做的事情:

function nth(obj, n)
{
  var key, i;

  for (key in obj)
  {
    if (obj.hasOwnProperty(key)) // always do this when you scan an object
    {
      if (key.indexOf("item") === 0) // this is the filter
      {
        i = parseInt(key.substring(4), 10); // parse the numeral after "item"
        if (i === n)
        {
          return obj[key]; // return this value
        }
      }
    }
  }

  return null;
}

暂无
暂无

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

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