[JavaScript] Funkcja korzystająca z instrukcji switch

bazilazi
Użytkownik
Użytkownik
Posty: 23
Rejestracja: 13 cze 2010, o 10:49
Płeć: Mężczyzna
Podziękował: 7 razy

[JavaScript] Funkcja korzystająca z instrukcji switch

Post autor: bazilazi »

Nie wiem jak połączyć switch z funkcją. Stworzyłem coś takiego, a dokładniej uzupełniłem funkcję i instrukcję switch jednak coś jest źle. Nie mam pomysłu w jaki sposób porównać wartości instrukcji switch w funkcji detectType.
Proszę o pomoc.

Kod: Zaznacz cały

// Example switch statement. typeof returns the type
// of the value as a string. For example, the type of
// a string is 'string', the type of a number is
// 'number', and the type of an object is 'object'.
switch (typeof 'foo') {
      case 'string':
    // some code
    // If you don't return in the block, you should
    // always have a break afterwards.
    break;
      case 'number':
    break;
      case 'object':
    break;
  default:
    //block
}

// 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(str, num, obj, other) {
  if(typeof === 'string'){
    return str;
  }
  else if(typeof === 'number'){
    return num;
  }
  else if(typeof === 'object'){
    return obj;
  }
  else{
    return other;
  }
}
abc666

[JavaScript] Funkcja korzystająca z instrukcji switch

Post autor: abc666 »

typeof jest operatorem, więc zapis
typeof === 'coś' jest bez sensu, powinieneś mieć
typeof obiekt === 'coś'

Co do samej funkcji to wg polecenia powinna ona wyglądać tak

Kod: Zaznacz cały

function detectType(obj) {
    switch(typeof obj) {
        case 'string': return 'str';
        case 'number': return 'num';
        [...]
    }
}
Zauważ, że można zrezygnować z break-ów ponieważ mamy w każdym przypadku instrukcję return
ODPOWIEDZ