亂數產生顏色

72 views
Skip to first unread message

gugod

unread,
Mar 9, 2007, 3:56:34 PM3/9/07
to hsinchu.js
以下這一列是用來產生 CSS 指定顏色時可用的 rgb(R,G,B) 字串。

"rgb(%,%,%)".replace(/%/g, function() { return
Math.floor(Math.random()*255) })

了解到 replace() 的第二個參數也可以是個 function() 的話,有些討厭的字串接續動作也可以變成字串內插變數,而迎刃而解了,
如:

"Hello, %NAME, You got %NUMBER of junk mails".replace(/%NAME/g,
user_name).replace(/%NUMBER/g, Math.random() * 10000 + 1000)

用此方法來弄個迷你樣版系統也許不難喔。

gugod

unread,
Mar 9, 2007, 3:59:26 PM3/9/07
to hsinchu.js

On Mar 10, 4:56 am, "gugod" <gugod...@gmail.com> wrote:

> 了解到 replace() 的第二個參數也可以是個 function() 的話,有些討厭的字串接續動作也可以變成字串內插變數,而迎刃而解了,
> 如:
>
> "Hello, %NAME, You got %NUMBER of junk mails".replace(/%NAME/g,
> user_name).replace(/%NUMBER/g, Math.random() * 10000 + 1000)

呃,這個範例沒有用到 function,應該改寫為:

"Hello, %NAME, You got %NUMBER of junk mails".replace(/%([A-Z]+)/g,
function( word ) { return dict[word] })

replace 第二個參數中若為 function 的話,其參數便為正規表示式所捕捉到的值。

Reply all
Reply to author
Forward
0 new messages