这些pop()函数从数组中删除最后一个元素并返回弹出的元素。此函数将数组的长度减 1,除非数组为空。

const array = [1, 2, 3, 4, 5, 6];
array.pop(); // 6;
array; // 1, 2, 3, 4, 5

pop()undefined如果数组为空,则返回,例如shift(). 如果数组为空,pop()不修改数组的长度。

const array = [1, 2, 3, 4, 5, 6];

array.length; // 6
array.pop(); // 6;
array.length; // 5

const emptyArray = [];
emptyArray.pop(); // undefined
emptyArray.length; // 0

将数组用作堆栈
与 一起使用时shift(),pop()可以轻松地将数组用作堆栈。例如,以下是使用深度优先搜索而不使用递归遍历二叉树时如何将数组用作堆栈的方法。

const tree = {
  left: {
    left: 'A',
    right: 'B'
  },
  right: {
    left: 'C'
  }
};

function traverse(tree) {
  const stack = [tree];
  let cur = tree;

  while (stack.length > 0) {
    const el = stack.pop();
    if (typeof el !== 'object') {
      if (el != null) {
        console.log(el);
      }
      continue;
    }

    stack.push(el.right);
    stack.push(el.left);
  }
};

// Prints "A B C"
traverse(tree);

By lxcss

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注