方法一:數組
var getRandomColor = function(){ return '#' + (function(color){ return (color += '0123456789abcdef'[Math.floor(Math.random()*16)]) && (color.length == 6) ? color : arguments.callee(color); })(''); }
隨機生成6個字符而後再串到一塊兒,閉包調用自身與三元運算符讓程序變得內斂。閉包
方法二: dom
var getRandomColor = function(){ return (function(m,s,c){ return (c ? arguments.callee(m,s,c-1) : '#') + s[m.floor(m.random() * 16)] })(Math,'0123456789abcdef',5) }
把Math對象,用於生成hex顏色值的字符串提取出來,並利用第三個參數來判斷是否還繼續調用自身。this
方法三:spa
Array.prototype.map = function(fn, thisObj) { var scope = thisObj || window; var a = []; for ( var i=0, j=this.length; i < j; ++i ) { a.push(fn.call(scope, this[i], i, this)); } return a; }; var getRandomColor = function(){ return '#'+'0123456789abcdef'.split('').map(function(v,i,a){ return i>5 ? null : a[Math.floor(Math.random()*16)] }).join(''); }
這個要求咱們對數組作些擴展,map將返回一個數組,而後咱們再用join把它的元素串成字符。prototype
方法四:code
var getRandomColor = function(){ return '#'+Math.floor(Math.random()*16777215).toString(16); }
這個實現很是逆天,雖然有點小bug。咱們知道hex顏色值是從#000000到#ffffff,後面那六位數是16進制數,至關於"0x000000"到"0xffffff"。這實現的思路是將hex的最大值ffffff先轉換爲10進制,進行random後再轉換回16進制。咱們看一下,如何獲得16777215 這個數值的。對象
方法五:blog
var getRandomColor = function(){ return '#'+(Math.random()*0xffffff<<0).toString(16); }
基本實現4的改進,利用左移運算符把0xffffff轉化爲整型。這樣就不用記16777215了。因爲左移運算符的優先級比不上乘號,所以隨機後再左移,連Math.floor也不用了。遞歸
方法六:
var getRandomColor = function(){ return '#'+(function(h){ return new Array(7-h.length).join("0")+h })((Math.random()*0x1000000<<0).toString(16)) }
修正上面版本的bug(沒法生成純白色與hex位數不足問題)。0x1000000至關0xffffff+1,確保會抽選到0xffffff。在閉包裏咱們處理hex值不足6位的問題,直接在未位補零。
方法七:
var getRandomColor = function(){ return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).slice(-6); }
此次在前面補零,連遞歸檢測也省了。
上面版本生成顏色的範圍算是大而全,但隨之而來的問題是顏色很差看,因而實現8搞出來了。它生成的顏色至關鮮豔。
方法八:
var getRandomColor = function(){ return "hsb(" + Math.random() + ", 1, 1)"; }