← 中文资源

简体中文版本

push 返回长度,shift 返回元素

push 与 unshift 返回新的长度,pop、shift、splice 返回被移除的元素:数组可变方法返回值各不相同,误当数组返回值链式调用会踩坑。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

push returns: 1
push returns: 3
pop returns: c
shift returns: a
unshift returns: 3
final array: [ 'x', 'y', 'b' ]
splice returns: [ 2, 3 ] left: [ 1, 4 ]

实现说明

各个操作都建立在顶层绑定之上:stack、nums。

使用要点

  • 演示输出是带标签的(push returns:、pop returns:、shift returns:),每个操作都会留下自己的一行标注。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 跨调用保留的状态放在这些顶层绑定里:stack、nums。

核心语句

const nums = [1, 2, 3, 4];
const stack = [];

代码示例

const stack = [];

// push returns the NEW length, not the array
console.log('push returns:', stack.push('a'));
console.log('push returns:', stack.push('b', 'c'));

// pop returns the removed element (undefined when empty)
console.log('pop returns:', stack.pop());

// shift returns the first element; unshift returns the new length
console.log('shift returns:', stack.shift());
console.log('unshift returns:', stack.unshift('x', 'y'));

console.log('final array:', stack);

// splice returns the removed elements as a new array
const nums = [1, 2, 3, 4];
console.log('splice returns:', nums.splice(1, 2), 'left:', nums);