类型错误:无法读取未定义反应的属性'length'



我正在React中做一个简单的练习。演习的目标是简单地:

  • 从阵列中随机抽取果实
  • 记录信息"我想要一个随机水果,请。">
  • 记录消息"给你:RANDOMFRUIT">
  • 记录信息"美味!我可以再来一杯吗?">
  • 从水果阵列中移除水果
  • 记录消息"对不起,我们都出去了。我们还剩水果。">

在运行此代码时,我遇到了以下错误。出于某种原因,"长度"似乎是个问题。

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警告。但我认为不跑步的主要原因是"长度"没有定义。

index.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.`);

Foods.js

const foods = [
"🍇", "🍈", "🍉", "🍊", "🍋", "🍌", "🍍", "🍎",
"🍏", "🍐", "🍒", "🍓", "🥝", "🍅", "🥑",
];
export default foods;

helper.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中,如果函数remove没有找到任何内容,它将返回undefined。然后,当你说。。。

console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);

您假设remaining是一个数组,但它实际上是未定义的。

尝试将return items;放在remove函数的末尾,在for循环之后。

在上面的代码中,如果在remove函数中找不到任何内容,则返回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) {
return Math.floor(Math.random()*items.length);
}
function remove(items, item) {
return items.filter(e => e !== item);
};

您的问题似乎就在这里:

function choice(items){
let idx = Math.floor(Math.random()* items.length);
}

所以let fruit = choice(foods),水果总是不确定的。

试着像这样返回helper函数的值:

function choice(items){
let fruitIndex = Math.floor(Math.random()* items.length);
return items[fruitIndex];
}

您还应该找到所选的索引并返回水果,否则choice将只返回一个数字。

最新更新