在 Javascript 中获取字符串中的最后一个符号时值错误

Wrong value while getting last symbol in string in Javascript

本文关键字:符号 最后一个 错误 Javascript 获取 字符串      更新时间:2023-09-26

我有一个变量 someText 存储数字。根据最后一个数字,我需要添加不同的文本。所以我将一些文本转换为搅拌,在 someTextLng 中获取字符串长度,并减去最后一个符号 someTextLng 在我的示例中document.write(lastChar + "<br/>");返回 7 - 一切正常。继续 if 并得到惊喜 - lastChar = 1。但是为什么?我的错误在哪里?

<script type="text/javascript">
var someText =  312347;
someText= someText.toString();
someTextLng = someText.length-1;
var lastChar = someText.substr(someTextLng, 1);
document.write(lastChar + "<br/>");
if (lastChar = "1") {
document.write(lastChar+"&nbsp;Day")
}
else if (lastChar = "2") {
document.write(lastChar+"&nbsp;DayZ")
}
else {
alert ("Wuza");
}
</script>

为什么不使用提醒运算符%作为最后一个数字?

var last = number % 10;

及以后

if (last === 1) {
    // do something
}
你需要

使用==来匹配lastChar的值。要获取最后一个字符,您可以使用提醒运算符:

var lastChar = someText % 10;
if (lastChar == 1) {
    document.write(lastChar+"&nbsp;Day")
}
else if (lastChar == 2) {
    document.write(lastChar+"&nbsp;DayZ")
}
else {
    alert ("Wuza");
}

如果你想检查的东西等于其他东西,它===不是=

你的代码应该是这样的

if (lastChar === "1") {
  document.write(lastChar+"&nbsp;Day")
}
else if (lastChar === "2") {
  document.write(lastChar+"&nbsp;DayZ")
}
else {
  alert ("Wuza");
}

:)

var someText =  312347;
someText= someText.toString();
someTextLng = someText.length-1;
var lastChar = someText.substr(someTextLng, 1);
console.log(lastChar + "<br/>");
if (lastChar == "1") {
   console.log(lastChar+"&nbsp;Day")
}
else if (lastChar == "2") {
   console.log(lastChar+"&nbsp;DayZ")
}
else {
   alert ("Wuza");
}

试试这个

<script type="text/javascript">
var lastChar =  (312347 % 10).toString;
document.write(lastChar + "<br/>");
if (lastChar === "1") {
  document.write(lastChar+"&nbsp;Day")
} else if (lastChar === "2") {
  document.write(lastChar+"&nbsp;DayZ")
} else {
  alert ("Wuza");
}
</script>