如何通过转到每个元素来弹出多维数组

时间:2018-06-19 17:25:03

标签: javascript

我想pop一个元素一个一个地,我有这个array [[1,2],[3]]

我将首先pop,先进入数组元素1,然后进入2(因为2是我要通知的最后一个元素,或者记录说它是最后一个元素)

问题:如果要遇到的每个pop的最后一个元素,我想一一array一个array然后我要通知({{1} })

这是我尝试的代码:

console.log('last element')

3 个答案:

答案 0 :(得分:0)

如果要弹出数组内部的数组,请尝试:

var mulA = [[1,2],['a','b','c'],['s'],['g','h'],['rr','tt','mm'],[],['q']];

var poped = mulA.pop();

var intId = setInterval(function(){
   
   if(poped == undefined || poped.length < 1) {
      if(mulA.length < 1) {
         clearInterval(intId);
         console.log('finished');
         return;
      }
      poped =  mulA.pop();
      console.log('last element');
      return;
   }
   
  console.log(poped.pop());
  
  
  console.log('notify on pop of each array last element');

},1500);

答案 1 :(得分:0)

您可以检查内部数组和外部数组的长度并打印通知或结束间隔。

var mulA = [[1,2],['a','b','c'],['s'],['g','h'],['rr','tt','mm'],[],['q']],
    intId = setInterval(function(){
        if (!mulA.length) {
            clearInterval(intId);
            return;
        }
        console.log(mulA[0].shift());
        if (!mulA[0].length) {
            while (mulA[0] && !mulA[0].length) mulA.shift();
            console.log('notify on pop of each array last element');
        }
    }, 500);

答案 2 :(得分:0)

首先打印内部数组,当它的长度等于该数组的最后一个元素的长度为1时,并且当内部数组的长度仅比从外部数组弹出时的长度为1时。

尝试以下操作:

var mulA = [[1,2],['a','b','c'],['s'],['g','h'],['rr','tt','mm'],[],['q']];


var poped = mulA.pop();
var intId = setInterval(function(){
   if(poped.length){
      if(poped.length == 1){
        console.log(poped.pop());
        console.log('notify on pop of each array last element');
        if(!mulA.length){
          clearInterval(intId);
          return;
        }
      }else{
          console.log(poped.pop());     
      }       
   } else {
      poped = mulA.pop();

   }

},150);