用 JavaScript 的 push、pop、unshift 和 shift 增删数组元素

用 push() 向 JavaScript 数组末尾添加,用 unshift() 向开头添加。用 pop() 取出末尾值,用 shift() 取出开头值。四种方法都会修改数组本身。添加方法返回新长度,删除方法返回取出的值。

比较操作位置和返回值

方法 对原数组的改动 返回值
push(value) 添加到末尾 新数组长度
unshift(value) 添加到开头 新数组长度
pop() 删除末尾元素 取出的值 / undefined
shift() 删除开头元素 取出的值 / undefined

在 const n = items.push('four') 中,n 是表示长度的数字。需要带有新增值的新数组时可以用展开语法。items.slice(1) 复制除首项之外的元素,items.slice(0, -1) 复制除末项之外的元素。

用 push() 和 unshift() 添加元素

在控制台运行下面的代码。push('red') 在末尾添加并返回 3。一次调用 unshift('black', 'white') 会按该顺序添加到开头并返回 5。分两次先添加 black、再添加 white,则 white 排在最前。参见 push() 和 unshift()。

const colors = ['blue', 'green'];
const afterPush = colors.push('red');
console.log(colors);    // ['blue', 'green', 'red']
console.log(afterPush); // 3

const afterUnshift = colors.unshift('black', 'white');
console.log(colors);
// ['black', 'white', 'blue', 'green', 'red']
console.log(afterUnshift); // 5

const separate = ['blue'];
separate.unshift('black');
separate.unshift('white');
console.log(separate); // ['white', 'black', 'blue']

用 pop() 和 shift() 取出元素

pop() 取出末尾值,shift() 取出开头值。对空数组调用时,两者都返回 undefined,长度仍为 0。要判断操作前是否为空,请在调用前检查 length。从 [undefined] 取出元素也返回 undefined,但实际删除了一个元素。参见 pop() 和 shift()。

const colors = ['blue', 'green', 'red'];
console.log(colors.pop());   // 'red'
console.log(colors);         // ['blue', 'green']
console.log(colors.shift()); // 'blue'
console.log(colors);         // ['green']

const empty = [];
console.log(empty.pop());   // undefined
console.log(empty.shift()); // undefined

const stored = [undefined];
console.log(stored.length); // 1
console.log(stored.pop());  // undefined
console.log(stored.length); // 0

完整示例:在同一个数组上试验四种操作

将 HTML 以 UTF-8 保存为 array-ends.html,然后用浏览器打开。每个按钮都会显示返回值、当前数组和长度。字符串用引号标出,便于与数字区分。「重置」会恢复输入框和数组。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>修改数组两端</title>
</head>
<body>
<label for="value">要添加的值</label>
<input id="value" type="text" value="four">
<button id="push" type="button">push:添加到末尾</button>
<button id="unshift" type="button">unshift:添加到开头</button>
<button id="pop" type="button">pop:从末尾取出</button>
<button id="shift" type="button">shift:从开头取出</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const original = ['one', 'two', 'three'];
let items = original.slice();
const value = document.querySelector('#value');
const output = document.querySelector('#output');

function show(label, returned, didRun = true) {
  const rendered = didRun ? (JSON.stringify(returned) ?? 'undefined') : '—';
  output.textContent = `返回值 (${label}): ${rendered}\n` +
    `当前数组: ${JSON.stringify(items)}\n长度: ${items.length}`;
}

function add(method) {
  const text = value.value.trim();
  if (text === '') {
    output.textContent = "请输入要添加的值。";
    return;
  }
  const returned = method === 'push' ? items.push(text) : items.unshift(text);
  show(`${method}()`, returned);
  value.value = '';
}

document.querySelector('#push').addEventListener('click', () => add('push'));
document.querySelector('#unshift').addEventListener('click', () => add('unshift'));
document.querySelector('#pop').addEventListener('click', () => show('pop()', items.pop()));
document.querySelector('#shift').addEventListener('click', () => show('shift()', items.shift()));
document.querySelector('#reset').addEventListener('click', () => {
  items = original.slice();
  value.value = 'four';
  show("初始状态", undefined, false);
});
show("初始状态", undefined, false);
</script>
</body>
</html>

将初始输入 four 添加到末尾,返回数字 4。紧接着从末尾取出,返回字符串 "four",长度回到 3。也可以在开头做同样的比较。取完所有元素后再试一次,会看到 undefined 和长度 0。

组合方法来实现栈或队列

push() 和 pop() 在同一端操作,构成后进先出的栈。用 push() 在末尾加入、用 shift() 从开头取出,构成先进先出的队列。按相同顺序加入两个值,再比较取出顺序。

const stack = [];
stack.push('A', 'B');
console.log(stack.pop()); // 'B'
console.log(stack.pop()); // 'A'

const queue = [];
queue.push('A', 'B');
console.log(queue.shift()); // 'A'
console.log(queue.shift()); // 'B'

撤销最近的一项适合用栈,按到达顺序处理适合用队列。长数组反复删除首项可能带来开销,因为后续元素的索引需要移动。如果性能重要,请用接近实际的数据测量,并考虑单独记录队首位置的队列。