0

I've tried to find answer to my question but i couldn't find and that's why I'm here, so question is - why I'm getting "TypeError: arr.coincidenсe not a function" when I'm trying to launch this code

 var arr = [0, 2, 3, 3, 3, 4, 5, 6, 6];
 alert(arr.occurencesCount(0)); // 1

 Array.prototype.occurencesCount = function (value) {
     var count = 0;
     for (var i=0;i<this.length;i++){
         if (value===this[i]){
             count++;
         }
     }
     return count;
 }

It should count how many times some value repeating in code, but somewhere is mistake and I can't find it. Please, help, thanks.

Andrew Still
  • 57
  • 1
  • 10
  • 2
    You need to use your function *after* defining it. – Jeto Mar 04 '18 at 19:01
  • Please see [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – str Mar 04 '18 at 19:02
  • I know why it's bad practice but it's just a task that i shoud do ) it's not work ) – Andrew Still Mar 04 '18 at 19:04

1 Answers1

1

In JavaScript the order of declaration can matter. Make sure you call your function AFTER you have assigned it to the prototype.

 var arr = [0, 2, 3, 3, 3, 4, 5, 6, 6];

 Array.prototype.occurencesCount = function (value) {
     var count = 0;
     for (var i=0;i<this.length;i++){
         if (value===this[i]){
             count++;
         }
     }
     return count;
 }

 alert(arr.occurencesCount(0)); // 1
jens
  • 2,075
  • 10
  • 15