实现说明
各个操作都建立在顶层绑定之上: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);