【问题标题】:why i can't push index in the same array? [closed]为什么我不能在同一个数组中推送索引? [关闭]
【发布时间】:2021-12-15 15:13:18
【问题描述】:
how can i push the index on one line like this->[1,2,2,3,2]
instead of this->[1][2][2][3][2]


 ``` let array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]];```

  function findLastElement (arr){
     for (let [index, element] of arr.entries()){
     let array = []
          if(typeof element === "object"){
          findLastElement(element)
              array.push(index)
             console.log(array)
             }
         }
     }    
   console.log(findLastElement(array))
  1. 我添加了这一行 let array = []

2.我需要将它推入数组 array.push(index)

2.在控制台中我应该只有这样的索引 [1,2,2,3,2],但现在我在不同的数组中都有索引 [1][2].....

  1. 我可以用这个例子吗?

【问题讨论】:

  • 对不起,我不明白。请edit 问题并尽可能清楚地解释:(1)您要实现的目标,(2)实际输入数据或源数据,(3)您获得的输出,以及(4)输出你想要的。该问题目前包含 3 个不同的数组,但我无法根据 (2)、(3) 和 (4) 判断哪个是哪个。
  • 在控制台中我应该只有这样的索引 [1,2,2,3,2],但现在我在不同的数组中都有索引 [1][2].....跨度>

标签: javascript arrays function recursion


【解决方案1】:

我认为要求的是这个。如果我错了,请纠正我。

给定

const array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]

我们可以得到这些指标:

array .length //=> 2 ~~> last index = 1
array [2 - 1] .length //=> 3 ~~> last index = 2
array [2 - 1] [3 - 1] .length //=> 3 ~~> last index = 2 
array [2 - 1] [3 - 1] [3 - 1] .length //=> 4 ~~> last index = 3
array [2 - 1] [3 - 1] [3 - 1] [4 - 1] .length //=> 3 ~~>  last index = 2
array [2 - 1] [3 - 1] [3 - 1] [4 - 1] [3 - 1] .length //=> 1 ~~> last index = 0
array [2 - 1] [3 - 1] [3 - 1] [4 - 1] [3 - 1] [1 - 1] // not an array, so we're done

所以我们想要的索引序列是[1, 2, 2, 3, 2, 0]。这似乎是正确的,但您最初的问题不包括最后的0,所以也许我遗漏了一些重要的东西。无论如何,这里有一个相当简单的递归:

const lastIndex = (x) =>
  Array .isArray (x) ? [x .length - 1, ... lastIndex (x [x .length - 1])] : []

const array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]

console .log (lastIndex (array))

【讨论】:

  • 大神,非常感谢!!!和解释是惊人的,,,,我终于明白了!我必须得到所有的索引,我不能以任何方式将它们推入一个数组,我可以在我的例子中使用这条路径吗?还是我应该改变我的方法?
【解决方案2】:

您是否尝试过以下操作? let arr = []; arr.push([1]); arr.push(2); arr.push([3]);

【讨论】:

  • 我需要动态添加索引,并且在控制台中已经应该有 [1,2,2,3,2]
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 2011-09-07
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多