在if/else if语句中,变量被锁定在第一个选项中.我怎样才能解决这个问题? [英] In an if/else if statement, the variable is being locked into the first option. How can I fix this?

查看:105
本文介绍了在if/else if语句中,变量被锁定在第一个选项中.我怎样才能解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的常规代码(使用JavaScript):

This is my general code (in JavaScript):

let x = Math.floor(Math.random()×6)+1);

if (x=1){
   do this
} else if (x=2){
   do that
} else if.... and so on. 

每当我在浏览器中测试此代码时,只会执行{do this}部分中可能发生的操作. x被锁定为1,即使这意味着它是6面公平的骰子.有什么想法为什么会发生这种情况,以及我该如何解决?

Whenever I test this code in a browser, only actions that could happen in the {do this} section happen. x is being locked as 1, even though it is meant to be a fair 6 sided die. Any ideas why this is happening, and how I can fix it?

推荐答案

JavaScript中的=运算符用于分配. x=1将始终返回true,因为这是一个永不失败的赋值.要测试是否相等,请使用==(平等)或===(

The = operator in JavaScript is for assignment. x=1 will always return true because that is an assignment that will never fail. To test for equality use == (equality with conversion) or === (strict equality).

这篇关于在if/else if语句中,变量被锁定在第一个选项中.我怎样才能解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