繁体   English   中英

如何使用 javascript 解析值?

[英]How do I parse a value using javascript?

我正在学习 web 开发训练营课程,并在我们的一个项目上做一些额外的工作。 我们构建了一个 RGB 颜色猜测游戏,我正在将它转换为一个十六进制颜色猜测游戏。 虽然网上有很多示例显示我可以复制和粘贴来进行这种转换的代码,但我更愿意编写自己的代码以了解代码的功能。 所以我的问题不是“我该怎么做这件事?” 因为它是“我现在做错了什么,为什么我不能这样做?” 然后给我看一个可行的例子。

我尝试了一些我在网上看到的不同方法,但是在每个应用程序中我都没有正确执行逻辑,因为我收到“无法设置未定义的属性”或“splilt() 不是函数) 等。

for(var i = 0; i < squaresVar.length; i++) {
  //add click listeners to squares
    squaresVar[i].addEventListener("click", function() {
      //convert RGB clickedColorVar to hex value
        var clickedColorVar = this.style.backgroundColor;
        function rgbToHex(clickedColorVar) {
//this is where I check that the function is running and that the var is selected
console.log("inside the rgbToHex function" + clickedColorVar);

//this bit is where I am confused. I am probably not using it right.
var clickedColorVarArray = clickedColorVar.slice(clickedColorVar.indexOf("("), clickedColorVar.indexOf(")")).split(",");


//if I can get the previous line of code to work, these rgb variable values should be extracted into an array I can then selectively convert into hex values, but I haven't made it this far since before we get here the console returns "split is not a function"

var r = clickedColorVarArray[0];
var b = clickedColorVarArray[1];
var g = clickedColorVarArray[2];

return "#" + makeHex(r) + makeHex(g) + makeHex(b);
                }

//Here is the function we are calling to convert the rgb values into 2 digit hex values
function makeHex(x) {
    var hex = x.toString(16);
//I don't understand this bit either, why aren't we checking for 2 digits?
//or is this checking for one digit and then adding a 0?
    return hex.length == 1 ? "0" + hex : hex;
}
//and at last here is where I call the rgbToHex function and pass it the clickedColorVar (which is an rgb color)
rgbToHex(clickedColorVar);

我原以为我可以得到三个不同的值,一个用于 r、g 和 b,但我尝试使用 the.slice()、indexOf() 和.split() 方法的方式肯定是错误的。

这是在codepen中: https://codepen.io/KD-Neeley/pen/PooNvWQ

您在没有参数的情况下调用 'rbgToHex' function。

将其更改为

//compare clicked color to picked color
    if (rgbToHex(clickedColorVar) === pickedColorVar)

在“rgbToHex”function 中发现了另一个问题。

var clickedColorVarArray = clickedColorVar.slice(clickedColorVar.indexOf("("), clickedColorVar.indexOf(")")).split(",");

上面的线应该是

var clickedColorVarArray = clickedColorVar.slice(clickedColorVar.indexOf("(")+1, clickedColorVar.indexOf(")")).split(",");

也像下面的代码片段一样改变'makeHex'。 否则它不会为您提供正确的十六进制代码,因为您尝试从“字符串”而不是“整数”获取十六进制值

function makeHex(x) {
var hex = parseInt(x).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}

您正在将.split 应用于返回数字的 indexOf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM