确定返回值的类型

时间:2011-07-24 15:15:24

标签: javascript

我从一个总是字符串的函数中得到一个返回值。我使用了typeof(obj),结果总是string

Date.functionName=Date.prototype.functionName=function(dataObj) {
        //The dataObj is always string. 
            // How can i differentiate between the values... 
};

我有三件事要作为字符串......

  1. 日期
  2. String ...
  3. 整数值......
  4. 这三个都是string类型。

    1. 我如何区分这三个值。
    2. 使用Date.mycustomfunction是正确的......或者我应该使用一些 其他班......

2 个答案:

答案 0 :(得分:2)

您可以使用isNaN检查它是否为整数。对于isDate类型的功能,有一些有趣的想法here。此处的一些答案可能有所帮助:How can I determine whether a given string represents a date?

答案 1 :(得分:1)

我不确定使用的日期格式,因此您需要自己添加适当的正则表达式:

var integer = null ;

if(   isNaN(  ( integer = parseInt(string) )  )  ===   false   ) ... //!! integer String values
else {

    if(  ( /*regular expression for your date format*/ ).test(string)  ===  true  ) //!! date String values
    else //!! all other String values

}

顺便说一下,在JavaScript中添加到原生Objects被认为是不好的做法,因为它不如编写新的Objects那么可靠。