简体   繁体   English

为什么我的程序提示未定义的值

[英]Why my program alerting undefined value

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]);
}

Why it shows the undefined value after alerting foundcars array eg, nano bmw it's alert, undefined, undefined Please let me know where I am wrong. 为什么在警告foundcars数组后显示未定义的值,例如nano bmw,它是警报,未定义,未定义的请让我知道我错了。

First of all you need to add the result of the prompt to a proper place in the con array. 首先,您需要将提示结果添加到con数组中的适当位置。

Then you should iterate through the array having in mind the length of the foundCars, not hard-coded 2. 然后,您应该考虑到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]);
}

jsfiddle jsfiddle

because foundCars is null for ever 因为foundCars为空

you should use like this for found cars. 您应该将这样的车用于发现的汽车。

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);
       } 
    }
}

and use for(var i = 0; i<foundCars.length; i++) insted of for(var i = 0; i<2; i++) 并使用for(var i = 0; i<foundCars.length; i++) for(var i = 0; i<2; i++)

Please Check: 请检查:

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);

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

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