为什么我的程序警告未定义的值

时间:2015-03-22 15:43:39

标签: javascript

var cars = ["nano", "bmw"];
var bikes = ["pulsar", "splander"];
var con = [];
var foundCars = [];
var foundBikes = [];
var notFoundTransport =[];
for(var i = 0; i<cars.length; i++){
    con = prompt("enter your tranport name");
    if(con[i] == cars[i]){
    foundCars.push(con[i]);
    } 
}
for(var i = 0; i<2; i++){
alert(foundCars[i]);
}

为什么在警告foundcars数组后它显示未定义的值 例如,nano bmw 它是警报,未定义,未定义 请让我知道我错在哪里。

3 个答案:

答案 0 :(得分:0)

首先,您需要将提示的结果添加到con数组中的适当位置。

然后你应该考虑到foundCars的长度迭代数组,而不是硬编码2。

var cars = ["nano", "bmw"];
var bikes = ["pulsar", "splander"];
var con = [];
var foundCars = [];
var foundBikes = [];
var notFoundTransport =[];
for(var i = 0; i<cars.length; i++){
    con[i] = prompt("enter your tranport name");
    if(con[i] == cars[i]){
        foundCars.push(con[i]);
    } 
}
for(var i = 0; i<foundCars.length; i++){
    alert(foundCars[i]);
}

答案 1 :(得分:0)

jsfiddle

因为foundCars永远为空

你应该像这样使用已发现的汽车。

for(var i = 0; i<cars.length; i++){
    con = prompt("enter your tranport name");
    for(var p = 0; p<cars.length; p++){
       if(con == cars[p]){
         foundCars.push(con);
       } 
    }
}

并使用for(var i = 0; i<foundCars.length; i++)

for(var i = 0; i<2; i++)内容

答案 2 :(得分:-1)

请检查:

var cars = ["nano", "bmw"];
var bikes = ["pulsar","splander"];
var con = [];
var foundCars = [];
var foundBikes = [];
var notFoundTransport =[];
var found = false;
var checkExist = false;


for(var i = 0; i<2; i++){
    con[i] = prompt("enter your tranport name");
}

for(var i = 0; i<con.length; i++){
    for(var j = 0; j<con.length; j++){
        if(con[i] == cars[j]){
            foundCars.push(con[i]);
            found = true;
            checkExist = true;
        }else if(con[i] == bikes[j]){
            foundBikes.push(con[i]);
            found = true;
            checkExist = true;
        }else if(con[i]!=cars[j]&&con[i]!=bikes[j]&&found==false&&j!=0){
                notFoundTransport.push(con[i]);
                found = true;
        }
    }
        found = false;
}

console.log(foundCars);
console.log(foundBikes);
console.log(notFoundTransport);