簡體   English   中英

為什么我不能在同一個數組中推送索引?

[英]why i can't push index in the same array?

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()){
   if(typeof element === "object"){
    findLastElement(element)
  1. 我無法理解如何在同一個數組中推送索引

    let array = [] array.push(index) console.log(array) } } } console.log(findLastElement(array))
  2. 我的解決方案是 - 在第一次迭代時,我已經有了第一個索引,如何在控制台的同一個數組中推送第二個索引,只有這樣的索引 [1,2,2,3,2]

你試過下面的嗎? let arr = []; arr.push([1]); arr.push(2); arr.push([3]);

我認為要求的是這個。 如果我錯了,請糾正我。

給定的

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM