[英]TypeError: Cannot read property 'length' of undefined react
我正在 React 中做一个简单的练习。 练习的目标是简单地:
运行此代码时,我遇到了以下错误。 出于某种原因,“长度”似乎是问题所在。
TypeError: Cannot read property 'length' of undefined
Module../src/index.js
C:/Users/jaina/Desktop/ReactAPPS/exercise1/exercise-one/src/index.js:15
12 | // Remove the fruit from the array of fruits
13 | let remaining = remove(foods, fruit);
14 | // Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.”
> 15 | console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
16 |
它还说__webpack_require__
以及其他 webpack 警告。 但我假设不运行的主要原因是“长度”未定义。
索引.js
import foods from './foods';
import { choice, remove } from './helpers';
// Randomly draw a fruit from the array
let fruit = choice(foods);
// Log the message “I’d like one RANDOMFRUIT, please.”
console.log(`I’d like one ${fruit}, please.`);
// Log the message “Here you go: RANDOMFRUIT”
console.log(`Here you go: ${fruit}`);
// Log the message “Delicious! May I have another?”
console.log('Delicious! May I have another?');
// Remove the fruit from the array of fruits
let remaining = remove(foods, fruit);
// Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.”
console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
食品.js
const foods = [
"🍇", "🍈", "🍉", "🍊", "🍋", "🍌", "🍍", "🍎",
"🍏", "🍐", "🍒", "🍓", "🥝", "🍅", "🥑",
];
export default foods;
助手.js
function choice(items){
let idx = Math.floor(Math.random()* items.length);
}
function remove(items, item){
for (let i = 0; i < items.length; i++){
if(items[i] === item){
return [ ...items.slice(0,i), ...items.slice(i+1)];
}
}
}
export {choice, remove};
任何帮助表示赞赏。
在helper.js
中,如果您的 function remove
没有找到任何内容,它将返回未定义。 然后,当你说...
console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
...你假设remaining
是一个数组,但它实际上是未定义的。
尝试放置return items;
在remove
function 的末尾,在 for 循环之后。
在上面的代码中,如果在remove
function 中找不到任何内容,则返回items
。
function remove(items, item){
for (let i = 0; i < items.length; i++){
if(items[i] === item){
return [ ...items.slice(0,i), ...items.slice(i+1)];
}
}
// change this to whatever you want in case it was able to find item to remove
return items;
}
您的问题似乎出在这里:
function choice(items){
let idx = Math.floor(Math.random()* items.length);
}
所以let fruit = choice(foods)
, fruit 永远是未定义的。
尝试像这样返回助手 function 的值:
function choice(items){
let fruitIndex = Math.floor(Math.random()* items.length);
return items[fruitIndex];
}
您还应该找到选择的索引并返回水果,否则choice
将只返回一个数字。
修改您的选择并删除 function
function choice(items) {
return Math.floor(Math.random()*items.length);
}
function remove(items, item) {
return items.filter(e => e !== item);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.