javascript对象数组输入到对象

时间:2016-12-18 14:44:38

标签: javascript arrays object

我想做什么:3个html输入,onclick(addCar) - 构造函数Cars创建对象(基于输入:名称,时间,速度和驱动程序)并将其存储在数组“cars”中。 onclick(race) - 从数组汽车中打印所有创建的对象(console.log)。

这是我到目前为止所做的:

var name = document.getElementById("name");
var time = document.getElementById("time");
var speed = document.getElementById("speed");
var driver = document.getElementById("driver");
var addCar = document.getElementById("addCar");
var race = document.getElementById("race");
var box = document.getElementById("box");
var cars = [];

function Cars(name, time, speed, driver, distance){
    this.name = name;
    this.time = time;
    this.speed = speed;
    this.distance = 0;
}

addCar.addEventListener("click", function(){
    var carNew = new Cars (name.value, time.value, speed.value, driver.value);
    cars.push(carNew);
});

race.addEventListener("click", function(){
    console.log(cars);
});
<!doctype html>
<html>
    <head>
        <title>J21ND</title>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="J21ND.css">
    </head>
    <body>
        <div class="fields">
            <h1>Car Race</h1>
            <input id="name" type="text" placeholder="Input car name">
            <input id="time" type="text" placeholder="Input car time">
            <input id="speed" type="text" placeholder="Input car speed">
            <input id="driver" type="text" placeholder="Input driver level, select: Rookie, Advanced or Pro">
        </div>
        <div class="buttons">
            <button id="addCar">Add Car</button>
            <button id="Race">Start Race</button>
        </div>
        <div id="box">
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

你有<button id="Race">Start Race</button>。 ID为Race

var race = document.getElementById("race");不同,其中ID为race。而且,Race!= race

我让他们平等,这是fiddle在控制台上记录的cars