TypeError:无法读取未定义反应的属性“长度”
2020-04-14
261
我正在 React 中做一个简单的练习。练习的目标很简单:
- 从数组中随机抽取水果
- 记录消息“我想要一个 RANDOMFRUIT,谢谢。”
- 记录消息“给你:RANDOMFRUIT”
- 记录消息“太好吃了!我可以再来一个吗?”
- 从水果数组中移除水果
- 记录消息“很抱歉,我们全部用完了。我们只剩下 FRUITSLEFT。
在运行此代码时,我遇到了以下错误。出于某种原因,“长度”似乎是问题所在。
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};
如能得到任何帮助,我们将不胜感激。
3个回答
在
helper.js
中,如果您的函数
remove
未找到任何内容,它将返回未定义。然后,当您说...
console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
...您假设
remaining
是一个数组,但它实际上是未定义的。
尝试将
return items;
放在
remove
函数的末尾,在 for 循环之后。
Jack Robinson
2020-04-14
在上面的代码中,如果在
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;
}
Mukund Goel
2020-04-14
修改您的选择并删除功能
function choice(items) {
return Math.floor(Math.random()*items.length);
}
function remove(items, item) {
return items.filter(e => e !== item);
};
Shantanu
2020-04-14