0
0

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 1 year has passed since last update.

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

Posted at

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

_.slice関数の挙動
console.log(slice([1, 2, 3, 4, 5], 0, 1));
// => [1]
console.log(slice([1, 2, 3, 4, 5], 0, 3));
// => [1, 2, 3]
console.log(slice([1, 2, 3, 4, 5], 2));
// => [3, 4, 5]

第1引数の位置から第2引数の数だけ取得する
第2引数が無い場合は末尾まで取得する
##_.slice関数の課題内容
https://youtu.be/KZaJoGJQSE4

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

  • 引数の有無に応じるにはif文を使えばよさそう

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

  • 引数の設定の仕方を理解できていなかった
  • 遠回りした関数を作っていた
  • 元の配列の保護を意識していなかった
  • splice頼みになっていた
  • 単純なことに時間をかけすぎた

##_.slice関数の実装コード

const slice = (array, start, end) => {
    const newArray = [];
    for (let i = start; i < array.length; i++) {
        if (!end) {
            newArray.push(array[i]);
        } else if (end) {
            return array.splice(start, end);
        }
    }
    return newArray;
}

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

##_.slice関数の解答コード

function slice(array, start = 0, end = array.length) {
  const slicedArray = [];
  for(let i = start; i < end; i++) {
    slicedArray.push( array[i] );
  }

  return slicedArray;
}

const numbers = [10, 20, 30, 40, 50];
const slicedNumbers = slice(numbers, 1, 4);

console.log( slicedNumbers );
// => [20, 30, 40]

console.log( numbers );
// => [10, 20, 30, 40, 50]
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?