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?

React学習過程で出てきたJSメソッド

0
Posted at

※現在、途中経過の記事です

動画教材やChat GPTに質問する過程で出てきたJSのメソッド

  • crypto.randomUUID
  • Array.isArray
  • includes
  • every
  • flatMap
  • new Set
  • Object.entries
  • localStorage

crypto.randomUUID();

整数の乱数生成。新しいidの生成などに便利

example.js
const arr = [
  {id: 1, name: 'Satoshi'},
  {id: 2, name: 'Kasumi'},
  {id: 3, name: 'Takeshi'}
]
const newMember = {id: crypto.randomUUID(), name: 'O-kido'};

const newArr = [...array, newMember];

Array.isArray

配列かどうかを確かめる。

example.js
const str = "string";
const arr = ["str", "num"];

//↓ 結果はnull
Array.isArray(str);
//↓ 結果はture
Array.isArray(arr);

includes

配列にそれがあるかを確かめる。絞り込み検索の実装に便利

example.js
const arr = ["apple", "banana", "orange"];

//↓ 結果はture
arr.includes("banana");

every

全部trueならture。AND検索の実装に便利

example.js
const arr = [1,2,3];

//↓ 結果はture
arr.every(n => n > 0);

flatMap

配列を一つの配列にまとめる。

example.js
const profiles = [
  {
    name: "Shimiken",
    age: 46,
    absolute: ["hentai", "unchi", "waki", "muscle"]
  },
  {
    name: "Genjin",
    age: 46,
    absolute: ["hentai", "newhalf"]
  },
  {
    name: "Chocoball",
    age: 59,
    absolute: ["hentai", "muscle"]
  },
];

profiles.map(ab => ab.absolute);
profiles.flatMap(ab => ab.absolute);

//↓ mapの結果 配列の中に配列
[
  ["hentai", "unchi", "waki", "muscle"],
  ["hentai", "newharf"],
  ["hentai", "muscle"]
]
//↓ flatMapの結果 一つのなだらかな配列
["hentai", "unchi", "waki", "muscle", "hentai", "newharf", "hentai", "muscle"]

new Set

重複を消す。Setはオブジェクトとして返すので、スプレット構文を使うことによって配列にしなおしている

example.js
const arr = ["unco", "unchi", "unco", "unpi"];
[...new Set(arr)];

//↓ 結果は
["unco", "unchi", "unpi"]

Object.entries

オブジェクトを配列にする。オブジェクトをmapやfilterで回したいときに便利

example.js
const obj = {
  1: "unco",
  2: "unchi",
  3: "unpi"
}

Object.entries(obj);

//↓ 結果は
[
  [1: "unco"],
  [2: "unchi"],
  [3: "unpi"]
]

localStorage

ブラウザにデータを保存する機能。文字列しか保存できない。

setItem ← 保存
getItem ← 取得
stringify ← 文字列に変換
parse ← 文字列から元の形式へ

example.js
//↓ 保存名、JSON形式の文字列に変換
localStorage.setItem('data', JSON.stringify(data));

//↓ 保存したものを取り出す
const saved = localStorage.getItem(data);

//↓ 保存したものをJSON形式から元の形に戻す
console.log(JSON.parse(saved));
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?