LoginSignup
0
0

More than 3 years have passed since last update.

【javascript】配列の置き換え

Last updated at Posted at 2020-12-23

constで定義したい

配列を定義する時に、後にArray.filter()等の結果に置き換える理由でletを用いてました。
この事に何か違和感を感じていたので、constで定義できるように関数を用意した、ただそれだけです。

exmaple1.js
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.filter(x => x < 5);

こんな感じに。

exmaple2.js
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
renewArray(array, array.filter(x => x < 5));

コード

const argumentsError = (argValue, nth, len='-', fnName='') => 
    console.error(`wrong arg(${nth} of ${len}) / ${fnName} function\n`, argValue);

const renewArray = (...args) => {
    //引数検査
    for (let i=0; i<2; i++) {
        if (!Array.isArray(args[i])) return argumentsError(args[i], i+1, 2, 'renewArray');
    }
    //本体
    const [baseArray, newArray] = args;
    baseArray.length = 0;
    baseArray.push(...newArray);
};


const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
renewArray(array, array.filter(x => x < 5));

これ必要?

必要とも言えるし、不要とも言える。

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