简体   繁体   English

为什么数组中的 object 返回未定义?

[英]Why does object in array return undefined?

My randomItem() function is returning veggies as undefined.我的randomItem() function 将veggies返回为未定义。 Any idea why?知道为什么吗?

 data = { bread: ["white", "italian 5 grain", "whole wheat"], cheese: ["cheddar", "muenster", "provolone", "swiss", "white american", "yellow america"], meat: ["oven roasted turkey", "oven roasted beef", "maple glazed ham", "black forest ham", "buffalo chicken breast", "bologna", "corned beef", "salsalito turkey", ], veggies: ["banana peppers", "black olives", "garlic pickles", "cucumbers", "dill pickles", "green peppers", "jalapeno peppers", "lettuce", "onions", "spinach", "tomato", "salt", "black pepper", "oregano", "oil and vinegar"], condiments: ["honey mustard", "spicy mustard", "mayo"], extras: ["avocado", "hummus", "guacamole", "bacon"], bake: ["pressed", "toasted"] } const getRandom = (min, max) => { return Math.floor((Math.random() * (max - min) + 1) + min); } function randomItem(item) { const random = getRandom(0, item.length - 1); console.log(data.item[random]); } randomItem(veggies);

EDIT: My code actually returned 'Reference Error, veggies is not defined'编辑:我的代码实际上返回了“参考错误,蔬菜未定义”

Problem 1: veggies is not a variable name so has to be passed as a string but if you were to access it from the data object it would be data.veggies问题 1: veggies不是变量名,因此必须作为字符串传递,但如果您要从data object 访问它,它将是data.veggies

Here's a fix:这是一个修复:

 data = { bread: ["white", "italian 5 grain", "whole wheat"], cheese: ["cheddar", "muenster", "provolone", "swiss", "white american", "yellow america"], meat: ["oven roasted turkey", "oven roasted beef", "maple glazed ham", "black forest ham", "buffalo chicken breast", "bologna", "corned beef", "salsalito turkey", ], veggies: ["banana peppers", "black olives", "garlic pickles", "cucumbers", "dill pickles", "green peppers", "jalapeno peppers", "lettuce", "onions", "spinach", "tomato", "salt", "black pepper", "oregano", "oil and vinegar"], condiments: ["honey mustard", "spicy mustard", "mayo"], extras: ["avocado", "hummus", "guacamole", "bacon"], bake: ["pressed", "toasted"] } var getRandom = (min, max) => { return Math.floor((Math.random() * (max - min) + 1) + min); } function randomItem(item) { const random = getRandom(0, item.length - 1); console.log(item[random]); //instead of logging data.item[random], just get the whole value from the argument } //This returns the values randomItem(Object.values(data.veggies));

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

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