Cash Register Part II
2012-11-17 Saturdayひゃっほう!!Codecademy で Cash Register Part II おわったぜ!
Recursing on a list で index + 1
って書くべきところを index++
って書いてハマってた。まさにこの人と同じ間違い。
//bad! This should be inside an object. We'll fix that a bit later
var change = 0;
function howManyCoins (coinName, coinAmount, coinsSoFar) {
if (change < coinAmount) {
console.log(coinsSoFar + " " + coinName);
} else {
change -= coinAmount;
howManyCoins(coinName, coinAmount, coinsSoFar + 1);
}
}
var currency = [5.00, 1.00, 0.25, 0.10, 0.01];
var coinNames = ["five dollar bills", "one dollar bills", "quarters", "dimes", "pennies"];
function makeChange (coinNames, currency, index) {
if (index >= currency.length) {
// and this
return;
} else {
//and this
howManyCoins(coinNames[index], currency[index], 0);
// ここの3つめの引数を index++ にして無限ループしてた
makeChange(coinNames, currency, index + 1)
}
}
change = 18.94;
makeChange(coinNames, currency, 0);
なぜ ++
って書いてたかというと、codecademy の別のコースで出てきて、1減らしたいときここは --
とも書けるぜ。これちょっと自慢できるぜ。って書いてあったんだよなー。これ。
function makeRobots(robotsNeeded){
// Do we need any robots?
if(robotsNeeded>0){
// We do? Well lets make one
console.log("Robot "+ robotsNeeded+" Created");
// Removes 1 from robots Needed
// Also the same as saying robotsNeeded = robotsNeeded -1
robotsNeeded--;
// Calls makeRobots with the new number of robots needed
makeRobots(robotsNeeded);
}
}
makeRobots(2);
ここでは、robotsNeeded = robotsNeeded -1
と robotsNeeded--
は同じ、という話で、robotsNeeded -1
と robotsNeeded--
は同じではないのだけど、そこをカンチガイしていたのだった。
Knowing this will impress your programmer friends, and make you more attractive to people in general. とかいわれたら使ってみたくなるじゃんね!
よくわかんなくてぶつぶつ言ってたら Twitter で教えてもらった。pre-increment と post-increment ってどう違うの!サイ本の説明よくわかんなかった!
さださん(@sada_h) の https://gist.github.com/4088752 見て、実行してみて、理解した。
var i = 1;
// +1 される前の値が出力されるのが i++
console.log(i++) // 1
// そして次に呼び出すときには +1 されている
console.log(i) // 2
var j = 1;
// +1 された後の値が出力されるのが ++j
console.log(++j) // 2
console.log(j) // 2
そうか。index + 1 はOKだし、index = index + 1 でもよくて、++index もよいのだった。index++ がまずかったのね。
残り Build a Blackjack Game, Final だけなんだけど、OOPのとこ復習しないといけないのをひしひしとかんじています。
Author
Yuko Honda Morita (yukop) : yukop.com
飯能→東京→シリコンバレー。夫と猫2匹と暮らしてます。作ったり学んだり踊ったりするのが好き。
Born in Japan, living in California with my husband and two cats. "A bit of a geek and a bit of a geek fan and a bit of an artist." ->
Latest Posts
Japanese
- 2016-02-20 » フロントバンパーの外し方メモ - SUBARU XV Crosstrek 2014
- 2016-01-19 » Singular they
- 2015-12-21 » San Joaquin River NWR
- 2015-12-20 » San Luis NWR
- 2015-11-22 » EAD(労働許可証)更新 その1
- 2015-11-08 » Burrowing Owl アナホリフクロウ
- 2015-10-31 » Tire Pressure Warning
English
- 2014-10-18 » Halloween Decorations
- 2014-08-01 » Cat Parasite
- 2014-07-29 » How to Make Dumplings From Scratch
- 2014-07-25 » Moving to an Unfamiliar Land That Speaks a Foreign Language
- 2014-07-23 » Going to See a Dentist
- 2014-07-22 » Agent Cooper's Favorite Cherry Pie
- 2014-07-19 » It's Nice Living with Two Kittens