简体   繁体   English

如何将数组中的随机元素添加到另一个空白数组?

[英]How to add a random element from an array to another blank array?

I want to create a simple restaurant menu by javascript .我想通过 javascript 创建一个简单的餐厅菜单。 First the menu will display 5 dishes (which stores in array "menu").首先菜单将显示 5 道菜(存储在数组“菜单”中)。 Then when I click the button "Order" , a random dish from the array "menu" will be display in the line "Orders" one by one as I keep clicking it.然后,当我单击“订购”按钮时,“菜单”阵列中的随机菜肴将在我不断单击时一一显示在“订购”行中。 To do this I generated random number from 0-4 and created 2nd blank array "Orders" and create DOM objects to write "Orders" array's element one by one in the HTML line.为此,我生成了 0-4 的随机数并创建了第二个空白数组“Orders”,并创建了 DOM 对象以在 HTML 行中一一写入“Orders”数组的元素。 Code is below代码如下

 const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"]; let show_menu = document.querySelector("#menu"); let show_orders = document.querySelector("#orders"); for (let i = 0; i <= menu.length; i++) { if (menu[i] != undefined) { show_menu.textContent += `     ${menu[i]}`; } } function chuumon() { let orders = []; let a = Math.floor(Math.random() * 5); document.querySelector("#num").textContent = a; orders.push(menu[a]); show_orders.textContent = orders[a]; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>restaurant order</title> </head> <body> <h4>Menu</h4> <span id="menu"></span> <hr> Orders: <span id="orders"></span><br> <span id="num"></span> <button onclick="chuumon()">Order</button> </body> </html>

The problem is when I hit the button "Order" in the line "Orders" it only shows the element[0] of array menu otherwise it didn't show anything.问题是当我点击“订单”行中的“订单”按钮时,它只显示数组menuelement[0] ,否则什么都不显示。

What's wrong with my push() method?我的push()方法有什么问题? ( orders.push(menu[a]) ) orders.push(menu[a])

Now I want to set up an event when click the button "Serve" the dish at first in Line "Orders" will be deleted one by one.现在我想设置一个事件,当单击“服务”按钮时,“订单”行中的第一个菜将被一一删除。 So I set up another function "Teikyo()" to use function_name.shift() methoad but struggling with access the "Order" Array values inside function "chuumon()" .Here is my code about these 2 functions.因此,我设置了另一个函数“Teikyo()”来使用function_name.shift()方法,但在访问函数“chuumon()”中的“Order”数组值时遇到了困难。这是我关于这两个函数的代码。 Can anyone suggest for me how to access into other function's property?谁能建议我如何访问其他函数的属性?

function chuumon() {
let a = Math.floor(Math.random() * 5);
show_orders.textContent = menu.join(",");
orders.push(menu[a]);
show_orders.textContent = orders;
last_order.textContent = orders[orders.length - 1]
   }
function teikyo()
  {
chuumon().orders.shift();
show_orders.textContent = orders;
  }

a is an index into menu . amenu的索引。 It won't be the correct index into orders , since this array will usually be shorter than menu .它不会是orders的正确索引,因为这个数组通常比menu短。 You should show menu[a] in show_orders , not orders[a] .您应该在show_orders显示menu[a] ,而不是orders[a]

orders should be declared and initialized outside the function. orders应该在函数外声明和初始化。 Otherwise you keep resetting it to an empty array, instead of collecting all the ordered items.否则,您将不断将其重置为空数组,而不是收集所有订购的项目。

 const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"]; let orders = []; let show_menu = document.querySelector("#menu"); let show_orders = document.querySelector("#orders"); for (let i = 0; i < menu.length; i++) { show_menu.textContent += `     ${menu[i]}`; } function chuumon() { let a = Math.floor(Math.random() * menu.length); document.querySelector("#num").textContent = a; orders.push(menu[a]); show_orders.textContent = menu[a]; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>restaurant order</title> </head> <body> <h4>Menu</h4> <span id="menu"></span> <hr> Orders: <span id="orders"></span><br> <span id="num"></span> <button onclick="chuumon()">Order</button> </body> </html>

That is nothing wrong with orders.push(menu[a]) it is pushing the array properlly, however, you actually don't need the orders.push(menu[a]) as you are initiating it everytime you call the function. orders.push(menu[a])没有错,它正确地推送数组,但是,您实际上不需要orders.push(menu[a])因为每次调用该函数时都会启动它。

You can simply do:你可以简单地做:

