So in python, you can use a function called range()
to (conventionally – I know there are other uses) easily iterate over, yknow, a range of numbers or through a list/array/yaddayadda. It works like this:
for i in range(13): # you can also limit it on the lower bound, a la range(7,13), print i # but be ye wary of yon fenceepostee
While going through some javascript tutorialling, I found a typical learner problem that I found later that I’d been approaching the wrong way, but if you’ll bear with me & restrain thyself from punching angrily through your computer/rotary telephone, COME WITH ME ON THIS JOURNEY:
For a Rock Paper Scissors game, lesson 11 or 12 of the Functions lesson of Codecademy‘s javascript class, it asks the student to use a randomize function (Math.random()
) to call “rock” when the first third of the number, “paper” when the second, and “scissors” when the third. My FIRST thought was to use a range function, like if i in range(.33)
and if i in range(.34,.66)
! So I tried a couple of different syntactial approaches that seemed javascriptey, they didn’t work, so I went a-googlin’ (how you do) and found the following solution:
Array.apply(null, Array(5)).map(function (_, i) {return i;}); [0,1,2,3,4]
I know I’m new to javascript, but that is honestly barely parseable. I’m not here to wail about things that one language does that another doesn’t, but this was a difference that frustrated me – – until (and you patient few, I know you’ve been waiting for this) I realized that there’s another way to solve this problem! And that’s the beautiful thing about programming, particularly learning different languages. I remember using this syntax in other learning situations, back in the day when I first learned Python. The resolution is to use the (javascript) format of:
if (i < .33) { return "computer chose rock"; } else if (i <= .66) { return "computer chose paper"; } else { return "computer chose scissors"; }
which looks (save the curly braces, ;, & s/else_if/elif) nearly the same as pythonic syntax.
MORAL OF THE STORY: there are many ways to do many different things! fabulous!