javascript - Why is the passed in value undefined when accessing the map method? -
when run snippet below in jsbin says capitalize won't work because property undefined. looked @ documentation , mentioned use of word 'this' not quite sure if applies here since string value passed in correct (console logged confirm). why capitalize method not apple work off map value?
class booktitle { constructor(title) { this.title = title; // creates object once, see top of jasmine file explanation } title() { return this._title; // retrieves title string } set title(title) { this._title = this.titlecreator(title); // calls method , sets title, see top of jasmine file explanation } titlecreator(string) { if (string == null){ return string; // catches first error } // note isn't meant fledged title creator, designed pass these specific tests var littlewords = ['and', 'do', 'the', 'a', 'an', 'in', 'of']; // these words don't want capitalize var modifiedstring = string .split(' ') // splits string array of words, breaks sentence .map(function(word,index) { if (index == 0) { return this.capitalize(word); // capitalize first word of string } else if (littlewords.indexof(word) == -1) { return this.capitalize(word); // capitalize words not little, -1 returned indexof if can't find word in array } else if (littlewords.indexof(word) >= 0) { return word; // not capitalize word in list of littlewords } }) .join(' '); // joins every element of array string space inbetween each value. created sentence array of words return modifiedstring; } capitalize(word) { return word.charat(0).touppercase() + word.slice(1); // function capitalizes word given } } let booktitles = new booktitle(); booktitles.title = 'inferno'; console.log(booktitles.title); // goal output inferno
the problem this
within map
refers function you're passing map
. use arrow function (word, index) => { ... }
instead , this
should fall through parent class.
var modifiedstring = string .split(' ') // splits string array of words, breaks sentence .map((word,index) => { // <-- arrow function if (index == 0) { return this.capitalize(word); // capitalize first word of string } else if (littlewords.indexof(word) == -1) { return this.capitalize(word); // capitalize words not little, -1 returned indexof if can't find word in array } else if (littlewords.indexof(word) >= 0) { return word; // not capitalize word in list of littlewords } }) .join(' ');
Comments
Post a Comment