1

I still working on a jQuery script that output under the Ckeditor the list of the most repeated words. Is not a keywords density but just a list of words and their repeats, excluding stop words both in english and Italian, plus some html clean-out. Is based on Bootstrap, jQuery and Ckeditor.

I've made this JSFiddle example that works good: https://jsfiddle.net/wzh7c42f/

the problem is if I wrote in any position inside a text in textarea the word "map" the function KeyDensityShow raise an error, and to be precise in the line

word_counts[positions[word]][1]++

I've not found a solution or why it give an error. If someone could help out to find the reason and provide a fix or a better optimization I will be very grateful.

ty in advance


EDIT:

Using the provided solution i fixed my code and works perfectly. this is the functional version on JSFiddle: https://jsfiddle.net/09m7c2hw/

Hart
  • 186
  • 2
  • 12

1 Answers1

2

The error happens because you're comparing the type of the key array to undefined, which is not wrong (as we already saw here):

if (typeof positions[word] == 'undefined') {

However, it fails when the key name is a reserved word (like map - a valid JavaScript function), because it'll always return the function itself, even if it's not present into the array.

Solution:

Change the snipet to the following:

if (!positions.hasOwnProperty(word)) {
    positions[word] = word_counts.length;
    word_counts.push([word, 1]);
} else {
    word_counts[positions[word]][1]++;
}

From the docs:

This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

Community
  • 1
  • 1
diogo
  • 3,769
  • 1
  • 24
  • 30
  • thank you so much, i suspected that was that kind of error. The solutionyou provided is perfect i've updated the main post to leave the new JSFiddle code for future use. – Hart Dec 23 '16 at 20:46