Always include a doctype: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-or- <!doctype html> (...the must easier HTML5>
<script type="text/javascript"> not <script language="javascript">
and put your javascript in the head section unless you have a GOOD reason to put it in the body
You have declared Nom as a global array, so you don't need to parse it into the function and since Nom is global, you don't need the showName function
Format you code a little better, you will find it's easier to read and debug
Code:
<!doctype html>
<html>
<head><title>Untitled Document</title>
<script type="text/javascript">
var Nom = ["Justin","Michel","Pascal"]; // an easy way to create and populate an array
function addName() {
var name = prompt('Enter a name',''); // Check your documentation to see how 'prompt' is used
Nom.push(name);
}
function showName() {
return Nom;
}
addName(); // Parse the array into the function
alert(Nom); // Spelling!!
alert(showName()); // -or- if you must
</script>
</head>
<body>
</body>
</html>
By mistake, DFORMS reached an interesting basic referential issue of JavaScript. I have simplified a part of his code like that:
Code:
var Nom = ['Justin','Michel','Pascal'];
var tbl=Nom;
tbl.push('Phillipe');
alert(Nom) // alerts: "Justin,Michel,Pascal,Philipe"
That happens because the variable tbl gets a reference value, not a primitive value. That assignment var tbl=Nom set a reference, thus from now on, all the changes made in the reference (tbl) will be reflected in the main object (Nom)
DFORMS might have thought that on using var tbl=Nom he can create another, independent, array, but he was wrong. From this point of view, a reference of the object is that object.
Bookmarks