search

Home  >  Q&A  >  body text

javascript问题:rgb语法书写问题

请问在为背景颜色赋随机值的时候,正确书写方式如下:

javascriptdocument.body.style.backgroundColor = 

'rgb(' + 
Math.floor(Math.random() * 256) + 
',' + 
Math.floor(Math.random() * 256) +
',' +
Math.floor(Math.random() * 256) + 
')';

问题:
正常赋值是这样:document.body.style.backgroundColor= 'rgb(255,255,255)';
不太明白的点在
'rgb('+ ……的一长串字串连接,是怎么连接起来的?
谢谢。

PHP中文网PHP中文网2902 days ago702

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 14:55:25

    给你换一种写法

    var r=Math.floor(Math.random() * 256)
    var g=Math.floor(Math.random() * 256)
    var b=Math.floor(Math.random() * 256)
    document.body.style.backgroundColor = 'rgb('+r+','+g','+b+')';
    

    reply
    0
  • 迷茫

    迷茫2017-04-10 14:55:25

    那段代码里就直接字符串拼接起来的,如:

    console.log('hello' + 'world'); // 'helloworld'
    

    reply
    0
  • 高洛峰

    高洛峰2017-04-10 14:55:25

    Math.floor(Math.random() * 256)返回的是一个[0, 255]之间的数字,在加起来的过程中,被隐式调用toString()转换成了字符串。

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 14:55:25

    JS 如果用字符串去加数字或者其他,就会自动转换成字符串,你问题中的','就是字符串,去加你的数值,就转成了字符串,隐形地调用了toString()

    reply
    0
  • Cancelreply