我试图让这个程序与HTML一起在DOM中显示--然而,在JavaScript控制台中,它却给了我这个错误。
Uncaught ReferenceError: phoneBrand is not defined
at test.js:74
at Array.filter (<anonymous>)
at getMatchingPlans (test.js:73)
at test.js:104
我已经尝试用不同的方式来修改,比如重做对象声明,但是我仍然有这个问题。如果能得到如何解决这个问题的信息,我将非常感激。
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() {
// 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");
matchingPhones.forEach(function(phone) {
const newList = document.createElement("ul");
newList.textContent=phone.name;
returnPhones.appendChild(newList);
})
}
const userPrefs = getUserPreferences();
const matchingPlans = getMatchingPlans(userPrefs);
printResults(matchingPlans);
正如错误信息所说,你使用了 phoneBrand
标识符,它没有被定义--它不是函数参数,不是变量。
你可能需要把它作为 getMatchingPlans
函数,以及那里使用的其他标识符。phoneCost
, phoneData
、等。
2 错误。