【发布时间】:2021-02-26 00:02:09
【问题描述】:
我无法创建一个检查数组中对象的函数。它需要检查年份是否为 2018 年或更早,如果是,我需要输出它。我尝试了一些我认为可以像这样工作的更简单的方法:
function checkQualifies(year){
year >= 2018
};
和function checkQualifies(item, index){ if(carTypes) { printCarTypes(carTypes.filter(x=>x.year>="2018")) } }
但它要么破坏我的代码,要么无法运行。
这是我的全部代码:
<html>
<head>
<title>Assignment Seven : Array, Objects, Functions, Methods</title>
<meta author="My Name" />
</head>
<body>
<h1>Javascript Assignment</h1>
<br/>
<h2>Your Output</h2>
<div id="my_output"></div>
</body>
</html>
<script>
var studentName = "Alicia Villatoro";
writeToPage("Assignment for: " + studentName);
writeToPage("");
writeToPage("Program 1: Writing an Array of Car Makes");
writeToPage("");
writeToPage("Creating Array: ");
var array_name = car_makes;
var car_makes = ["Toyota", " Honda", " Audi", " BMW", " Mercedes"];
writeToPage("Displaying Array: ");
writeToPage(car_makes);
writeToPage("Program 2");
writeToPage("");
writeToPage("Create Car Object: ");
var toyotaCamryCar = new Object();
toyotaCamryCar['make'] = "Toyota";
toyotaCamryCar['model'] = "Camry";
toyotaCamryCar['year'] = "2019";
toyotaCamryCar['price'] = 25000;
writeToPage("Write the Car Object and Attributes");
writeToPage(toyotaCamryCar['make']);
writeToPage(toyotaCamryCar['model']);
writeToPage(toyotaCamryCar['year']);
writeToPage(toyotaCamryCar['price']);
writeToPage("Program 3");
writeToPage("");
writeToPage("Create an Array of Objects");
var carTypes = [];
carTypes.push({make:"Toyota", model: "Camry", year: "2018"});
carTypes.push({make: "Toyota", model: "Corolla", year: "2019"});
carTypes.push({make: "Audi", model: "A4", year: "2017"});
carTypes.push({make: "BMW", model: "i3", year: "2018"});
carTypes.push({make: "Honda", model :"Accord", year: "2016"});
writeToPage("Displaying Objects: ");
printCarTypes(carTypes);
writeToPage("Program 4");
writeToPage("");
writeToPage("Check the objects and print out the Toyota ones, use conditionals");
if(carTypes){
printCarTypes(carTypes.filter(x=>x.make==="Toyota"))
};
writeToPage("Program 5");
writeToPage("");
writeToPage("Create the checkQualifies function");
function checkQualifies(item, index){
if(carTypes)
{
printCarTypes(carTypes.filter(x=>x.year>="2018"))
}
}
writeToPage("Run the checkQualifies below for each entry of the array from Program 3");
writeToPage("Complete");
function printCarTypes(carTypes) {
for (var i = 0; i < carTypes.length; i++) {
writeToPage("Car Types [" + i + "]: " + JSON.stringify(carTypes[i]));
}
writeToPage("");
}
function writeToPage(strText) {
var output = document.getElementById("my_output");
var currentValue = output.innerHTML;
output.innerHTML = currentValue + "<br/>" + strText;
}
</script>'
【问题讨论】:
标签: javascript arrays function object