【问题标题】:What is the usage of typeof in javascript?javascript中typeof的用法是什么?
【发布时间】:2015-11-12 03:08:55
【问题描述】:

typeof 返回原始数据类型,但我不明白为什么在 javascript 中使用它?

【问题讨论】:

标签: javascript typeof


【解决方案1】:

我不明白为什么在 javascript 中使用它?

typeof用于

返回[s]原始数据

例如,如果我想知道某些东西是否未定义,我可以这样做

if (typeof object === 'undefined')

检查,因为如果它未定义,则没有数据类型(因为它是未定义的)。这通常是为什么typeof 将用于日志记录以外的原因,查看通过 ajax 接收的内容,或用于制作接受可以具有不同类型的参数的函数并使用 typeof 检查该类型等。

【讨论】:

  • 另一个原因是当你让你的函数接受不同的参数时。然后typeof 将允许您确定类型并采取相应措施
  • 最好这样做:if(object === undefined) 在尝试防止错误时将此条件放在范围的顶部。那是因为 if(typeof object === undefined) 如果这是您的目标,则不一定会分支。
  • +1 因为这是一个实际的代码示例。所有其他示例都没有显示if 语句中的基本用法...
【解决方案2】:

typeof 是一个一元运算符,放置在可以是任何类型的单个操作数之前。它的值是一个指定操作数类型的字符串。

   - x                             typeof x

   undefined                        "undefined"
   null                             "object"
   true or false                    "boolean"
   any number or NaN                "number"
   any string                       "string"
   any function                     "function"
   any non function native object   "object"

typeof 与除 null 之外的原始值一起工作得很好。typeof 无法区分 null 和 object,因为 null 是假的,而对象是真的。这里有 few case studies 可能有用。 typeof 对除 function 之外的所有对象和数组值计算为 object。typeof 如何处理函数可能超出了这个问题的范围。

希望这会对你有所帮助。

【讨论】:

    【解决方案3】:

    typeof 运算符返回一个表示操作数类型的字符串。我们可以通过以下方式使用它来检查值的类型:

    let nr = 5;
    
    if (typeof nr === 'number') {
      console.log('nr is number');
    }
    
    
    let str = 'hi';
    
    if (typeof str === 'string') {
      console.log('str is string');
    }

    当一个变量可以有多个值时,这尤其有用。例如,nullundefinednumber。在这种情况下,我们可以将typeof 运算符与if 语句结合使用,以便针对给定场景执行正确的代码。

    【讨论】:

      【解决方案4】:

      您可以使用 JavaScript typeof 运算符来查找 JavaScript 变量的类型。它还用于验证变量或输入。更好地解释 => http://www.w3schools.com/js/js_datatypes.asp 示例 typeof "John" // 返回字符串 typeof 3.14 // 返回数字 typeof false // 返回布尔类型 typeof [1,2,3,4] // 返回对象 typeof {name :'John', age:34} // 返回对象

      【讨论】:

        【解决方案5】:

        javascript中的typeof为什么要用?

        有时您可能需要检查变量中存储了哪些类型的数据,例如,typeof 是运算符而不是函数,它与停止执行函数并从该函数返回值的 return 语句完全不同.

        typeof 运算符返回一个字符串,指示未计算的操作数的类型。

        console.log(typeof 'name');
        // expected output: "string"
        console.log(typeof 74);
        // expected output: "number"
        console.log(typeof true);
        // expected output: "boolean"
        console.log(typeof declaredButUndefinedVariable);
        // expected output: "undefined";
        

        typeof MDN web docs

        typeof 运算符后面总是跟它的操作数:

        typeof UnaryExpression => 请记住括号是可选的,但请记住:括号对于确定表达式的数据类型非常有用。

        var data = 100;
        typeof data + ' Bye'; // return 'number Bye'
        typeof (data + 'Bye'); // return 'string'
        

        其他例子:

        // Numbers
        typeof 37 === 'number';
        typeof 3.14 === 'number';
        typeof(42) === 'number';
        typeof Math.LN2 === 'number';
        typeof Infinity === 'number';
        typeof NaN === 'number'; // Despite being "Not-A-Number"
        typeof Number('1') === 'number'; // Number tries to parse things into numbers
        
        
        // Strings
        typeof '' === 'string';
        typeof 'bla' === 'string';
        typeof `template literal` === 'string';
        typeof '1' === 'string'; // note that a number within a string is still typeof string
        typeof (typeof 1) === 'string'; // typeof always returns a string
        typeof String(1) === 'string'; // String converts anything into a string, safer than toString
        
        
        // Booleans
        typeof true === 'boolean';
        typeof false === 'boolean';
        typeof Boolean(1) === 'boolean'; // Boolean will convert values based on if they're truthy or falsy, equivalent to !!
        
        
        // Symbols
        typeof Symbol() === 'symbol'
        typeof Symbol('foo') === 'symbol'
        typeof Symbol.iterator === 'symbol'
        
        
        // Undefined
        typeof undefined === 'undefined';
        typeof declaredButUndefinedVariable === 'undefined';
        typeof undeclaredVariable === 'undefined'; 
        
        
        // Objects
        typeof {a: 1} === 'object';
        
        // use Array.isArray or Object.prototype.toString.call
        // to differentiate regular objects from arrays
        typeof [1, 2, 4] === 'object';
        
        typeof new Date() === 'object';
        typeof /regex/ === 'object'; // See Regular expressions section for historical results
        

        【讨论】:

          【解决方案6】:

          以下是一种常见的 hack 类型,但存在一些问题:

          const type = obj => Object.prototype.toString.call(obj);
          
          type("abc");// [object String]
          type(123);// [object Number]// What's with all the objects?
          type([]);// [object Array]
          type({});// [object Object]
          type(Object.create(null));// [object Object]
          type(-1/0);// [object Number] Not exactly a true number
          type(NaN);// [object Number] WTF?
          

          如您所见,它存在一些问题。它总是返回用括号括起来的两种类型,第一种总是一个“对象”。如果总是返回,这会使第一种类型的信息变得无用。其次,它的区别是有限的。它无法告诉我们对象是作为文字(普通)还是使用 Object.create() 创建的,这在调用时需要关键字“new”。它还错误地将无穷大和 NaN 称为数字。

          我希望分享一个更好的 typeof 函数来解决所有这些问题。它适用于所有原语,包括符号、异常(错误、未定义、null 和 NaN)、本机对象和函数的最常见情况(数组、映射、对象、函数、数学、日期、承诺等),以及甚至可以检测用户制作的对象(标识为 Plain)和 DOM 元素(标识为 HTML)。它应该适用于所有现代和较旧的浏览器。它被分解成几个功能,使代码更加用户友好:

          const isDOM = obj => (obj.nodeType && !isPlain(obj)) ? true : false;
          const isPlain = obj => obj ? obj.constructor === {}.constructor : false;
          const sanString = str => str.replace(/[^a-zA-Z ]/g, "");
          const isNaN = obj => (Object.is(obj, NaN) === true) ? true : false;
          
          function objType(obj){
          if(obj === undefined) return undefined;
          if(obj === Infinity) return Infinity;
          if(obj === -Infinity) return -Infinity;
          if(isDOM(obj)) return 'HTML';
          let str = Object.prototype.toString.call(obj);
          if(str === '[object Object]' && isPlain(obj)) return 'Plain';
          str = sanString(str).split(' ');
          if(str[1] === 'Number' && isNaN(obj)) return NaN;
          return str[1];}
          }
          

          这样使用:

          objType(null);// Null
          objType(undefined);// undefined
          objType("abc");// String
          objType(123);// Number
          objType([]);// Array
          objType({});// Plain not [object Object]
          objType(Object.create(null));// Object is what we want
          objType(document.body);// HTML
          objType(-1/0);// -Infinity
          objType(NaN);// NaN
          

          如果您发现任何错误或错误或有更好的解决方案(不是来自库或框架),请告诉我。我很乐意及时修复它。

          【讨论】:

          • objType({constructor:'',nodeType:true}) => "HTML"。真的吗?不太确定你想在这里做什么,但我不明白这如何回答当前的问题。请注意,不要检查类似的属性,例如要知道一个对象是否是一个节点,请调用object instanceof Node
          • 使用 typeof(document.body) 返回 [object HTMLBodyElement] 并且每个 DOM 元素都有自己的构造函数。我的 objType 将所有 DOM 分组为 HTML。当您希望在操作 DOM 以确保它实际生成 HTML 元素时检查代码时,这很有用。
          • 你没有明白我的意思......所以首先,typeof 是一个运算符,你不要把它当作一个函数来调用(不需要())。然后我的第一点是你的函数将返回'HTML'{constructor:'',nodeType:true},而它只是一个普通对象。这是因为您通过检查属性做错了。而且无论我如何看待您的代码在做什么(IMM,它只是一种让事情出错并编写更多内容的复杂方法),它绝对不能回答手头的问题。
          猜你喜欢
          • 2013-11-17
          • 1970-01-01
          • 2011-04-16
          • 2011-04-17
          • 1970-01-01
          • 1970-01-01
          • 2018-09-26
          • 2013-07-03
          • 1970-01-01
          相关资源
          最近更新 更多