当前位置: 首页 > 科技观察

JavaScript:如何将颜色字符串转换为对象?

时间:2023-03-12 12:10:43 科技观察

将一个HSL颜色字符串转换为具有每个颜色值的对象思路:使用String.prototype.match()得到一个包含3个字符串和数值的数组;使用Array.prototype.map()和Number得到这些被转换为数值数组;使用数组分解将值存储到命名变量中,并从中创建适当的对象。代码实现:consttoHSLObject=(hslStr)=>{const[hue,saturation,lightness]=hslStr.match(/\d+/g).map(Number);return{hue,saturation,lightness};}//测试控制台.log(toHSLObject('hsl(50,10%,10%)'));//{hue:50,saturation:10,lightness:10}按照上面的思路可以处理RGB,RGBA,HSLA同理,如下:扩展一:将RGB颜色字符串转换为每个颜色值的对象代码:consttoRGBObject=(rgbStr)=>{const[red,green,blue]=rgbStr.match(/\d+/g).map(Number);return{red,green,blue};}console.log(toRGBObject('rgb(128,0,128)'));//{red:128,green:0,blue:128}扩展2:将一个RGBA颜色字符串转换为一个对象,每个颜色值代码实现:consttoRGBAObject=(rgbaStr)=>{let[red,green,blue,alpha]=rgbaStr.match(/\d+(\.\d+)?/g).地图(数字);return{red,green,blue,alpha};}console.log(toRGBAObject('rgba(128,0,128,0.5'));//{red:128,green:0,blue:128,alpha:0.5}扩展3:将HSLA颜色字符串转换为每个颜色值的对象代码:consttoRGBAObject=(hslaStr)=>{const[hue,saturation,lightness,alpha]=hslaStr.match(/\d+(\.\d+)?/g).map(Number);return{色调,饱和度,亮度,alpha};}console.log(toRGBAObject('hsla(128,0,128,0.5'));//{色相:128,饱和度:0,亮度:128,alpha:0.5}