javascript – 子串,拆分,字符串到数字和RGB到HEX

我认为这是一项简单的任务,但它变得非常复杂.见代码.

    // Convert "rgb(255, 255, 255)" to (255, 255, 255) and then to Hex code
    var data = {
        color:"rgb(165,199,72)",
        color:"rgb(229,121,74)",
        color:"rgb(105,177,222)"        
    }
    // rgb To Hex Conversion
    var componentToHex = function(c) {            
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }       
    var rgbHex = function(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }


    //Substring "rgb(255, 255, 255)" to "(255, 255, 255)"
    var subStringRGB = function(c){
        var b = c.substring(4, c.length);
    }
    var stringRGBtoNumber = function(c){
        var b = Number(c.split(','));
    }

它是抛出错误,无法读取未定义的拆分.如何解决这个问题?

最佳答案
您可以将这些函数组合成带有扩展运算符的单行和一些值的部分映射.

subStringRGB和stringRGBtoNumber现在返回已处理的值.

var data = [{ color:"rgb(165,199,72)"}, { color:"rgb(229,121,74)" },{ color:"rgb(105,177,222)" }],        
    componentToHex = function(c) {            
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    },
    rgbHex = function(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    },
    subStringRGB = function(c){
        return c.slice(4, -1);
    },
    stringRGBtoNumber = function(c){
        return c.split(',').map(Number); // split and convert all parts to Number
    };
    
console.log(data.map(c => rgbHex(...stringRGBtoNumber(subStringRGB(c.color)).map(componentToHex))));

转载注明原文:javascript – 子串,拆分,字符串到数字和RGB到HEX - 代码日志