LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript関数ドリル】初級編のindexOf関数の実装アウトプット

Last updated at Posted at 2022-06-09

indexOf関数の課題内容

_.indexOf関数を自分で実装する課題。
https://lodash.com/docs/4.17.15#indexOf

「課題内容」/「解説動画」/「解答例」を確認したい場合は、以下リンク先のページを参照。
https://js-drills.com/blog/indexOf/

課題に取り組む前の状態

  • 解答例を見なくてもできそうだと思った。

課題に取り組んだ後の状態

  • 解答例はfromIndexが負の数の場合の処理を別途書いていないようなので、その辺り、自分の書いたコードでよいのか判断に悩みました。(※Lodashのページには、”If fromIndex is negative, it's used as the offset from the end of array.”とあったため)

indexOf関数の実装コード(答えを見る前)

function indexOf(array, value, fromIndex = 0) {
    if (fromIndex < 0) {
        for (let i = array.length + fromIndex; 0 <= i; i--) {
            if (array[i] === value) {
                return i;
            }
        }
        return -1;
    }

    for (let i = fromIndex; i < array.length; i++) {
        if (array[i] === value) {
            return i;
        }
    }
    return -1;
}

indexOf関数の実装コード(答えを見た後)

// 同じ
0
0
0

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
0
0