【发布时间】:2020-08-29 20:30:49
【问题描述】:
我正在尝试修复我的代码的错误 - 问题是由带有错误消息的类型错误引起的:
test.js:89 Uncaught TypeError: Cannot read property 'forEach' of undefined
at printResults (test.js:89)
at test.js:105
代码如下:
const phones = [{
name: "iPhone XS", brand: "Apple", cost: 43, data: "500MB", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "iPhone 11", brand: "Apple", cost: 64, data: "90GB", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "Galaxy S10", brand: "Samsung", cost: 30, data: "20GB", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "Galaxy S10", brand: "Samsung", cost: 65, data: "Unlimited", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "Galaxy A10", brand: "Samsung", cost: 11.99, data: "500MB", minutes: 250, texts: "Unlimited"
},
{
name: "Galaxy S9", brand: "Samsung", cost: 31, data: "20GB", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "StarTAC 130", brand: "Motorola", cost: 3, data: "0MB", minutes: 200, texts: 500
},
{
name: "Pixel 3A", brand: "Google", cost: 23, data: "4GB", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "Xperia 10", brand: "Sony", cost: 30, data: "20GB", minutes: "Unlimited", texts: "Unlimited"
},
{
name: "P30", brand: "Huawei", cost: 27.99, data: "500MB", minutes: 500, texts: "Unlimited"
}];
// Functions
function getUserPreferences() {
// These are asking the user for entry of the data into the system.
const userPrompt = [
{
phoneBrand: prompt("Enter a brand name")
},
{
phoneCost: prompt("Enter a monthly cost")
},
{
phoneData: prompt("Enter the amount of data")
},
{
phoneMins: prompt("How many minutes?")
},
{
phoneTexts: prompt("How many texts?")
},
]
}
function getMatchingPlans(phoneBrand, phoneCost, phoneData, phoneMins, phoneTexts) {
// This is then filtering the object of phones to match what the user has entered into the system.
const matchingPhones = phones.filter(function(phone) {
if(phone.brand===phoneBrand && phone.cost.toString()<=phoneCost && phone.data<=phoneData && phone.minutes.toString()<=phoneMins && phone.texts.toString()<=phoneTexts) {
return true;
}
return false;
})
}
function printResults() {
// This is then displaying data in the system.
const returnPhones = document.querySelector("#returnPhones");
matchingPlans.forEach(function(phone) {
const newList = document.createElement("ul");
newList.textContent=phone.name;
returnPhones.appendChild(newList);
})
}
const userPrefs = getUserPreferences();
const matchingPlans = getMatchingPlans(userPrefs);
printResults(matchingPlans);
非常感谢您的帮助!我只是想让程序将用户的偏好与手机对象中存储的手机相匹配,然后在 DOM 中显示给用户。以前没有这个工作的函数,我只是想用函数来重构它。
【问题讨论】:
-
getMatchingPlans从不返回任何东西,所以调用它的结果是undefined。 -
您也没有将
matchingPlans声明为printResults中的参数,因此printResults从外部范围使用matchingPlans,这不是最佳实践。您将它作为参数传递,因此声明一个参数来接收它:function printResults(matchingPlans) {。
标签: javascript html loops object foreach