Spells and Charms

プログラミング(呪文学)の学習記録。

eloquent javascript 2nd edition chapter 2 Program Structure

今回からは気になるところだけメモしていくことにしました。

 

whileとdo-whileのちがい
while(a){
//何らかの処理
}

do{
//何らかの処理
} while (a)

条件aに関わらずdo-whileは最低1回は実行されてしまう。

 

 

**以下エクササイズのネタバレありです**

 

 

 

 

 

 

Exercise

Looping a Triangl

Write a loop that makes seven calls to console.log to output the following triangle:

#
##
###
####
#####
######
#######
for(var i = '#'; i.length<=7; i += '#'){
console.log(i)
}

 

 

FizzBuzz

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead.

 When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz"for numbers divisible by only one of those).

 

I wrote a simple for-loop.

for(var n = 1; n <= 100; n++){
console.log(n)
}

Then added if expression.

for(var n = 1; n <= 100; n++){
 if(n%3 === 0){
	n = 'Fizz';
 }if(n%5 === 0){
	n += 'Buzz';
 } 
console.log(n)
}

But if I ran this, the result was below.

1
2
Fizz

 

What was wrong?

 

 

 

I forgot to add else?

for(var n = 1; n <= 100; n++){
  var result = '';
  if(n%3 === 0){
    result = 'Fizz';
  }if(n%5 === 0){
  	result += 'Buzz';
  }else{
  	result = n;
  }
  console.log(result); 
}

It showed like below.

1
2
3
4
Buzz
6
7
8
9
Buzz
11
12
13
14
FizzBuzz

 Almost there!!
The only thing was 'Fizz' should be appeared, when n%3 ===0.


Spoiler alert!I  saw the hint.

It said use || operator!!   

 

This is my final answer.

for(var n = 1; n <= 100; n++){
  var result = '';
  if(n%3 === 0)
    result = 'Fizz';  if(n%5 === 0)
    result += 'Buzz'; 
  console.log(result||n); 
}