简体   繁体   English

JavaScript代码在输出中打印多余的行(未定义)

[英]JavaScript code printing extra line (undefined) in output

need help with this code. 需要有关此代码的帮助。 What am I doing wrong? 我究竟做错了什么?

Problem: Create 10 cars, where each car has a color and number. 问题:创建10辆汽车,每辆汽车都有颜色和数字。 The cars should be numbered in order from 0 to 9. The cars from 0 to 4 should be colored "green" and the cars from 5 to 9 should be colored "blue". 轿厢应按从0到9的顺序编号。从0到4的轿厢应被标记为“绿色”,而从5到9的轿厢应被标记为“蓝色”。 Place the cars in order in an array called carGarage. 将汽车按顺序排列在名为carGarage的阵列中。

Guideline: To avoid duplicate code when creating 10 separate cars, first first create a constructor function Car that takes color and number parameters and sets them to this.color and this.number. 准则:为了避免在创建10辆独立的汽车时出现重复的代码,首先要创建一个构造函数Car,该函数接受颜色和数字参数并将它们设置为this.color和this.number。 Then create 10 cars and place them in a carGarage array. 然后创建10辆汽车,并将它们放置在carGarage阵列中。

// create a car constructor function
var Car = function(color, number) {
    this.color = color;
    this.number = number;
}
// create a carGarage array
var carGarage = [10];
// create a loop that creates cars and places them in carGarage
for (var i = 0; i <= 9; i++) {
    var color, number;
    i <= 4? color = 'green': color = 'blue';
    number = i;
    var newCar = new Car(color, number);
    carGarage.push(newCar);

}
// test code
for (var i = 0; i < carGarage.length; i++) {
   car = carGarage[i];
   console.log(car.color + " car #" + car.number);
}

Expected Output 预期产量

green car #0
green car #1
green car #2
green car #3
green car #4
blue car #5
blue car #6
blue car #7
blue car #8
blue car #9

Actual Output 实际产量

undefined car #undefined
green car #0
green car #1
green car #2
green car #3
green car #4
blue car #5
blue car #6
blue car #7
blue car #8
blue car #9

This line is the key: 这行是关键:

var carGarage = [10];

You've initialized array with one element - 10 , not array of length 10. You have to change it to: 您已使用一个元素10初始化了数组,而不是长度为10的数组。您必须将其更改为:

var carGarage = [];

So you initialize empty array. 因此,您初始化了空数组。

You had 2 times undefined because both 10.color and 10.number aren't defined. 您有2次undefined因为未同时定义10.color10.number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM