Shorten this code?
Is there a way to short and make this function faster, smaller and better?
function rand() {
var r = Math.floor(Math.random()*array.length);
document.getElementById('obj').innerHTML = array[r];
}
Originally Posted by
WayneISWayne
Is there a way to short and make this function faster, smaller and better?
function rand() {
var r = Math.floor(Math.random()*array.length);
document.getElementById('obj').innerHTML = array[r];
}
Don't know why you would want to do that but...
Code:
function rand() {
document.getElementById('obj').innerHTML = array[Math.floor(Math.random()*array.length)];
}
Unless you are repeating it like a million times, I don't think the space or time difference will be significant!
Thank you so much! I'm trying to make a really small JavaScript for less load time etc... and better on benchmarks too.
A shorter method ?
Code:
function rand() {
document.getElementById('obj').innerHTML = array[~~ (Math.random()*array.length)];
}
Originally Posted by
007Julien
A shorter method ?
Code:
function rand() {
document.getElementById('obj').innerHTML = array[~~ (Math.random()*array.length)];
}
Dose the tilde work on all browsers?
Well, if you are repeating that a lot, it's not good to be calling document.getElementById so much. Storing a reference would probably be better. Short code doesn't necessarily mean it's faster.
Great wit and madness are near allied, and fine a line their bounds divide.
Originally Posted by
Declan1991
Well, if you are repeating that a lot, it's not good to be calling document.getElementById so much. Storing a reference would probably be better. Short code doesn't necessarily mean it's faster.
I know. If I do that, there would be a lot of function calls. I wish there was a better way of doing the getElementById.
As an example, you can see this page which play chess (no castling and en passant capture) with a 1023 bytes javascript !
Originally Posted by
WayneISWayne
I know. If I do that, there would be a lot of function calls. I wish there was a better way of doing the getElementById.
Code:
var rand = ( function ()
{
var elem = document.getElementById( 'obj' );
return function()
{
elem.innerHTML = array[ Math.floor( Math.random() * array.length ) ];
}
} )();
Where used, return should be executed unconditionally and always as the last statement in the function.
That's my signature, it's not part of the damn post!
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks