Javascript map method on array of string elements

后端 未结 8 649
悲哀的现实
悲哀的现实 2021-01-11 10:09

I am trying to understand how to implement the map method (rather than using a for loop) to check a string for palindromes and return boolean values for whether the mapped a

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-11 10:56

    Apart from a few minor mistakes in your code, such as scope issues (you're referencing the "newArray" and "myArray" outside of the function in which they where defined, and therefore, getting "undefined")..

    The main issue you had is that you addressed the ENTIRE array inside the map function, while the whole concept is breaking things down to single elements (and then the function collects everything back to an array for you).

    I've used the "filter" function in my example, because it works in a similar manner and I felt that it does what you wanted, but you can change the "filter" to a "map" and see what happends.

    Cheers :)

    HTML:

    
    
    

    BLA

    BLA2

    Javascript:

    function palindromeChecker(string) {
      var myString = string.toLowerCase();
      var myArray = myString.split(" ");
      var newArray = myArray.filter(function (item) {
        var reversedItem = item.split('').reverse().join('');
        return  item == reversedItem;
    });
    
    document.getElementById("bla").innerHTML = myArray;
    document.getElementById("bla2").innerHTML = newArray;
    
    }
    
    palindromeChecker("What pop did dad Drink today");
    

提交回复
热议问题