eloquent javascript 2nd edition chapter 4 Data Structures: Objects and Arrays
Exercises
The sum of a range
The sum of a range
The introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers:
Write a
range
function that takes two arguments,start
andend
, and returns an array containing all the numbers fromstart
up to (and including)end
.Next, write a
sum
function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.As a bonus assignment, modify your
range
function to take an optional third argument that indicates the “step” value used to build up the array. If no step is given, the array elements go up by increments of one, corresponding to the old behavior. The function callrange(1, 10, 2)
should return[1, 3, 5, 7, 9]
. Make sure it also works with negative step values so thatrange(5, 2, -1)
produces[5, 4, 3, 2].
ひとつめのfunction.
コンソール確認したら正しそうなので次に。
これもコンソールで確認したら大丈夫そうだった。ので次。
次のはさっきかいたrangeをアレンジするもののよう。
ちょっと迷走。
できたっぽい!
回答はpushをつかってましたが、
あまりまだ自分は多用してないのでforループで地道に書きました。
エクササイズはまだありますが、もうすぐテクニカルテストなるものを受けるので今回はここまでです。