coffeescript-为什么总是将其输出为'1'?

问题描述 投票:0回答:1

为什么即使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"
javascript html coffeescript
1个回答
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而被删除
© www.soinside.com 2019 - 2024. All rights reserved.