Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ตรวจสอบ JavaScript Arrays ว่ามี Empty Strings หรือไม่

ข้อมูลตัวอย่าง

var studentDetails = new Array(); 
studentDetails[0] = "John"; 
studentDetails[1] = ""; 
studentDetails[2] = "Smith"; 
studentDetails[3] = ""; 
studentDetails[4] = "UK";

วิธีตรวจสอบ

ใช้ for loop ตรวจสอบ array[index] == ""

ตัวอย่างโค้ด

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

วิธีรัน

node fileName.js

ชื่อไฟล์ demo210.js

ผลลัพธ์

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

คำอธิบาย

วนลูปตรวจสอบทุก index studentDetails[index] == "" พบ empty string ที่ index 1 และ 3
วิธีทันสมัย: arr.some(s => s === "") หรือ arr.includes("") ตรวจสอบเร็วกว่า