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.
First of all you need to add the result of the prompt to a proper place in the con array.
Then you should iterate through the array having in mind the length of the foundCars, not hard-coded 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]);
}
because foundCars
is null for ever
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++)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.