Giả sử sau đây là mảng của chúng ta với các giá trị không trống và rỗng -
studentDetails[2] = "Smith";
studentDetails[3] = "";
studentDetails[4] = "UK";
function arrayHasEmptyStrings(studentDetails) {
for (var index = 0; index < studentDetails.length; index++) { Để kiểm tra mảng cho các chuỗi trống, cú pháp như sau. Đặt điều kiện như vậy để kiểm tra -
if(yourArrayObjectName[yourCurrentIndexvalue]==””){
// insert your statement
} else{
// insert your statement
} Ví dụ
var studentDetails = new Array();
studentDetails[0] = "John";
studentDetails[1] = "";
studentDetails[2] = "Smith";
studentDetails[3] = "";
studentDetails[4] = "UK";
function arrayHasEmptyStrings(studentDetails) {
for (var index = 0; index < studentDetails.length; index++) {
if (studentDetails[index] == "")
console.log("The array has empty strings at the index=" +
(index));
else
console.log("The value is at
index="+(index)+"="+studentDetails[index]);
}
}
arrayHasEmptyStrings(studentDetails); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js
Ở đây tên tệp của tôi là demo210.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\javascript-code> node demo210.js The value is at index=0=John The array has empty strings at the index=1 The value is at index=2=Smith The array has empty strings at the index=3 The value is at index=4=UK