在 javascript 中设置等效项以查找回文

isset equivalent in javascript to find palindrome

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

换句话说,"mom"应该return为真,"mmo"应该return为真,"omm"应该return为真等...,这就是 PHP 脚本所做的,但下面的 JS 脚本甚至不适用于字符串 "mom"

的第一次迭代

以下是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"

开头

我的尝试:

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))

首先,感谢大家的评论。

其次,我 运行 在 PHP 文件中的计数数组上 var_dump 结果是这样的:

array (size=2)
'm' => int 2
'o' => int 1

这让我明白 js 中的计数必须是这项工作的对象,我必须根据输入的字符串创建对象的索引。

一件事导致另一件事,并且完全重写,但它与拼写检查器一起工作 - 请参阅底部的 link 以获取完整代码:

var count = {};
var strArr = [];
var oddCounter = 0;
var objKeys = [];
var splitString;
var reverseArray;
var joinArray;
var url = "test-spelling.php";
var someRes = "";

var mForN = function(obj, strArr) {
  for (var y = 0; y < strArr.length; y++) {
    // console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
    if (isset(obj[strArr[y]])) {
      obj[strArr[y]]++;
    } else {
      obj[strArr[y]] = 1;
    }
  }
  return obj;
};

var mForN_2 = function(obj, objKeys) {
  for (var z = 0; z < objKeys.length; z++) {
    /* console.log(
      "obj[objKeys[z]]: " +
        obj[objKeys[z]] +
        " obj[objKeys[z]] % 2: " +
        eval(obj[objKeys[z]] % 2)
    ); */
    if (eval(obj[objKeys[z]] % 2) == 1) {
      oddCounter++;
    }
    // console.log("oddCounter: " + oddCounter);
  }

  return oddCounter <= 1;
};

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

var isPalindrom = function(str) {
  // reverse original string
  splitString = str.split("");
  reverseArray = splitString.reverse();
  joinArray = reverseArray.join("");

  var checking = checkSpellingOfStr(str);

  if (str == joinArray) {
    strArr = str.split("");
    // console.log("strArr: " + strArr);

    objKeys = makeObjKeys(count, strArr);
    // console.log("filled count before mForN: " + JSON.stringify(count));

    // create array of keys in the count object
    objKeys = Object.keys(count);
    // console.log("objKeys: " + objKeys);

    count = mForN(count, strArr);
    // console.log("count after mForN: " + JSON.stringify(count));

    return mForN_2(count, objKeys);
  } else {
    return 0;
  }
};

var makeObjKeys = function(obj, arr) {
  for (var x = 0; x < arr.length; x++) {
    obj[arr[x]] = null;
  }
  return obj;
};

var checkSpellingOfStr = function(someStr) {
  var formData = {
    someWord: someStr
  };

  $.ajax({
    type: "GET",
    url: url,
    data: formData,
    success: function(result) {
      if (!$.trim(result)) {
      } else {
        console.log(result);
        $("#checkSpelling").html(result);
      }
    }
  });
};

通过以下调用开始一切:

isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";

在我的例子中,我有一个表单,我按如下方式监听按钮点击:

var palindromeTxt = document.getElementById("palindromeTxt").value;
var btn = document.getElementById("button");
btn.addEventListener("click", function (event) {
  isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
});

以下是拼写检查的php:

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);

if(!empty($_REQUEST['someWord']))
{
    $someWord = $_REQUEST['someWord'];
}

$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, $someWord)) {
  echo trim($someWord) . " is a recognized word in the English language";
} else {
  echo "Your word is either misspelled or that is not a recognized word";
}

您需要在您的服务器上安装 pspell,并在您的 php.ini

中添加扩展名=pspell.so

这就是我所做的,在我的 mac 本地获取 运行:

cd /Users/username/Downloads/php-5.6.2/ext/pspell 

/usr/local/bin/phpize

./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/

make

cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226

sudo apachectl restart

check your phpinfo file and you should see the following:

pspell
PSpell Support  enabled

Live example