1
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.

javascirptで64の倍数の配列(数列)をモダンな記法、fill()やmap()でスマートに作る方法

Last updated at Posted at 2022-08-29

例:こんな配列がほしい

[ 64, 128, 192, 256, 320, 384, 448, 512, 576, 640, 704, 768 ]

レガシーな書き方

var array = []
for(let i=1; i<10; i++){
    array[i] = i*64
}

なるべくモダンな記法で書きたい

const array = new Array(12).fill(64).map((v, i) => {return (i + 1) * v})

解説

new Array(12) で空要素が12個ある配列を作ります
Array.fill(64)で64を埋めます
各要素をMapで繰り返し処理してindex+1を乗算しています

コメント頂きました

@shiracamus さん提供

関数ブロックを式にして、よりスッキリとした書き方。

const array1 = Array(12).fill(64).map((v, i) => (i + 1) * v)
const array2 = Array(12).fill().map((_, i) => ++i * 64)
const array3 = [...Array(12).keys()].map(i => ++i * 64)

@think49 さん提供

ジェネレータ関数を定義して使い回せるようにした書き方。

'use strict';
function* multiple(number, length) {
  let i = 0;
  while (length - i) yield number * ++i;
}

console.log([...multiple(2, 5)]);  // [2, 4, 6, 8, 10]
console.log([...multiple(64, 5)]); // [64, 128, 192, 256, 320]

他にもあれば教えて下さい!編集リクエストもお待ちしています!

1
0
4

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
1
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?