【问题标题】:How can i get all index of array如何获取数组的所有索引
【发布时间】:2019-05-11 05:11:31
【问题描述】:

如何获取数组的所有索引,

[  
   {  
      "name":"aloha",
      "age":"18"
   },
   {  
      "name":"hello word"
   },
   {  
      "name":"John Doe",
      "age":"28"
   }
]

输出应该类似于 [0,1,2]

【问题讨论】:

  • 请参考这个 AlexC stackoverflow.com/help/how-to-ask。在提问之前考虑尝试一下。
  • 每个数组索引从零开始,到比数组长度小一的数字结束。你想问什么,好好问

标签: javascript arrays node.js


【解决方案1】:

最简单的方法是(见this post):

let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = Array.from(a.keys())
console.log(b)

天真的解决方案是在你的数组上调用map((_, i) => i))

let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = a.map((_, i) => i)
console.log(b)

【讨论】:

    【解决方案2】:

    您也可以使用 Object.keys 来检查任何对象的键索引。

    let a = [
            {
            'name' : "aloha",
            "age": "18"
            },
            {
            "name": "hello word"
            },
            {
            "name": "John Doe",
            "age" : "28"
        }]
        
    console.log(Object.keys(a));

    【讨论】:

      【解决方案3】:

      你可以使用 forEach 循环,就像这个例子:

      //The array you want to get all the indexes from
      const array = [{'a':1}, {'b':2}, {'c':3}];
      //All indexes array
      const indexArray = [];
      
      array.forEach((el, i) => {
          indexArray.push(i);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-13
        • 2018-12-09
        • 1970-01-01
        • 2017-06-03
        • 2021-03-17
        • 2012-09-15
        • 2017-09-22
        • 2016-10-11
        相关资源
        最近更新 更多