473,598 Members | 3,409 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Whats wrong with this?

<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Ma th.random());
document.write( safetyTips[i]);
}
output();
//-->
</script>
safetyTips[] - this array is in here.js ...

Jul 23 '05 #1
62 3703
TheShadow1 wrote on 02 apr 2005 in comp.lang.javas cript:
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Ma th.random());
document.write( safetyTips[i]);
}
output();
//-->
</script>


You cannot have both an external and inline scripting
with the same <script> block.

Don't use <!--, //-->, outdated for years.

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #2
TheShadow1 wrote:
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Ma th.random());
document.write( safetyTips[i]);
}
output();
//-->
</script>

safetyTips[] - this array is in here.js ...


Evertjan has already fixed your main problem, but you also have given
yourself a maintenance problem by hard-coding (I presume) the length
of your array.

Given the general nature of the question in your subject, I'll add
that you can also make it more concise (I've used 'sT' for the name
of the safteyTips array to avoid wrapping):

<script type="text/javascript" src="here.js"></script>
<script type="text/javascript">
document.write( sT[Math.round((sT. length-1)*Math.random( ))]);
</script>

is all that is required.

--
Rob
Jul 23 '05 #3
Lee
RobG said:

TheShadow1 wrote:
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Ma th.random());
document.write( safetyTips[i]);
}
output();
//-->
</script>

safetyTips[] - this array is in here.js ...


Evertjan has already fixed your main problem, but you also have given
yourself a maintenance problem by hard-coding (I presume) the length
of your array.

Given the general nature of the question in your subject, I'll add
that you can also make it more concise (I've used 'sT' for the name
of the safteyTips array to avoid wrapping):

<script type="text/javascript" src="here.js"></script>
<script type="text/javascript">
document.write( sT[Math.round((sT. length-1)*Math.random( ))]);


Using Math.round() underselects the first and last elements of the array.
sT[Math.floor(Math .random()*sT.le ngth)]

Jul 23 '05 #4
RobG <rg***@iinet.ne t.auau> writes:
document.write( sT[Math.round((sT. length-1)*Math.random( ))]); .... is all that is required.


Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math .random() * sT.length)]
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5
Lasse Reichstein Nielsen wrote:
RobG <rg***@iinet.ne t.auau> writes:

document.write( sT[Math.round((sT. length-1)*Math.random( ))]);


...
is all that is required.

Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math .random() * sT.length)]

or:
sT[new Date()%sT.lengt h]

Mick
Jul 23 '05 #6
Lee wrote:
RobG said:

[...]

<script type="text/javascript" src="here.js"></script>
<script type="text/javascript">
document.write( sT[Math.round((sT. length-1)*Math.random( ))]);

Using Math.round() underselects the first and last elements of the array.
sT[Math.floor(Math .random()*sT.le ngth)]


I was going to comment on the possibility that the selection was not
even for all elements in the array, however using Math.floor as
suggested infers that Math.random will *never* return 1, or at least
that the index will never be evaluated to be the length of the array.

Should that occur, the tip of the day will be 'undefined'.

The specification says that Math.random will return a value "greater
than or equal to 0 but less than 1" which means that in theory the
.floor method is OK, but is it in practice?
--
Rob
Jul 23 '05 #7
RobG wrote:
Lee wrote:

<snip>
Using Math.round() underselects the first and last elements of the
array. sT[Math.floor(Math .random()*sT.le ngth)]


I was going to comment on the possibility that the selection was not
even for all elements in the array, however using Math.floor as
suggested infers that Math.random will *never* return 1, or at least
that the index will never be evaluated to be the length of the
array.

Should that occur, the tip of the day will be 'undefined'.

The specification says that Math.random will return a value "greater
than or equal to 0 but less than 1" which means that in theory the
.floor method is OK, but is it in practice?


Apparently a now every old Opera version (I think it was 4 but it may
have been 5) had a buggy Math.random that did occasionally return 1. I
have not heard mention of any other javascript versions with the same
problem. Absolute safety can be guaranteed with - Math.random() % 1 -.

A faster alternative to Math.floor in this context could be an OR zero
operation:-

array.sT[((Math.random() *sT.length) | 0)]

As OR zero truncates numbers with fractional parts into integers. It
also restricts the possible range of those integers to 32 bit signed
integers, which is half of the specified possible range for Array
indexes (though that should not be a problem in most cases).

Richard.
Jul 23 '05 #8
JRS: In article <nG************ ****@twister.ny roc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang. javascript, Mick White
<mw***********@ rochester.rr.co m> posted :
Lasse Reichstein Nielsen wrote:
RobG <rg***@iinet.ne t.auau> writes:

document.write( sT[Math.round((sT. length-1)*Math.random( ))]);


...
is all that is required.

Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math .random() * sT.length)]

or:
sT[new Date()%sT.lengt h]


I think that the OP has a 5-element array.
Have you tried your method with 5 or 10 elements in the array?
Actually, AFAIK, it *might* work in XP, and *might* in non-PC; but I
don't expect it to in NT, and it does not in Win98.

