javascript问题:rgb语法书写问题
PHP中文网
PHP中文网 2017-04-10 14:53:25
[JavaScript讨论组]

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

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中文网

认证0级讲师

全部回复(4)
大家讲道理

给你换一种写法

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+')';
迷茫

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

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

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

伊谢尔伦

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号