【问题标题】:How to split value in javascript?如何在javascript中拆分值?
【发布时间】:2019-03-18 16:01:01
【问题描述】:

这里我有一个月对象在这个月对象里面的值1,2,3,4,5 并且选择的经验值是04(见控制台)所以想找到值,我比较两者但我没有定义因为4 and 04 not matched 如何匹配他们 ?

console.log(selectedExperience.from.split('/')[0])) // 04

console.log(months) // [ { value : 1, name: "one"}
                          { value: 2, name: "two" }
                          { value: 4, name: "four" } ]

console.log(months.find(month => month.value === selectedExperience.from.split('/')[0])); // undefined

【问题讨论】:

  • 最好的办法是在“04”字符串上使用 parseInt。例如parseInt(selExp.from.split("/")[0], 10) 将产生数字 4
  • split 方法返回一个字符串,并且由于您将“===”与一个 INT 值进行比较,因此您的查找不会返回任何内容
  • @DDD 你能不能别再要求人们支持你的问题了?我不确定它是否完全酷,而且肯定很烦人。如果人们想支持你的问题,他们会的。随它去吧。
  • @Pierce 好的,谢谢你说得对

标签: javascript arrays object javascript-objects


【解决方案1】:

如何将其转换为int

console.log(months.find(month => month.value === parseInt(selectedExperience.from.split('/')[0])));

【讨论】:

  • 我的错!我想把它写在这个问题上!
【解决方案2】:

您可以使用parseInt

month.value === parseInt(selectedExperience.from.split('/')[0]) 

console.log(parseInt('04') === 4)

【讨论】:

    【解决方案3】:

    使用Number,这样你比较的是数字而不是字符串:

    Number(month.value) === Number(selectedExperience.from.split('/')[0])
    

    【讨论】:

      【解决方案4】:

      尝试使用“+”运算符将字符串转换为数字:

      var test = "04";
      console.log(test); //04
      console.log(+test); //4
      
      console.log(months.find(month => month.value === +selectedExperience.from.split('/')[0]));
      

      【讨论】:

        【解决方案5】:

        假设04 是一个字符串,做一个parseInt 或在比较之前将其转换为数字,否则使用一元运算符

        console.log(selectedExperience.from.split('/')[0])) // 04
        let exp = parseInt(selectedExperience.from.split('/')[0],10)
        
        console.log(months)  // [ { value : 1, name: "one"}
                             //   { value: 2, name: "two" }
                             //   { value: 4, name: "four" }] 
        
        console.log(months.find(month => month.value ===exp  ))
        

        【讨论】:

          【解决方案6】:

          .split() 将返回一个字符串数组。因此,要与整数进行比较,您需要使用parseInt 对其进行解析。

          var test = "04/12";
          var months = [{
              value: 1,
              name: "one"
            },
            {
              value: 2,
              name: "two"
            },
            {
              value: 4,
              name: "four"
            }
          ];
          
          console.log(test.split('/')[0]);
          console.log(months);
          
          console.log(months.find(month => month.value === parseInt(test.split('/')[0])));

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-01-02
            • 1970-01-01
            • 2013-09-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多