如何使用 JavaScript 避免向表中插入 NULL 值?
javascriptweb developmentobject oriented programming更新于 2025/11/22 2:52:17
为了消除插入表中的空值,您需要在输入值时检查条件。
检查 NULL 的条件必须如下 −
while( !( yourVariableName1==null || yourVariableName2==null ||
yourVariableName3==null…...N){
// yourStatement1
.
.
N
}
上述逻辑永远不会允许插入空值。
现在您可以使用 for 循环并将值插入表中而不插入 NULL。以下是代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h2>Demo Of Inserting the value into the table</h2>
<p>This is demo on the javascript array</p>
<p id="demo"></p>
<script>
var index = 0;
var firstNameArray = new Array();
var lastNameArray = new Array();
var firstName = "";
var lastName = "";
while (!(firstName == null || lastName == null)) {
firstName = prompt("Please Enter your First Name=");
lastName = prompt("Please Enter your Last Name=");
firstNameArray[index] = firstName;
lastNameArray[index] = lastName;
index++;
}
document.writeln("<table border='1' width='50%'>");
document.writeln("<caption>DEMO TABLE IN JAVASCRIPT</caption>");
document.writeln("<th>FirstName</th><th>LastName</th>");
for (var startIndex in firstNameArray) {
if (firstNameArray[startIndex] !== null &&
lastNameArray[startIndex] !== null)
document.writeln("<tr><td>" + firstNameArray[startIndex] +
"</td><td>" + lastNameArray[startIndex] + "</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>
要运行上述程序,请保存文件名"anyName.html(index.html)",然后右键单击该文件。选择选项"使用 Live Server 打开"在 VS Code 编辑器中。
输出
将产生以下输出 −

现在输入名字。
将产生以下输出 −

点击 OK 按钮后,您将获得以下输出 −

现在,输入姓氏这将产生以下输出 −

点击OK按钮后,现在点击两次Cancel按钮,您将获得最终输出。
最终输出表如下 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

