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?

✅ 今日学んだこと

  • 配列の中から特定の要素を探す方法(includes() と for ループでの検索)
  • 配列のシャッフル(sort() と Math.random() を使ったランダム並べ替え)
  • 文字列を1文字ずつ配列に分割する方法(split(""))
  • 文字列の各文字をループで順番に表示する方法
  • オブジェクトの値を配列として取り出す方法(Object.values())
  • 配列の値の合計を求める方法(for ループの合計計算、reduce()の活用)
  • 配列の結合方法(スプレッド構文 [...] と concat() メソッド)

配列の中から 'りんご' を探して、見つかったら 'ありました!' と表示する

  • 文字列はクォーテーションで囲むことが重要
  • includes() を使うと簡単に存在チェックができる
  • for 文で回して探す方法もある
const array = ["りんご", "ごはん", "たまご"];

if (array.includes("りんご")) {
  console.log("ありました!");
}

0から9までをランダムな順で並べた配列を作って表示する

  • Array.from()[...Array(10).keys()] で0〜9の配列を作る
  • sort(() => Math.random() - 0.5) でシャッフルする
const numbers = [...Array(10).keys()];
numbers.sort(() => Math.random() - 0.5);
console.log(numbers);

文字列 'JavaScript' を1文字ずつ表示する

  • split("") で文字列を1文字ずつの配列に変換し、for 文で表示する
const texts = "JavaScript";
const chars = texts.split("");

for (let i = 0; i < chars.length; i++) {
  console.log(chars[i]);
}

オブジェクトの中の値をすべて足して合計を出す関数を書く

  • Object.values() でオブジェクトの値を配列として取得
  • for 文や reduce() で合計を計算
const obj = { a: 10, b: 20, c: 30 };
const numbers = Object.values(obj);

let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum); // 60

または

const sum = numbers.reduce((acc, val) => acc + val, 0);
console.log(sum);

2つの配列を結合して、新しい配列を作るコードを書く

  • スプレッド構文や concat() を使う
const arr1 = [1, 2, 3];
const arr2 = [3, 4, 5, 6];
const newArray = [...arr1, ...arr2];
console.log(newArray);

// concatの場合
const combined = arr1.concat(arr2);
console.log(combined);

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?