Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

charAt is not a function

Tags:

javascript

I'm trying to create a key mapping that keeps track of the frequency for each character of a string in my createArrayMap() function but I keep getting this error from firebug: TypeError: str.charAt(...) is not a function

I found the charAt() function on Mozilla's developer website it should be a function that exists.

var input;
var container;
var str;
var arrMapKey = [];
var arrMapValue = [];


function initDocElements() {

    container = document.getElementById("container");
    input = document.getElementById("inputbox");

}

function createArrayMap() {
    str = input.value;
    for (var i = 0; i < str.length; i++) {
        if (arrMapKey.find(str.charAt(i)) == undefined) {
            arrMapKey.push(str.charAt(i));
            arrMapValue.push(1);
        }
    }
}

function keyPressHandler() {
    createArrayMap();
    console.log(arrMapKey);
    console.log(arrMapValue);
}

function prepareEventHandlers() {
    input.onfocus = function() {
        if (this.value == "Start typing here!") {
            this.value = "";
        }
    };
    input.onblur = function() {
        if (this.value == "") {
            this.value = "Start typing here!";
        }
    };
    input.onkeyup = keyPressHandler;
}

window.onload = function() {
    initDocElements();
    prepareEventHandlers();
};
like image 462
xavier Avatar asked Jan 18 '14 23:01

xavier


People also ask

What is charAt function?

The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

What is a use of charAt () of string object in Javascript?

The charAt() method returns the character at a specified index (position) in a string.

Does charAt return a string or a char?

The charAt() method in Java returns the char value of a character in a string at a given or specified index.

What can we use instead of charAt in Java?

Just use Array. from to turn the string into an array.


1 Answers

The problem is not with String.charAt(), but with Array.find().

The first argument to find is a callback, but the result of str.charAt(i) is a character and not a callback function.

To search for an element in your array, you could use Array.indexOf() as @adeneo already suggested in a comment

function createArrayMap() {
    var str = input.value;
    for (var i = 0; i < str.length; i++) {
        if (arrMapKey.indexOf(str.charAt(i)) == -1) {
            arrMapKey.push(str.charAt(i));
            arrMapValue.push(1);
        }
    }
}

See JSFiddle

like image 74
Olaf Dietsche Avatar answered Oct 11 '22 00:10

Olaf Dietsche