Click to See Complete Forum and Search --> : Count number of items in an array


Arc
06-27-2003, 04:48 PM
Hi there, I've done searches on this site and on goolge and can't find an answer to this.

I have this code


function checklength() {
var words = document.form.entry.value;
var wordsarray = words.split(" ");
var numwords = count(wordsarray);
alert("Your message is "+numwords+" long.");
}


but it isn't working... is the count function supposed to be used to count the number of items in the array?

Thanks!:D

Jona
06-27-2003, 04:51 PM
Since count() is not a function, the code will not work.

[J]ona

Arc
06-27-2003, 04:52 PM
ok, so what is the function to count the elements in an array?

Jona
06-27-2003, 04:54 PM
Untested code:


function count(arrayObj){return arrayObj.length;}


[J]ona

Arc
06-27-2003, 05:05 PM
array.length worked.
Thanks!:D

Jona
06-27-2003, 05:07 PM
You're welcome.

[J]ona

Charles
06-27-2003, 05:10 PM
If you would look at my other post where I've answered your question not more than a few minutes ago youwould note that Array.length gives you the number of items in an array.

And your function will count leading, trailling and multiple spaces as separate words. This method will correct for that:

<script type="text/javascript">
<!--
String.prototype.wordCount = function () {return this.replace(/^\s+/, '').replace(/\s$/, '').split(/\s+/).length}
// -->
</script>

<textarea onchange="if (this.value.wordCount() > 100) {alert (['Please limit yourself to 100 words. You see to have', this.value.wordCount(), 'of the little buggers there.'].join(' ')); this.focus()}"></textarea>

Of course, this method will still count " one&nbsp;,&nbsp;two " as three words. My other method is much beter.