Chapter 3, Functions
Lets do the following exercises:
Exercises
- To convert Hex colors to RGB, perform the following:
function getRGB(hex) { return "rgb(" + parseInt(hex[1] + hex[2], 16) + ", " + parseInt(hex[3] + hex[4], 16) + ", " + parseInt(hex[5] + hex[6], 16) + ")"; } Testing: > getRGB("#00ff00"); "rgb(0, 255, 0)" > getRGB("#badfad"); "rgb(186, 223, 173)"
One problem with this solution is that array access to strings like
hex[0]
is not in ECMAScript 3, although many browsers have supported it for a long time and is now described in ES5.However, But at this point in the book, there was as yet no discussion of objects and methods. Otherwise an ES3-compatible solution would be to use one of the string methods, such as
charAt()
,substring()
, orslice()
. You can also use an array to...