【问题标题】:Assigning a value to a variable randomly, but not working随机为变量赋值,但不起作用
【发布时间】:2013-08-31 17:42:22
【问题描述】:

我正在尝试编写 JavaScript 代码,该代码将通过一个函数生成一个随机数,然后使用该随机数(1 到 6 之间)为变量“背景”分配一个值。

这就是我所拥有的:

function genBackground() {

var x=Math.floor((Math.random()*6)+1);

assignBG(x);
alert("test alert");
}

function assignBG(x) {
if (x === 1){
var background=blue;}
else if (x === 2){
var background=green;}
else if (x === 3){
var background=red;}
else if (x === 4){
var background=purple;}
else if (x === 5){
var background=yellow;}
else if (x === 6){
var background=orange;}
}

警报“测试警报”不显示,但在“assignBG(x);”行之前显示。我做错了吗?

【问题讨论】:

    标签: javascript random numbers


    【解决方案1】:

    这些“颜色”是否之前在代码中定义?否则,你应该写color = "white"等等......

    我也会像这样重写assignBG:

    function genBackground() {
    
        var x=Math.floor((Math.random()*6)+1);
    
        var color = generateBG(x);
        alert(color); // and do whatever you like with this color
    }
    
    function generateBG(x) {
        var colors = ["blue","green","red","purple","yellow","orange"];
        return colors[x];
    }
    

    【讨论】:

    • 前面定义的意思是什么?这是完整的代码
    • 我的意思是bluegreenpurple是变量名,不是原子或字符串……JS中没有预定义这样的全局变量。
    • 我使用了你重写的函数 assignBG() 并且它可以工作,谢谢
    • 我再次重写了它,所以它不使用全局变量(这被认为是一种不好的做法)。另外,浏览器的开发者控制台中没有出现这个错误吗?
    猜你喜欢
    • 2014-10-31
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多