Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use typeof and switch cases in Javascript

Tags:

I'm having problems finding out what's wrong with the code below. I have consulted how to use typeof and switch cases, but I'm lost at this point. Thanks in advance for your advices.

// Write a function that uses switch statements on the // type of value. If it is a string, return 'str'. If it // is a number, return 'num'. If it is an object, return // 'obj'. If it is anything else, return 'other'. function detectType(value) {   switch (typeof value) {     case string:       return "str";     case number:       return "num";     default:       return "other";   } } 

------------- Update -----------------------------------

Turns out the problem comes from my mistake (or rather oversight) of not following the instructions properly. Thanks again for your help and comments!

like image 287
stanigator Avatar asked Jan 06 '12 06:01

stanigator


1 Answers

typeof returns a string, so it should be

function detectType(value) {   switch (typeof value) {     case 'string':       return "str";     case 'number':       return "num";     default:       return "other";   } } 
like image 138
qiao Avatar answered Sep 20 '22 13:09

qiao