【发布时间】:2019-08-10 01:30:07
【问题描述】:
我正在做我的项目并决定最大限度地优化它!我的函数的目的是随机放置一张图片。
这是我的 js 函数:
moveImage() {
this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
}
可以优化吗? 我不认为我应该使用 random 两次...
【问题讨论】:
-
“我不认为我应该使用 random 两次...” 为什么不呢?你不想要不同的数字吗?
-
您是要优化性能还是优化可读性?在这两个方面似乎已经非常接近最优了。如果您不想调用
Math.random两次,您总是可以将结果存储在一个变量中,但这会导致非常不同的行为,因此请仔细考虑这是否是您真正想要的。 -
@T.J.Crowder 我正试图找到一些变体来少写......因为这个原因!数字应该不同
-
moveImage(img, screensize, size) { img = Math.round(Math.random() * (screensize - size)); } moveImage(this.imgTop, screen.height, this.imgHeight) moveImage(this.imgLeft, screen.width, this.imgWidth)
标签: javascript function optimization ecmascript-6