2015년 8월 30일 일요일

Javascript loop

Let's see javascript loop statements. Learning test is written using Jasmine. Please refer Jasmine usage which I wrote before if you have interest it.

1. label with continue, break
Javascript can define label. In [line 3],  "firstLoop" label is defined. This is useful when escape nested loop statement. The "break" statement in [line 9] make to escape of the First(for) loop, The second break in [line 13] make to escape loop(while) statement. This is same as in "continue" statements as well.

it("label with break, break for loop if sum >= 50", function() {
var sum = 0;
firstLoop: for (var i = 0; i < 10; i++) {
var j = 0;
while (true){
sum++;
j++;
if (sum >= 50) {
break firstLoop;
}
if (j > 10) {
break;
}
}
}
expect(i).toBe(4);
});
it("label with continue, sum++ if j is odd number, j < 10", function() {
var sum = 0;
firstLoop : for (var i = 0; i < 2; i++) {
var j = 0;
while (true) {
j++;
//skip if j is even number
if (j % 2 == 0) {
continue;
}
if (j < 10) {
sum++;
console.log("j, sum : " + j +", " + sum);
} else {
continue firstLoop;
}
}
}
expect(sum).toBe(10);
});
2. for - in statement
Property name is used in "for - in" statement if the element are Object. If element is array, index is used. In [line 8], p have the attribute name of object and can access the value of property like [line 9]. The [line 22] shows how to use it in Array.

it("for - in statement with object, array", function() {
var coffee = {
"price" : "5000",
"name" : "Americano"
}
for (p in coffee) {
if (p == "price") {
expect(coffee[p]).toBe("5000");
}
if (p == "name") {
expect(coffee[p]).toBe("Americano");
}
}
var arayCoffee = ["Americano", "Caffee Latte"];
arayCoffee.name = "My favorite";
for (i in arayCoffee) {
if (i == 0) {
expect(arayCoffee[i]).toBe("Americano");
}
if (i == 1) {
expect(arayCoffee[i]).toBe("Caffee Latte");
}
if (i == "name") {
expect(arayCoffee[i]).toBe("My favorite");
}
}
})
3. for - of statement
The for - of  statement retrieve its element like [line 6] without index.

it("for - of statement ", function() {
var arayCoffee = ["Americano", "Caffee Latte"];
for (obj of arayCoffee) {
if (obj == "Americano") {
expect(obj).toBe("Americano");
}
if (obj == "Caffee Latte") {
expect(obj).toBe("Caffee Latte");
}
}
});
4. Reference
- MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
- Jasmine - http://jasmine.github.io/2.3/introduction.html

댓글 없음:

댓글 쓰기