如何检查 JavaScript 数组中是否为空字符串?
javascriptweb developmentobject oriented programming
假设以下是包含非空值和空值的数组 −
studentDetails[2] = "Smith"; studentDetails[3] = ""; studentDetails[4] = "UK"; function arrayHasEmptyStrings(studentDetails) { for (var index = 0; index < studentDetails.length; index++) {
要检查数组中是否为空字符串,语法如下。设置这样的条件进行检查 −
if(yourArrayObjectName[yourCurrentIndexvalue]==””){ // insert your statement } else{ // insert your statement }
示例
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