我正在参加网络开发训练营类(class),并为我们的一个项目做一些额外的工作。我们构建了 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,但我尝试使用 .slice()、indexOf() 和 .split() 方法的方式一定是错误的.
最佳答案
您正在调用不带参数的“rbgToHex”函数。
更改为
//compare clicked color to picked color
if (rgbToHex(clickedColorVar) === pickedColorVar)
在“rgbToHex”函数中发现另一个问题。
var clickedColorVarArray = clickedColorVar.slice(clickedColorVar.indexOf("("), clickedColorVar.indexOf(")")).split(",");
上面的行应该是
var clickedColorVarArray = clickedColorVar.slice(clickedColorVar.indexOf("(")+1, clickedColorVar.indexOf(")")).split(",");
同时更改“makeHex”,如以下代码片段所示。否则它不会给你正确的十六进制代码,因为你尝试从“string”而不是“int”获取十六进制值
function makeHex(x) {
var hex = parseInt(x).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
关于javascript - 如何使用 JavaScript 解析值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405182/