coffeescript-为什么这总是输出为“ 1”?

时间:2020-03-14 14:54:56

标签: javascript html coffeescript

为什么即使randomArea不是North,它总是输出为“ 1”?

if randomArea = "North"
    id.innerHTML = "1"
else if randomArea = "South"
    id.innerHTML = "2"
else if randomArea = "East"
    id.innerHTML = "3"
else if randomArea = "West"
    id.innerHTML = "4"
else if randomArea = "Central"
    id.innerHTML = "5"
else if randomArea = ""
    id.innerHTML = "6"

1 个答案:

答案 0 :(得分:0)

在JavaScript中,=是一个赋值运算符,它将始终赋值,if语句将评估该值的真实性。在这种情况下,“ North”是一个非空字符串,这是正确的,因此id.innerHTML被分配了其值"1"。应该使用等号运算符==

if randomArea = "North"       // <-- here
    id.innerHTML = "1"
else if randomArea = "South"
    id.innerHTML = "2"
else if randomArea = "East"
    id.innerHTML = "3"
else if randomArea = "West"
    id.innerHTML = "4"
else if randomArea = "Central"
    id.innerHTML = "5"
else if randomArea = ""
    id.innerHTML = "6"

您需要更改所有相等条件以评估真实性,而不是分配值,该值始终会用非空字符串解析为true

if randomArea == "North"            // <-- here
    id.innerHTML = "1"
else if randomArea == "South"       // <-- here
    id.innerHTML = "2"
else if randomArea == "East"        // <-- here
    id.innerHTML = "3"
else if randomArea == "West"        // <-- here
    id.innerHTML = "4"
else if randomArea == "Central"     // <-- here
    id.innerHTML = "5"
else if randomArea == ""            // <-- here
    id.innerHTML = "6"

注意:

  • 最有可能需要删除// <-- here才能获得有效的CoffeeScript