0

What's wrong with my looping? The first iteration has null?

generateRewardOptions = () => {
        let options = []
        const max = 20

        for(let i = 1; i <= max; i++){
            options[i] = {
                key: i,
                value: i,
                text: i
            }
        }

        return options
    }

console.log(JSON.stringify(generateRewardOptions()));

https://jsbin.com/cupelanotu/edit?html,js,console,output

Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

2 Answers2

1

The problem is that you start the loop from 1 when should start from 0.

Changing the for from 0 and excluding max should solve the issue:

for(let i = 0; i < max; i++){

JavaScript arrays are 0-based

smnbbrv
  • 23,502
  • 9
  • 78
  • 109
1

Another option in addition to what smnbbrv suggestes is to use push in your loop:

for(let i = 1; i <= max; i++) {
    options.push({
        key: i,
        value: i,
        text: i
    });
}

and then you don't have to start at i=0.

e-shfiyut
  • 3,538
  • 2
  • 30
  • 31
  • 1
    this is easier but can have performance problems on big arrays, https://jsperf.com/array-direct-assignment-vs-push/5 (60% slower than direct assignment on modern chrome) – smnbbrv Jan 28 '18 at 13:03
  • 1
    nice link. Thanks – e-shfiyut Jan 28 '18 at 13:07
  • 1
    @smnbbrv This test is flawed and does not reflect real array performance in Chrome, see https://stackoverflow.com/questions/21034662/why-push-method-is-significantly-slower-than-putting-values-via-array-indices-in . According to https://jsperf.com/push-method-vs-setting-via-key/3 there is no significant performance difference between those two methods. – le_m Jan 28 '18 at 13:15