functiontestNum(a) {
let result;
if (a > 0) {
result = 'positive';
} else {
result = 'NOT positive';
}
return result;
}
console.log(testNum(-5));
Basic Syntax - for loop
也有while以及do while
for (let i = 0 ; i < 10 ; i +=1){
console.log(i);
}
while (condition) {
// statements
}
do {
// statements
} while (condition);
Basic Syntax - forEach & for of
可以從array, map. set中逐筆取資料
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(num => sum += num);
console.log(sum) // 15let mArray = [1, 2, 3]
for (let value of mArray) {
console.log(value); // 1 2 3
}
Basic Syntax - Function
// named functionfunctionsum(a, b){
return a+b;
}
// 匿名函式const sum = function(a, b) {
return a+b;
}
// arrow functionconst sum = (x, y) => {
return x + y
};
More about Arrow Function
部分情況下可以用的簡寫
// no arguments時const callMe = () => {
console.log('John!');
}
// 只有一個argumentconst callMe = name => {
console.log(name);
}
// function內只有一行const doubleNum = num => num * 2;
Basic Syntax - Object
基本上就是python的dict,常會搭配array、能方便轉成JSON
const dog = {
name: 'Tom',
breed: 'Golden Retriever',
weight: 60
}
// get values by keyconsole.log(dog.breed) // Golden Retrieverconsole.log(dog[breed]) // Golden Retriever
More about Object
// get values from each keyObject.keys(dog).forEach((key) => {
console.log(dog[key]);
});
// define function in objectconst dog = {
breaks() {
console.log('woof');
}
};
dog.breaks(); // woof
直接跑npx jest就會自動去找所有match pattern的test case
當然也可以把他加到package.json的script內
Config Jest
先透過npx jest --init產生jest.config.js,問題依照需求作答
Would you like to use Jest when running "test" script in "package.json"? ... yes
Would you like to use Typescript for the configuration file? ... no
Choose the test environment that will be used for testing » node
Do you want Jest to add coverage reports? ... no
Which provider should be used to instrument code for coverage? » babel
Automatically clear mock calls, instances, contexts and results before every test? ... no