LoginSignup
8
7

More than 5 years have passed since last update.

もしぼくが「それ、もっとスマートに書けるよ」を書くなら

Posted at

それ、もっとスマートに書けるよ」をもしもぼくが書くなら

ある特定の文字列が別の文字列内にあるかどうか

const ua = navigator.userAgent;

if (~ua.indexOf('iPhone') || ~ua.indexOf('iPod') || ~ua.indexOf('iPad')) {
  return 'ios';
} else {
  return 'other';
}

正規表現を使います

const isAppleDevice = !!navigator.userAgent.match(/iPhone|iPod|iPad/)

それlet使わなくてもできるよ

const { foo, bar } = (() => {
  if (new Date().getHours() < 12) {
    return {
      foo: 'forenoon',
      bar: 'am'
    }
  } else {
    return {
      foo: 'afternoon',
      bar: 'pm'
    }
  }
})();

基本は別関数にして返す形にしますが、この例ならこうするかなと。

const isForenoon = new Date().getHours() < 12
const [ foo, bar ] = isForenoon ? ['forenoon','am'] : ['afternoon','pm']

参考

それ、もっとスマートに書けるよ

「それ、もっとスマートに書けるよ」がもっとスマートに書けるよ

8
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7