Click to See Complete Forum and Search --> : Count number of items in an array
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
Since count() is not a function, the code will not work.
[J]ona
ok, so what is the function to count the elements in an array?
Untested code:
function count(arrayObj){return arrayObj.length;}
[J]ona
array.length worked.
Thanks!:D
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 , two " as three words. My other method is much beter.