首页 > 解决方案 > 使用 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”

我在这里做错了什么?

标签: javascriptarrays

解决方案


在您要求用户输入的行中,您正在用整数覆盖您在第一行中声明的数组。您无法访问整数的第 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")
}

推荐阅读