前端自学——改过的代码

终于几番纠结之后,开始了前端自学之路。虽然有转行穷三年的说法,我还是希望我的决定是值得的。

这个博客中记录的是自己犯过的错,用于自省。

1. Java Script学习

练习的题目是,随机生成一个颜色,在界面显示。跟着视频自己写了一个,获得的颜色字符串总是undefined。

function getColor() {
    var arr = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
    var str = "#";
    for (var i = 0; i < 6; ++i)
    {
        var num = parseInt(Math.random * 16);
        str += arr[num];
    }
    return str;
}
console.log(getColor());
window.onload = function () {
    document.getElementById("dv").style.backgroundColor = getColor();
}

再次看视频才发现问题:
1.random方法,应该有()
2.颜色是由十六进制构成,random()方法结果的范围是[0,1)。由于十六进制的字符串存储在数据中,所以数组的索引值范围应是0~15,故随机生成索引值时应是random()*15。

function getColor() {
            var arr = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
            var str = "#";
//            console.log(parseInt(Math.random()*16));
//            return str;
            for (var i = 0; i < 6; ++i)
            {
                var num = parseInt(Math.random() * 15);
                str += arr[num];
            }
            return str;
        }

        window.onload = function () {
            document.getElementById("dv").style.backgroundColor = getColor();
        }

你可能感兴趣的:(前端学习,Java,Script)