Computer >> Máy Tính >  >> Lập trình >> Javascript

Không thể đẩy tất cả các phần tử của một ngăn xếp vào một ngăn xếp khác bằng vòng lặp for trong JavaScript?

Như chúng ta đã biết ngăn xếp hoạt động theo nguyên tắc Cuối cùng ra trước. Đầu tiên, để chèn vào anotherstack, bạn cần bật () tất cả các phần tử từ ngăn xếp đầu tiên và đẩy vào ngăn xếp thứ hai.

Ví dụ

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);

Để chạy chương trình trên, bạn cần sử dụng lệnh sau -

node fileName.js.

Đây, tên tệp của tôi là demo189.js.

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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
]