我无法让它作为 JavaScript 函数工作(我在控制台时得到我想要的返回值.log但我不能将其作为函数调用)

I can't get this to work as a JavaScript function (I get the return value I want when I console.log this but I can't call it as a function)

本文关键字:返回值 我想要 log 函数调用 不能 控制台 JavaScript 函数 工作      更新时间:2023-09-26

我正在尝试将其用作函数,我可以在任何字符串上作为函数调用,以获取返回值 true 并使用 .map 以数组形式false语句 -

我了解.map的工作原理,并且可以在console.log(lastArray)时让它在new array中返回我想要的值,但我无法让它作为我可以调用字符串lastArray(dirtyString)finalArray("the cat pop racecar blue")并得到[false, false, true, true, false]的函数工作。我不能使用任何循环,必须使用.map(但我已经解决了这些问题,因为console.log-ing finalArray为我返回一个新的正确值数组......我只是看不到我做错了什么,当我尝试重新工作时,我得到了Undefined。我想保持我已有的方法,我只是不知道为什么它不能作为我可以调用的功能(我已经做了几个小时的在线研究,并且已经为此工作了好几天)。另外,对不起,我的代码太混乱了,有时是多余的,而且评论很多(我刚刚尝试了很多方法试图让它工作,我对CS和JS有点陌生)。此外,当尝试对字符串调用函数时,它还会返回错误。这是我的代码:

    /* split string into array of substrings, clean out extra spaces, return new array of substrings */ 
    var dirtyString = ("stash and pop on this level");

    var cleanArray = function(dirtyString){
      var splitString = dirtyString.split(" ");
      var cleanArray = splitString.filter(Boolean);
      return cleanArray;
    };
    var newArray = cleanArray(dirtyString);
    /* take each element of the array, if it's a palindrome, add a true element to new array using map; if it's not, add a false element to the new array... using map */
    ///helper function that returns correct value when I console.log it///
    var lastArray = newArray.map(function(x) {
      if (x === x.split("").reverse().join("")){
        return true;}
        else {
          return false;}
        });
  */attempting to put the logic in lastArray into a function I can call /*  
    var palindromicMap = function (dirtyString) {
      var cleanedArray = cleanArray(dirtyString);
      var output = cleanedArray.map(function(x){
        if (x === x.split("").reverse().join("")){
          return true;}
        else if (x !== x.split("").reverse().join("")){
          return false;}
      });
      return output;
    };
    console.log(lastArray);
*/returns correct outcome /*
    palidromicMap(cleanArray);
*/returns error /*
palindromicMap("cat pop racecar blue");
*/returns error/*

在这里查看这个 jsfiddle。该函数将字符串作为参数,但你为其提供了函数,从而导致误导性错误消息。

基本上将调用更改为

console.log(palindromicMap(dirtyString));

似乎解决了问题。

相关文章: