将十进制转换为二进制、八进制或十六进制
let num = 43;
console.log(num.toString(2));
console.log(num.toString(8));
console.log(num.toString(16));
保留指定位小数
let num = 3.141592653;
console.log(num.toFixed(2));
console.log(num.toFixed(4));
颜色色值转换,代码来自Copilot提示
function rbg2Hex(r, g, b) {
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
function hex2Rgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
console.log(rbg2Hex(255, 0, 0));
console.log(hex2Rgb('#FF0000'));
console.log(rbg2Hex(255, 0, 200));
console.log(hex2Rgb('#ff00c8'));
参考 强推:20个值得收藏的ES6小技巧
|