Do any systems show a 1 ms resolution for X = new Date() ?

<FAQENTRY> :

I find that
(Math.random()* 10)|0
is appreciably faster than
Math.floor(Math .random()*10)
although the latter might be considered more readable.

If tests on other systems show similar results, ISTM that it would be
worth adding the former to FAQ 4.22, and taking the opportunity to
remark that |0 can beat Math.floor.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
Dr John Stockton wrote:
JRS: In article <nG************ ****@twister.ny roc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang. javascript, Mick White
<mw***********@ rochester.rr.co m> posted :
Lasse Reichstein Nielsen wrote:
RobG <rg***@iinet.ne t.auau> writes:

document.write( sT[Math.round((sT. length-1)*Math.random( ))]);

...
is all that is required.
Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math .random() * sT.length)]
or:
sT[new Date()%sT.lengt h]

I think that the OP has a 5-element array.
Have you tried your method with 5 or 10 elements in the array?
Actually, AFAIK, it *might* work in XP, and *might* in non-PC; but I
don't expect it to in NT, and it does not in Win98.

Well, John, new Date() is cast as a Number in a Modulus operation.

sT[new Date().getTime( )%sT.length] will force the conversion though, and
create equal distribution of the array entries. Since the datestamp is a
large dynamic number, its use is ideal in this scenario (one off).
I don't know why it wouldn't work in NT or Win98, please educate me.
Mick

Do any systems show a 1 ms resolution for X = new Date() ?
<FAQENTRY> :

I find that
(Math.random()* 10)|0
is appreciably faster than
Math.floor(Math .random()*10)
although the latter might be considered more readable.

If tests on other systems show similar results, ISTM that it would be
worth adding the former to FAQ 4.22, and taking the opportunity to
remark that |0 can beat Math.floor.

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2386
by: Chris Geerdink | last post by:
combo with PHP. what is wrong with the Javascript? else { include("mysql.php"); $query1 = mysql_query("INSERT INTO gbook (naam, email, text) VALUES ('".$_POST."', '".$_POST."', '".$_POST."')"); ?> <script language="JavaScript"> <!--
4
4060
by: asdf | last post by:
Hello! Can someone tell me whats wrong with this piece of code: Option Compare Database Option Explicit Sub retrieve() Dim rst As ADODB.Recordset Dim i As Integer
5
1978
by: Alexandre Martins | last post by:
Provider=Microsoft.Jet.OLEDB.4.0;UserId=Admin;Password=teste;Data Source=C:\Inetpub\wwwroot\inktoner\dados\db_inktoner.mdb;Persist Security Info=True I can't connect in my database ! whats wrong ?? tks
1
2455
by: aa | last post by:
When I am reading from local disk (d:), everithing is OK, but then I am reading from map disk I am geting the this error. Whats wrong. Thanks Server Error in '/Extra' Application. ---------------------------------------------------------------------------- ---- The specified user does not exist. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more...
3
2037
by: mahsa | last post by:
Hi do you know whats wrong with this code? <asp:HyperLink id="HLink_Help" runat="server" NavigateUrl='<%# "javascript:window.open('comments.aspx?id=1,width=500,height=600, scrollBars=yes');" %>'>Need Help?</asp:HyperLink> -- mahsa
1
2488
by: '~=_Slawek_=~' | last post by:
$DOW = (jddayofweek(unixtojd(mktime(1, 1, 1, $month, $day, $year)))+6)%7; $DOW= (jddayofweek(juliantojd($month, $day, $year))+6)%7; The results are supposed to be the same, but they are not. Whats wrong? Any clues?
7
2223
by: Mike Barnard | last post by:
It's a simple test... VERY SIMPLE. But... In an external stlyesheet some attributes don't show. With the same styles cut and pasted to the test internally it works as expected. Anyone tell me why? Its probably sooooooo obvious, but it is 1.19 am! Thanks. www.thunderin.co.uk/
0
1294
by: cuddles | last post by:
hi im using IBM DB2 version 8 i have a procedure that should delete an error log table DELETE FROM TABLE1.ERR_MSG_LOG WHERE DATE(CRT_S) < (CURRENT DATE - 30 DAYS); but i keep getting this error: A database manager error occurred. CLI0604E CallableStatement get*** method was called without calling execute. SQLSTATE=S1010
5
2312
by: islayer | last post by:
can someone tell me what is wrong with the bold code? i am just learning perl. the program should create a perl file with a random name (5 letters, followed by a number), but the name is always just the number. whats wrong with my code? #!/usr/bin/perl use Fcntl; @array = (a..z); srand; foreach (1..5) { $name = int(rand scalar(@array));
1
1436
by: x40 | last post by:
I try to learn python thru solving some interisting problem, found google trasure hunt, write first program ( but cant find whats wrong). # Unzip the archive, then process the resulting files to obtain a numeric result. You'll be taking the sum of lines from files matching a certain description, and multiplying those sums together to obtain a final result. Note that files have many different extensions, like '.pdf' and '.js', but all...
0
7991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8395
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
6719
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5850
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5438
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3898
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3939
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2412
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1250
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.