[英]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" “未捕获的 ReferenceError:未定义范围”
'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.看来您来自 Python 或 PHP 背景,但 JavaScript 没有全局range()
函数。 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.如果练习的目的是区分命令式编程和声明式编程,那么range(2)
与[0,1,2]
应该无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.