前端随机问答(二)

2019-06-14  本文已影响0人  沃夫_

Q:判断数据类型的几种方法

type value
基本类型 string、number、boolean、undefined、null
引用类型 Object

typeof

typeof ''  // string
typeof 123  // "number"
typeof false  // "boolean"
typeof abc  // "undefined"
typeof null  // "object"
typeof {}    // "object"
typeof []  // "object"
typeof function(){}  // "function"

constructor

var a = ''; a.constructor === String;  //  true
var a = 123; a.constructor === Number;  //  true
var a = false; a.constructor === Boolean;  //  true
([]).constructor === Array;  //  true
({}).constructor === Object;  //  true
(function(){}).constructor === Function;  //  true
(()=>{}).constructor === Function;  //  true
// 如果声明的变量值未定义(undefined)或者值为null,则会提示类型错误,Uncaught TypeError: Cannot read property 'contructor' of undefined (或null)

Object.prototype.toString.call()

function wt_type(o) {
  return Object.prototype.toString.call(o);
  // return Object.prototype.toString.call(o).match(/\[object (\S*)\]/)[1].toLowerCase();  //  转成小写字符类型
}
wt_type('123') === '[object String]';  //  true
wt_type(123) === '[object Number]';  //  true
wt_type(false) === '[object Boolean]';  //  true
wt_type() === '[object Undefined]';  //  true
wt_type(null) === '[object Null]';  //  true
wt_type(()=>{}) === '[object Function]';  //  true
wt_type(Symbol)  === "[object Function]";  // true
Array.isArray([1,2,3])  // true

Q:如何规避在严格模式下,ES6函数新特性造成的报错?

const doSomeTh = (function(){
  'use strict'
  return function({a,b}){
    console.log(a,b)
  }
})();
// doSth.js
'use strict'
function add({a,b}){
  console.log(a+b)
}

未完待续。。。

上一篇 下一篇

猜你喜欢

热点阅读