Javascript:回文功能? [英] Javascript: palindrome function?

查看:52
本文介绍了Javascript:回文功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的单词触发器的工作代码:

I have working code for a simple word flipper:

var strFlip = function(str) {
    return str.split(" ").map(function(word) {
        return word.split("").reverse().join("");
    }).join(" ");    
};

console.log(strFlip("This is designed to swap the letter order of each word in the string"));

// "sihT si dengised ot paws eht rettel redro fo hcae drow ni eht gnirts"

我想添加一个if/else,以使该代码现在可以识别字符串中的每个单词是否都是回文(拼写相同的正反表达式:hannah).

I want to add an if/else to allow this code to now identify if each word in a string is a palindrome (spelled the same forward and backward ex: hannah).

所以我尝试通过以下方式继续.map()逻辑:

So I tried continuing the .map() logic with:

var strFlip = function(str) {
  return str.split(" ").map(function(word) {
    return word.split("").reverse().join("");
      }).join(" ").toLowerCase().map(function(test) {
    if (test.split(" ") === word){
      return true;
    }else{
      return false;
    }
  }
   );
};

console.log(strFlip("Hannah loves her racecar"));

但是....毫不奇怪的是,它返回一个错误,基本上表明 if 部分之前的长链接函数本身不是一个函数:

BUT.... unsurprisingly, it returns an error essentially stating that the long linked collection of functions before the if section is not itself a function:

TypeError:str.split(...).map(...).join(...).toLowerCase(...).map不是函数

尝试匹配所有花括号时,我也迷失了方向,但我想我都懂了.

I was also getting lost trying to match all of the curly braces, but I think I got them all.

那么,是否可以在其中添加if/else?

So, is it possible to add the if/else within?

推荐答案

.join(").toLowerCase()返回字符串,而不是数组.错误指出'some string'.map 不是函数,因为它是 undefined .

.join(" ").toLowerCase() returns a string, not an array. The error is stating that 'some string'.map is not a function because it's undefined.

如果您想要的是一个数组,该数组指示索引处的单词是否是回文,那么...

If what you want is an array that indicates whether a word at an index is a palindrome then...

var sentence = 'Eve drives a racecar',
        words = sentence.split(" ").map(function(word) {
                    var isPalindrome = word.length > 1 && (word.toLowerCase() === word.toLowerCase().split("").reverse().join(""));
                    return { text: word, isPalindrome: isPalindrome };
                });
    alert(JSON.stringify(words));

这篇关于Javascript:回文功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