0
0

More than 1 year has passed since last update.

【JavaScript関数ドリル】Lodash関数の実装【勉強用】_.indexOf関数

Posted at

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

_.indexOf関数の挙動
_.indexOf([1, 2, 1, 2], 2);
// => 1
 
// Search from the `fromIndex`.
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3

第1引数に配列、第2引数に検索する値、第3引数で開始位置を指定し、指定されなければ0が初期値

_.indexOf関数の課題内容

_.indexOf関数に取り組む前の状態

  • lastIndexOfと同じ要領で作成する

_.indexOf関数に取り組んだ後の状態

  • −1のリターンを深く考えすぎてしまった
  • 今後はできるだけシンプルに実装していきたい
  • セミコロンの有無をまだまだ理解しきれていないため、指摘があればいただきたい。
  • if文の末端にセミコロンをつけていないのは、for文の中身であるため付けるべきでないと考えた。

_.indexOf関数の実装コード

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


console.log(indexOf([1, 2, 1, 2], 2));
// => 1
 
// Search from the `fromIndex`.
console.log(indexOf([1, 2, 1, 2], 2, 2));
// => 3

console.log(indexOf([1, 2, 1, 2], 4, 2));
// => -1

_.indexOf関数の解答コード

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

  return -1;
}

// console.log( indexOf([1, 2, 1, 2], 2) );
// => 1

// Search from the `fromIndex`.
console.log( indexOf([1, 2, 1, 2], 3, 2) );
// => 3
0
0
2

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