-
Okay... let's play following the bouncing ball.
Code:
<div id='blueBall'>
Blue Ball
</div>
<div id='blueBall'>
Blue Ball
</div>
<div id='redBall'>
Red Ball
</div>
<input id='ballCount'>
<script language='JavaScript'>
function CountBall(ball) {
document.ballCount.value = ball.length;
}
</script>
<a href='javascript:void()' onclick='CountBall(blueBall)'>Count the Blue Ones</a>
<a href='javascript:void()' onclick='CountBall(redBall)'>Count the Red Ones</a>
Now, it counts 2 for the the blue balls but says undefined for the red ones.
Feces throwing monkeys.
-
Not an array of objects
The id='redBall', as there is only one, cannot be an array, so you cannot use the array length property.
Do a work around....
Code:
<script language='JavaScript'>
function CountBall(ball)
{
var temp = ball.length;
if (temp > 1)
{
ballCount.value = temp;
}
else
{
ballCount.value = "1"
}
}
</script>
If you call the function for an object which doesn't exist then you will have to add a handler. :cool:
-
Yes, I have to work around a flaw in the language. It is an array of length 1.
-
I don't think that is a flaw. I think it makes sense and is supposed to be that way.
-
It opens up problems when you start to dynamicly add or remove elements in a document. Lets say you had two red balls, but you removed one. Are you comfortable with what once was an array 2 becoming a scalar? I'm of the mind set that it is still an array. It is now length one. There is no need to do the extra backend work of converting it from an array to a scalar as though we are cleaning up anything, and there is no need to require more traps in the programming to catch the incidents were we do have an array of one.
I haven't worked with Java, yet, and I can't think of an object model in C++ to equate this to. I would wager that those languages would take the array 1 approach. I'm sure PHP does, but it is more loosely typed than JavaScript, so that is a bad example.
And it is not necessarily a flaw in JavaScript. It may just be a flaw in the document object model. I don't see any advantage in it.