how do I want to fill the undefined value in the seats array with the value in namaPenumpang
my code
I have tried using a for
loop it worked
var kursi = [undefined, "galih"];
function tambahPenumpang(namaPenumpang, kursi) {
// jika angkot masih kosong
if (kursi.length == 0) {
kursi.push(namaPenumpang);
return kursi;
} else {
for (let i = 0; i < kursi.length; i++) {
if (kursi[i] === undefined) {
kursi[i] = namaPenumpang;
return kursi;
} else if (namaPenumpang === kursi[i]) {
console.log("Kursi ini sudah terisi oleh " + kursi[i]);
return kursi;
} else if (kursi[i] !== undefined) {
kursi.push(namaPenumpang);
return kursi;
}
}
}
}
How my code work use a map()
?
Please help me to solve this problem, how can the contents of the array at the index with the value unndefined be replaced using the value namaPenumpang
2
Answers
map
always returns an array of the same size. So you cannot add new items.The logic of your code probably does not do what you intend.
Here are some modifications:
You can get the same functionality with the map function.