【问题标题】:Finding variable types from a string从字符串中查找变量类型
【发布时间】:2020-11-07 01:42:25
【问题描述】:

如果这个问题已经得到解答,请原谅,但是我正在努力寻找任何答案。

我正在寻找是否可以在下面的代码中将变量类型转换为字符串。

input = prompt('Type something please', 'your input here')
alert(input + ' is a ' + typeof input)

即如果用户输入 1 typeof 将返回数字,或者如果用户输入 true 则返回布尔值

【问题讨论】:

  • 我猜你可以eval 输入,但是……用户输入的任何内容都定义为字符串。一个字符串可能可以被解释为其他类型,例如'1' 可以转换为1'true' 可以解释为true。但是,如何区分用户何时输入 string 'true',而不是布尔值?您可以要求 JSON 作为输入,JSON.parse() 它,'true' 表示布尔值 true'"true"' 表示字符串 'true'...
  • 这能回答你的问题吗? How to convert instance of any type to string?

标签: javascript string variables types typeof


【解决方案1】:

通常,每个示例的所有输入都将返回一个字符串,而不考虑他们输入或打算输入的内容。但是,我们可以构建一些逻辑来检查他们输入的内容是否是;字符串(仅限字母)或整数(仅限数字)或任何其他逻辑,您可以根据这些逻辑进行检查。

检查输入是否包含数字的最快方法之一;

isNaN(input)         // this returns true if the variable does NOT contain a valid number

eg.
isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

您可以尝试正则表达式(这并不总是理想的但有效)

var input = "123";

if(num.match(/^-{0,1}\d+$/)){
  //return true if positive or negative
}else if(num.match(/^\d+\.\d+$/)){
  //return true if float
}else{
  // return false neither worked
}

您也可以使用(typeof input),但如果您的用户要输入预期的条目集,这会更方便

var input = true;
alert(typeof input);
// This eg will return bolean

如果这有帮助,请告诉我。

【讨论】:

  • 谢谢!我也能够实现这个答案:)
  • 您可能想为我们投票和鼓掌。如果你明白我的意思,我们会感觉很好。 :D
【解决方案2】:

您可以通过一系列parseIntparseFloatparseBool 功能。

只要你得到一个有效的结果,就返回它。

类似于:

if (parseInt(input) != NaN) {
  return "int"
}
if (parseFloat(input) != NaN) {
  return "float"
}

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 2019-08-18
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多