简体   繁体   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. i can't understand how to push index in the same array我无法理解如何在同一个数组中推送索引

    let array = [] array.push(index) console.log(array) } } } console.log(findLastElement(array))
  2. my selution is- on first iteration i alredy have first index,how i can push the second one in the same array in console have only index like this [1,2,2,3,2]我的解决方案是 - 在第一次迭代时,我已经有了第一个索引,如何在控制台的同一个数组中推送第二个索引,只有这样的索引 [1,2,2,3,2]

Did you try the below?你试过下面的吗? let arr = []; arr.push([1]); arr.push(2); arr.push([3]);

I think what's asked for is this.我认为要求的是这个。 Please correct me if I'm wrong.如果我错了,请纠正我。

Given给定的

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

We can get these indices:我们可以得到这些指标:

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

And so the sequence of indices we want is [1, 2, 2, 3, 2, 0] .所以我们想要的索引序列是[1, 2, 2, 3, 2, 0] This seems correct, but you original question did not include that final 0 , so perhaps I'm missing something important.这似乎是正确的,但是您最初的问题没有包括最后的0 ,所以也许我错过了一些重要的东西。 In any case, here's a fairly simple recursion for that:无论如何,这是一个相当简单的递归:

 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