如何检查 JavaScript 数组中的空字符串?
假设数组中包含非空值和空值,如下所示:-
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
广告