87
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-10-07

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

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

const ua = navigator.userAgent;

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

String.prototype.includes()を使いましょう。

const ua = navigator.userAgent;

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

※「それ、もっとスマートに書けるよ」を書いた人はnavigator.userAgentを配列だと勘違いしていますが、navigator.userAgentは文字列です。(だからua.indexOf()Array.prototype.indexOf()ではなくてString.prototype.indexOf()です。)「ある特定の要素が配列内にあるかどうか」を調べる場合は、Array.prototype.includes()を使いましょう。

それ即時関数使わなくても出来るよ

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

三項演算子を使いましょう。

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

URLクエリーパラメータのパース

const result = params.reduce((acc, param) => {
  const pair = param.split('=');
  acc[pair[0]] = decodeURIComponent(pair[1]);
  return acc;
}, {});

URLSearchParamsを使いましょう。

const result = new URLSearchParams(params);
87
56
8

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
87
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?