首页 > 解决方案 > javascript中的isset等效项以查找回文

问题描述

我在 PHP 中创建了一个脚本来查找回文,但是当我尝试在 JavaScript 中执行相同操作时,它无法按预期工作。这不仅仅是检查反转的字符串是否匹配的问题,还必须检查字符串的任何顺序。

换句话说,“mom”应该返回为真,“mmo”应该返回为真,“omm”应该返回为真,等等......,这就是PHP脚本所做的,但下面的JS脚本甚至没有为字符串“妈妈”的第一次迭代工作

以下是 PHP 脚本:

<?php
function is_palindrom($str) {

$str_array = str_split($str);
$count = array();

foreach ($str_array as $key) {
  if(isset($count[$key])) {
    $count[$key]++;
  } else {
    $count[$key] = 1;
  }
}

$odd_counter = 0;
foreach ($count as $key => $val) {
  if(($val % 2) == 1) {
    $odd_counter++;
  }
}

return $odd_counter <= 1;
}

echo is_palindrom('mom') ? "true" : "false";

以下是我在JS中尝试过的:

var count = [];
var strArr = [];
var oddCounter = 0;

var foreach_1 = function(item, index) {
 console.log("count[index]: " + count[index]);
 if (typeof count[index] !== "undefined") {
  count[index]++;
 } else {
  count[index] = 1;
 }
};

var foreach_2 = function(item, index) {
console.log("item: " + item + " item % 2: " + eval(item % 2));
 if (eval(item % 2) == 1) {
  oddCounter++;
 }
 console.log("oddCounter: " + oddCounter);
 return oddCounter <= 1;
};

var isPalindrom = function(str) {
 strArr = str.split("");
 console.log(strArr);

 strArr.forEach(foreach_1);
 console.log(count);

 count.forEach(foreach_2);
};

我相信我尝试使用以下代码在 javascript 中复制 isset 失败了:

if (typeof count[index] !== "undefined") {

结果,我尝试编写自己的 isset 函数,但结果仍然相同,它不起作用:

 var isset = function(obj) {
  if (typeof obj === "undefined" || obj === null) {
    return false;
  } else {
    return true;
  }
};

调用以下函数:

  if (isset(count[index])) {
    count[index]++;
  } else {
    count[index] = 1;
  }

像往常一样,任何帮助将不胜感激并提前感谢

顺便说一句,我不记得对某事进行多次修订或迭代的词——我知道它以“re”开头

标签: javascriptphpisset

解决方案


我的尝试:

let p1 = `No 'x' in Nixon.`
let p2 = `Was it a car or a cat I saw?`
let p3 = `A man, a plan, a canal, Panama!`

function is_palindrome (str) {
  const normalize = str => str.replace(/[.,:;`'"!?\/#$%\^&\*{}=\-_~()\s]/g, '').toLowerCase()
  const reverse = str => [...str].reverse().join('')

  return normalize(str) === reverse(normalize(str))
    ? true
    : false
}

console.log(is_palindrome(p1))
console.log(is_palindrome(p2))
console.log(is_palindrome(p3))

推荐阅读