我正在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警告。但是我假设不运行的主要原因是“长度”未定义。
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};
感谢您的帮助。
答案 0 :(得分:1)
在helper.js
中,如果函数remove
未找到任何内容,它将返回未定义。然后,当你说...
console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
...您假设remaining
是一个数组,但实际上是未定义的。
在for循环之后,尝试将return items;
放在remove
函数的末尾。
答案 1 :(得分:0)
在上面的代码中,如果在<a class="logo">
<img src="image2.jpg">
</a>
函数中找不到任何内容,请返回items
。
remove
答案 2 :(得分:0)
您的问题似乎在这里:
function choice(items){
let idx = Math.floor(Math.random()* items.length);
}
所以let fruit = choice(foods)
,水果将永远是不确定的。
尝试返回辅助函数的值,如下所示:
function choice(items){
let fruitIndex = Math.floor(Math.random()* items.length);
return items[fruitIndex];
}
您还应该找到选择的索引并返回结果,否则choice
将仅返回数字。
答案 3 :(得分:0)
修改您的选择并删除功能
@media only screen and (min-width: 600px) {
.logo{
content:url("image2.jpg");
}
}
@media only screen and (min-width: 768px) {
.logo{
content:url("image2.jpg");
}
}