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?

Array.keys()メソッドでお手軽に大量のダミーデータを作る

Posted at

Reactでレンダリングについて学ぶために、
「あえて大量のダミーデータを用意してコンポーネントに負荷をかけたい!」
と考えていました。

Array.keys()を使えば大量のダミーデータを持った配列を用意することができると知ったので、そのやり方をメモします。

const data = [...Array(1000).keys()]

上記のコードを実行すると、
[0, 1, 2, ... 999]
がdate変数に入ります。

解説

Array(1000)を実行すると、1000個の空のスロットがある配列が生成されます(空のスロットは要素自体が存在せず、直接参照してもundefinedが返される)。

Array(1000).keys()を実行すると、Array Iteratorオブジェクトが返ります。

Iteratorとは、繰り返し可能なデータを、next()メソッドで一つずつ順番に返す仕組みのことです。

サンプル
const iterator = Array(1000).keys();
console.log(iterator.next()); // { "value": 0, "done": false }
console.log(iterator.next()); // { "value": 1, "done": false }

/// 省略

console.log(iterator.next()); // { "value": 999, "done": false }

...は「スプレッド構文」と言って、配列の中身やオブジェクトのプロパティを展開することができます。
こちらは先ほど紹介したIteratorにも使用することができます。

[...Array(1000).keys()]とすることで、next()メソッドを実行しなくても1000個の数値が格納された配列を生成することができます。

まとめ

Array.keys()メソッドでお手軽に大量のダミーデータを作ることができました。
どなたかの参考になれば幸いです。

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?