LoginSignup
1
0

More than 1 year has passed since last update.

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

Posted at

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

nth関数の挙動
var array = ['a', 'b', 'c', 'd'];

_.nth(array, 1);
// => 'b'

_.nth(array, -2);
// => 'c';

第2引数が負の場合、配列から第2引数個目の値を返す

nth関数の課題内容

nth関数に取り組む前の状態

  • 正負を判断する方法を検索すればよさそう

nth関数に取り組んだ後の状態

  • 三項演算子の使い方をよく理解できた
  • 解答が2行に対し自分は7行も書いてしまった
  • 今後も三項演算子について積極的に使用したい

nth関数の実装コード

const nth = (array, index) => {
    if (Math.sign(index) === 1) {
        return array[index]
    } else if (Math.sign(index) === -1) {
        const absNumber = Math.abs(index);
        const returnNum = array.splice(-absNumber, 1);
        return returnNum.shift();
    };
};

console.log(nth([1, 2, 3, 4, 5], 3));
// => '4'

console.log(nth([1, 2, 3, 4, 5, 6, 7, 8], -4));
// => '5'

nth関数の解答コード

function nth(array, n = 0) {
  return n >= 0 ? array[n] : array[array.length + n];
}

const array = ['a', 'b', 'c', 'd'];

console.log( nth(array, 1) );
// => 'b'

console.log( nth(array, -2) );
// => 'c';
1
0
4

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