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関数ドリル】を毎日やる【勉強用】その5

Posted at

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

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

第2引数分の値を先頭から取得するもの
##take関数の課題内容
https://youtu.be/3euFMRP0XqA

##take関数に取り組む前の状態

  • 前回作成したtakeRight関数をそのまま使用することにした

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

  • 単純な機能でも様々な実装方法があるとわかった

##take関数の実装コード

const take = (array, num) => {
    let newArray = [];
    if (num === 0) {
        return newArray;
    } else if (num > 1) {
        const sliceNumber = num;
        newArray = array.slice(0, sliceNumber);
    } else {
        newArray = array.slice(0, 1);
    }
    return newArray;
};

console.log(take([1, 2, 3, 4, 5, 6], 3));
//[1,2,3]
console.log(take([1, 2, 3, 4, 5, 6]));
//[1]
console.log(take([1, 2, 3, 4, 5, 6], 8));
//[1,2,3,4,5,6]
console.log(take([1, 2, 3, 4, 5, 6], 0));
//[]

##take関数の解答コード

function take(array, n = 1) {
  if(n === 0) {
    return [];
  }
  if(n > array.length) {
    return [...array];
  }

  const takenValues = [];
  for(let i = 0; i < n; i++) {
    takenValues.push( array[i] );
  }

  return takenValues;
}

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

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

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

console.log( take([1, 2, 3], 0) );
// => []
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?