javascript中的isset等效项以找到回文

时间:2018-11-07 06:27:39

标签: javascript php isset

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

换句话说,“ mom”应返回为真,“ mmo”应返回为真,“ omm”应返回为真,依此类推……,这是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”

2 个答案:

答案 0 :(得分:-1)

我的尝试

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

答案 1 :(得分:-1)

首先,谢谢您的所有评论。

第二,我在PHP文件中的count数组上运行了一个var_dump,结果如下:

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

这使我明白js中的count必须是该工作的对象,并且我必须根据输入的字符串为该对象创建索引。

一件事导致另一件事,并且需要完全重写,但是它与拼写检查器一起工作-参见底部链接以获取完整代码:

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,以及将extension = pspell.so添加到php.ini

这就是我所做的,以使其在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