简体   繁体   中英

imperative vs declarative JavaScript

I am doing an exercise about imperative vs declarative. Unfortunately I don't understand the example or I don't get any results. "Uncaught ReferenceError: range is not defined"

'use strict'
// imperative
let numbers = range(10)
let evenNumbers = []
for (let i = 0; i < numbers.length; i += 1) {
    if (numbers[i] % 2 === 0) {
        evenNumbers.push(numbers[i])
    }
}
console.log(evenNumbers) // => [0, 2, 4, 6, 8]

and:

// declarative
range(10).filter(v => v % 2 === 0) // => [0, 2, 4, 6, 8]

It seems you come from a Python or PHP background, but JavaScript does not have a global range() -function. See this post for an alternative.

Edit: A simple solution in this case would simply be to write:

let numbers = [0,1,2,3,4,5,6,7,8,9]

Sure, it's a bit verbose, but it's also very easy to read, and in a small case like this, it's not problematic. If the purpose of the exercise was the difference between imperative and declarative programming, range(2) vs [0,1,2] should not matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM