【问题标题】:Using charAt with number in Javascript在Javascript中使用带有数字的charAt
【发布时间】:2019-05-27 14:36:06
【问题描述】:

我想为我的语句设置一些索引并检查它是否找到我找到了这个方法 charAt 但它只适用于字符串,所以如何用数字处理这些

if (mobileNumber) {
        let j = mobileNumber.charAt(2);
        let w = mobileNumber.charAt(0);
        alert("@", w, j)
        if (j === 9) { //Not work quz it's a number
          alert("FoundJ", j)
          return;
        } else if (w === 6) { //Not work quz it's a number
          alert("FoundW", w)
          return
        } else{
           alert("sorry, App does not work in your city right now")
           return
          }

更新

现在我处理索引但我对它们有一些问题这是我的声明 如果我写下数字并且它包含 9 || 6 in the (2)index 我在调用函数时看到了警报我不知道为什么?

 let j = mobileNumber.toString().charAt(2);
      if (mobileNumber.length <= 0) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, write your Mobile Number"
          })
        );
        return;
      } else if (mobileNumber.length < 10) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid:
              "• Your Mobile Number must be exactly 10 characters!"
          })
        );
        return;
      } else if (regNumber.test(mobileNumber) === false) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, Your mobile must be a number"
          })
        );
        return;
      }
      else if (j != 9 || j != 6) { // i think the issue with **OR** 
        alert("sorry not work in your city yet!")
        return;
      }
 else {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: ""
          })
        );
      }

【问题讨论】:

  • j === "9" ? ...
  • 对不起,再检查一下
  • 要么 j === '9' 要么 parseInt(j, 10) === 9 与 w 相同
  • 很遗憾,我不太了解你

标签: javascript reactjs react-native ecmascript-6 numbers


【解决方案1】:

首先使用toString()将数字转换为字符串,然后使用charAt(index)

var mobileNumber = 98812345;
console.log(mobileNumber.toString().charAt(1));

【讨论】:

  • 你能再检查一遍Q吗?
【解决方案2】:

之前只需将它们转换为字符串:

if (mobileNumber) {
   let j = mobileNumber.toString().charAt(2);
   let w = mobileNumber.toString().charAt(0);
}

如果您需要它们作为数字,只需将它们解析回来:

let jNumber = parseInt(j, 10);

【讨论】:

  • 你能再检查一遍Q吗?
【解决方案3】:

=== 执行精确比较而无需转换类型(据我所知)

如果你有一个数值表达式,你可以将它转换成字符串,然后使用 charAt() 进行比较

function findJW(mobileNumber) {
    console.log("Checking "+ mobileNumber)
    let str = mobileNumber.toString();
    let j = str.charAt(2);
    let w = str.charAt(0);
  
    if (j == '9') {
       console.log("FoundJ", j)
    } else if (w == '6') {
      console.log("FoundW", w)
    } else{
      console.log("sorry, App does not work in your city right now")
    }
}

findJW(12954678)
findJW(62354678)
findJW(11111111)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多