Get the name of an object's type

前端 未结 20 2713
忘掉有多难
忘掉有多难 2020-11-21 22:37

Is there a JavaScript equivalent of Java\'s class.getName()?

20条回答
  •  庸人自扰
    2020-11-21 22:54

    You should use somevar.constructor.name like a:

        
        const getVariableType = a => a.constructor.name.toLowerCase();
    
        const d = new Date();
        const res1 = getVariableType(d); // 'date'
        const num = 5;
        const res2 = getVariableType(num); // 'number'
        const fn = () => {};
        const res3 = getVariableType(fn); // 'function'
    
        console.log(res1); // 'date'
        console.log(res2); // 'number'
        console.log(res3); // 'function'

提交回复
热议问题