无法使用 JavaScript 中的 for 循环将一个堆栈的所有元素推送到另一个堆栈中?
javascriptweb developmentobject oriented programming更新于 2025/11/18 15:08:17
众所周知,堆栈遵循后进先出的原则。首先,要插入另一个堆栈,您需要从第一个堆栈中弹出所有元素并将其推送到第二个堆栈中。
示例
var myFirstStack=[10,20,30,40,50,60,70];
var mySecondStack=[];
for(;myFirstStack.length;){
mySecondStack.push(myFirstStack.pop());
}
console.log("After popping the all elements from the first stack=");
console.log(myFirstStack);
console.log("After pushing (inserting) all the elements into the second
stack=");
console.log(mySecondStack);
要运行上述程序,您需要使用以下命令 −
node fileName.js.
这里,文件名是 demo189.js。
输出
这将产生以下输出 −
PS C:\Users\Amit\javascript-code> node demo189.js After popping the all elements from the first stack= [] After pushing (inserting) all the elements into the second stack= [ 70, 60, 50, 40, 30, 20, 10 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

