javascript - 使用 JavaScript 检查偶数或添加
问题描述
我正在尝试学习 JavaScript,我正在使用一个数组并提供一个瑞典社会保障 nr 来确定它是男人还是女人。
瑞典的 ssn 长度为 10,如果倒数第二个 nr 为偶数,则为女性,否则为男性。
所以我尝试构建以下内容:
let socialSec = Array[10]
socialSec = parseInt(prompt("Supply social security nr"))
document.write("Your input nr was: " + socialSec + "<br>" + "<br>")
if (socialSec[8] % 2 === 0) {
document.write("Woman")
} else {
document.write("Man")
}
但无论我输入什么,它总是默认为“Man”
我在这里做错了什么?
解决方案
在您要求用户输入的行中,您正在用整数覆盖您在第一行中声明的数组。您无法访问整数的第 8 个索引,因此它将始终默认为 Man
简单地说,如果 socialSec 是一个 int(由您的用户输入设置),则 socialSec[8] 将是未定义的。未定义 % 2 != 0。
以下是它的实现方式:
// Get the ssn as a string
let socialSec = prompt("Supply social security nr")
document.write("Your input nr was: " + socialSec + "<br>" + "<br>")
// convert the string to an array (optional)
socialSec = socialSec.split("");
if (socialSec[8] % 2 === 0) {
document.write("Woman")
} else {
document.write("Man")
}
推荐阅读
- php - WordPress single.php 文件
- python - 在这段代码中,我得到了这个 ZeroDivisionError : float modulo
- r - 无法在 Emacs 的 R 缓冲区中以印地语 (utf-8) 显示文本
- django - 通过 url 与 django rest api 交互如何工作?
- powershell - CIM_LogicalDisk 枚举
- python - 动态熊猫数据框生成
- linux - GLX 视觉对象和 FBconfig 之间有什么区别?
- android - 如何从 Android App 中的 logcat 中捕获错误?
- c# - 使用 MVC 下载大文件
- powershell - Powershell 比较两个 List 和 foreach