Как циклы while (true) влияют на функции? - PullRequest
0 голосов
/ 09 марта 2020

Я пытаюсь создать систему управления запасами для назначения, и мне трудно понять, как это Хотя (true) l oop не «блокирует» остальную часть моего кода в функции.

Для назначения все должно отображаться в консоли.

Проблема в основном (); функция. Когда я запускаю код, подсказки появляются, как и ожидалось, но при вводе входных данных ничего не отображается в консоли, пока я не введу «выход» в подсказку, когда считается, что l oop должен прерваться.

Спасибо за любую помощь.

Ниже приведен код для присвоения,

function displayMenu() {
        window.console.log("The Inventory Management App");
        window.console.log("");
        window.console.log("COMMAND MENU");
        window.console.log("view - View all products");
        window.console.log("update - Update Products");
        window.console.log("del - Delete employee");
        window.console.log("exit - Exit the application");
}

function view(chingaderas){ 
    "use strict";
    var i = 1;
    chingaderas.forEach(function (thing) {
        window.console.log(String(i) + ". " + thing);
        i += 1;
    });
    window.console.log("");
}
            
function update(chingaderas) { // need to find out how to update a specific part of 2 dimensional array 
    "use strict";
var sku = window.prompt("Enter the SKU# of the item you would like to update");
var changeMade = false;
for (var i = 0; i < chingaderas.length; i++) { 
    if (sku == chingaderas[i][0]) {
            var currentStock = window.prompt("How many " + chingaderas[i][1] + " are in stock?");
            changeMade = true;
            if (isNaN(currentStock)) {
                    window.alert("Invalid entry");
                    update(chingaderas);
            } else {
                    chingaderas[i][2] = parseInt(currentStock);
                    window.console.log("The new inventory of " + chingaderas[i][1] + "is now " + chingaderas[i][2]);
            }
    } else if (sku == null) {
            break
    }
}
if (changeMade == false & sku != null) {
        window.alert("Sku number not found")
        update(chingaderas);
}
}
var inventory = [
    [2233, "Hat",    12, "$14.99"],
    [3223, "Socks",  36, "$9.99"],
    [4824, "Shirt",  10, "$15.99"],
    [6343, "Jeans",  22, "$39.99"],
    [9382, "Jacket", 5,  "$49.99"],
];

var main = function () {
   window.console.log("say something")
    
    let command; 
    displayMenu();
    while (true) {
            command = window.prompt("What would you like to do? (view, update, exit)");
            if (command == "view") { // if to view inventory
                    view(inventory); 
            } else if (command == "update") { // to run the update function 
                    update(inventory); 
            } else if (command == "exit"){ // to exit the program 
                   break; 
            } 
            else {
                    window.document.write("invalid entry"); 
            }
    
            
    }
    window.console.log("Program has ended"); 
}
main(); 

1 Ответ

0 голосов
/ 09 марта 2020

Вам нужно дать браузеру время для отображения новой информации. И prompt, и while(true) block - они не позволяют текущей вкладке делать что-либо до тех пор, пока prompt не будет завершено и l oop не завершится полностью.

Вы можете main рекурсивно вызывать себя после setTimeout, чтобы у вещей была возможность визуализировать:

var main = function() {
  window.console.log("say something")
  let command;
  displayMenu();
  command = window.prompt("What would you like to do? (view, update, exit)");
  if (command == "view") { // if to view inventory
    view(inventory);
  } else if (command == "update") { // to run the update function 
    update(inventory);
  } else if (command == "exit") { // to exit the program 
    window.console.log("Program has ended");
    return;
  } else {
    window.document.write("invalid entry");
  }
  setTimeout(main);
}

function displayMenu() {
  window.console.log("The Inventory Management App");
  window.console.log("");
  window.console.log("COMMAND MENU");
  window.console.log("view - View all products");
  window.console.log("update - Update Products");
  window.console.log("del - Delete employee");
  window.console.log("exit - Exit the application");
}


function view(chingaderas) {
  "use strict";
  var i = 1;
  chingaderas.forEach(function(thing) {
    window.console.log(String(i) + ". " + thing);
    i += 1;
  });
  window.console.log("");
}


function update(chingaderas) { // need to find out how to update a specific part of 2 dimensional array 
  "use strict";
  var sku = window.prompt("Enter the SKU# of the item you would like to update");
  var changeMade = false;
  for (var i = 0; i < chingaderas.length; i++) {
    if (sku == chingaderas[i][0]) {
      var currentStock = window.prompt("How many " + chingaderas[i][1] + " are in stock?");
      changeMade = true;
      if (isNaN(currentStock)) {
        window.alert("Invalid entry");
        update(chingaderas);
      } else {
        chingaderas[i][2] = parseInt(currentStock);
        window.console.log("The new inventory of " + chingaderas[i][1] + "is now " + chingaderas[i][2]);
      }
    } else if (sku == null) {
      break
    }
  }
  if (changeMade == false & sku != null) {
    window.alert("Sku number not found")
    update(chingaderas);
  }
}

var inventory = [
  [2233, "Hat", 12, "$14.99"],
  [3223, "Socks", 36, "$9.99"],
  [4824, "Shirt", 10, "$15.99"],
  [6343, "Jeans", 22, "$39.99"],
  [9382, "Jacket", 5, "$49.99"],
];


var main = function() {
  window.console.log("say something")
  let command;
  displayMenu();
  command = window.prompt("What would you like to do? (view, update, exit)");
  if (command == "view") { // if to view inventory
    view(inventory);
  } else if (command == "update") { // to run the update function 
    update(inventory);
  } else if (command == "exit") { // to exit the program 
    window.console.log("Program has ended");
    return;
  } else {
    window.document.write("invalid entry");
  }
  setTimeout(main);
}

main();

Если это вообще возможно, было бы лучше избегать prompt полностью, так как это довольно неудобно для пользователя и предотвращает рендеринг и взаимодействие со страницей - рассмотрите возможность создания ввода вместо этого поле и кнопка на странице.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...