function chuumon() {
  let a = Math.floor(Math.random() * 5);
  document.querySelector("#num").textContent = a;
  show_orders.textContent = menu[a];
}

 const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"]; let show_menu = document.querySelector("#menu"); let show_orders = document.querySelector("#orders"); for (let i = 0; i <= menu.length; i++) { if (menu[i] != undefined) { show_menu.textContent += `     ${menu[i]}`; } } function chuumon() { let a = Math.floor(Math.random() * 5); document.querySelector("#num").textContent = a; show_orders.textContent = menu[a]; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>restaurant order</title> </head> <body> <h4>Menu</h4> <span id="menu"></span> <hr> Orders: <span id="orders"></span><br> <span id="num"></span> <button onclick="chuumon()">Order</button> </body> </html>

Or, if you want to push something on that array and keep track, you need to declare it outside your function.或者,如果您想在该数组上推送某些内容并进行跟踪,则需要在您的函数之外声明它。

 const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"]; let orders = []; let show_menu = document.querySelector("#menu"); let show_orders = document.querySelector("#orders"); let show_order = document.querySelector("#order"); for (let i = 0; i <= menu.length; i++) { if (menu[i] != undefined) { show_menu.textContent += `     ${menu[i]}`; } } function chuumon() { let a = Math.floor(Math.random() * 5); document.querySelector("#num").textContent = a; show_orders.textContent = menu[a]; orders.push(menu[a]); show_orders.textContent = orders; show_order.textContent = orders[orders.length - 1] }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>restaurant order</title> </head> <body> <h4>Menu</h4> <span id="menu"></span> <hr> Orders: <span id="orders"></span><br> <span id="num"></span> <hr> Last Order: <span id="order"></span><br> <button onclick="chuumon()">Order</button> </body> </html>

Problem: If it hasn't already been mentioned, your empty array orders is defined within the function.问题:如果尚未提及,则您的空数组orders是在函数中定义的。 When a function is finished, all values within said function are garbage collected (deleted from memory -- gone).当一个函数完成时,该函数中的所有值都会被垃圾收集(从内存中删除 - 消失了)。 Every click of the button runs a the function with an empty orders array every time.每次单击按钮都会运行一个带有空orders数组的函数。 The only text that'll show up is "steak" because you happen to get 0 of course, but what happens when the index is 3 (or anything other than 0)?:唯一会显示的文本是“steak”,因为您当然碰巧得到 0,但是当索引为 3(或除 0 以外的任何值)时会发生什么?:

orders = [];
menu[0] = 'steak';
orders.push('steak');
orders[0] = 'steak';
// Next click
orders = [];
menu[3] = 'salad';
orsers.push('salad');
orders[3] = ??????
// The length of orders is always 1 

Solution: Do not create a new array, it's pointless.解决方案:不要新建数组,没有意义。 The nature of the function is that of an event handler.该函数的性质是事件处理程序的性质。 It works with the array once every click and nothing else.每次点击它都会与数组一起工作,没有别的。

 const items = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"]; const menu = document.querySelector(".menu"); items.forEach(item => menu.insertAdjacentHTML('beforeEnd', `<li>${item}</li>`)); function orderItem(e) { let order = document.querySelector('.order'); let index = Math.floor(Math.random() * items.length); order.textContent = ` ${index+1}. ${items[index]}`; } document.querySelector('button').addEventListener('click', orderItem);
 .menu { display: flex; justify-content: space-between; margin: -10px 0 -6px 0; } b { font: 2ch/1 }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>restaurant order</title> </head> <body> <h4>Menu</h4> <ol class="menu"></ol> <hr> <button>Order</button><b> :</b>&nbsp; <output class='order'></output> </body> </html>

For my edit path about adding another event with button "Serve" to delete one by one the dish showed in "Orders" linne.对于我的编辑路径,使用按钮“服务”添加另一个事件以逐个删除“订单”中显示的菜。 Here is my relate code and I tested it successfully.If you want to access a DOM object property just add the .value after the name of object.这是我的相关代码,我测试成功。如果您想访问 DOM 对象属性,只需在对象名称后添加.value

function chuumon() {
 let a = Math.floor(Math.random() * 5);
 show_orders.textContent = menu.join(",");
 orders.push(menu[a]);
 show_orders.textContent = orders;
 last_order.textContent = orders[orders.length - 1];
    }

function teikyo(){
  orders.shift(show_orders.value);
  show_orders.textContent = orders;
  first_serve.textContent = orders.shift(show_orders.value);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM