JavaScript basic 語法59-113 freecodecamp

內容目錄

Use Conditional Logic with If Statements

function trueOrFalse(wasThatTrue) {
  // Only change code below this line
  if (wasThatTrue) {
    return “Yes, that was true”;
  }
  return “No, that was false”;
  // Only change code above this line
}

Comparison with the Equality Operator

// Setup
function testEqual(val) {
  if (val == 12) { // Change this line
    return “Equal”;
  }
  return “Not Equal”;
}
testEqual(10);
testEqual(12)
console.log(testEqual(10));
console.log(testEqual(12));
Not Equal
Equal

Comparison with the Strict Equality Operator

// Setup
function testStrict(val) {
  if (val === 7) { // Change this line
    return “Equal”;
  }
  return “Not Equal”;
}
testStrict(10);
testStrict(7);
testStrict(“7”);
console.log(testStrict(10),’\n’,testStrict(7),’\n’,testStrict(“7”));
Not Equal
 Equal
 Not Equal

Practice comparing different values

// Setup
function compareEquality(a, b) {
  if (a === b) { // Change this line
    return “Equal”;
  }
  return “Not Equal”;
}
compareEquality(10, “10”);
compareEquality(“20”, 20);
console.log(compareEquality(10, “10”), compareEquality(“20”, 20));
Not Equal Not Equal

Comparison with the Inequality Operator

// Setup
function testNotEqual(val) {
  if (val != 99) { // Change this line
    return “Not Equal”;
  }
  return “Equal”;
}
testNotEqual(10);
console.log(testNotEqual(99), testNotEqual(“99”), testNotEqual(12), testNotEqual(“bob”));
Equal Equal Not Equal Not Equal

Comparison with the Strict Inequality Operator

// Setup
function testStrictNotEqual(val) {
  if (val !== 17) { // Change this line
    return “Not Equal”;
  }
  return “Equal”;
}
testStrictNotEqual(10);
testStrictNotEqual(17);
console.log(testStrictNotEqual(10));
console.log(testStrictNotEqual(17));

Comparison with the Greater Than Operator

function testGreaterThan(val) {
  if (val > 100) {  // Change this line
    return “Over 100”;
  }
  if (val > 10) {  // Change this line
    return “Over 10”;
  }
  return “10 or Under”;
}
console.log(testGreaterThan(0),’\n’,testGreaterThan(10),’\n’,testGreaterThan(11),’\n’,testGreaterThan(99),’\n’,testGreaterThan(101));
10 or Under
 10 or Under
 Over 10
 Over 10
 Over 100

Comparison with the Greater Than Or Equal To Operator

function testGreaterOrEqual(val) {
  if (val >= 20) {  // Change this line
    return “20 or Over”;
  }
  if (val >=10) {  // Change this line
    return “10 or Over”;
  }
  return “Less than 10”;
}
// testGreaterOrEqual(0); Less than 10
// testGreaterOrEqual(10); 10 or Over
// testGreaterOrEqual(21); 20 or Over

Comparison with the Less Than Operator

function testLessThan(val) {
  if (val < 25) {  // Change this line
    return “Under 25”;
  }
  if (val < 55) {  // Change this line
    return “Under 55”;
  }
  return “55 or Over”;
}

Comparison with the Less Than Or Equal To Operator

function testLessOrEqual(val) {
  if (val <= 12) {  // Change this line
    return “Smaller Than or Equal to 12”;
  }
  if (val <= 24) {  // Change this line
    return “Smaller Than or Equal to 24”;
  }
  return “More Than 24”;
}

Comparisons with the Logical And Operator

function testLogicalAnd(val) {
  // Only change code below this line
  if (val >= 25 && val <= 50) {
      return “Yes”;
  }
  // Only change code above this line
  return “No”;
}

Comparisons with the Logical Or Operator

function testLogicalOr(val) {
  // Only change code below this line
  if (val < 10 || val > 20) {
    return “Outside”;
  }
  // Only change code above this line
  return “Inside”;
}

Introducing Else Statements

function testElse(val) {
  let result = “”;
  // Only change code below this line
  if (val > 5) {
    result = “Bigger than 5”;
  }else {
    result = “5 or Smaller”;
  }
  // Only change code above this line
  return result;
}
// console.log(testElse(4)); 5 or Smaller
// console.log(testElse(6)); Bigger than 5

Introducing Else If Statements

function testElseIf(val) {
  if (val > 10) {
    return “Greater than 10”;
  } else if (val < 5) {
    return “Smaller than 5”;
  } else {
    return “Between 5 and 10”;
  }
}
testElseIf(0);
testElseIf(5);
testElseIf(7);
testElseIf(10);
testElseIf(12);
Smaller than 5
Between 5 and 10
Between 5 and 10
Between 5 and 10
Greater than 10

Logical Order in If Else Statements

function orderMyLogic(val) {
  if (val < 5) {
    return “Less than 5”;
  } else if (val < 10) {
    return “Less than 10”;
  } else {
    return “Greater than or equal to 10”;
  }
}
console.log(orderMyLogic(0));
console.log(orderMyLogic(7));
console.log(orderMyLogic(6));
console.log(orderMyLogic(11));
Less than 5
Less than 10
Less than 10
Greater than or equal to 10

Chaining If Else Statements 邏輯是由小寫到大

function testSize(num) {
  // Only change code below this line
  if (num < 5) {
    return “Tiny”;
  } else if (num < 10) {
    return “Small”;
  } else if (num < 15) {
    return “Medium”;
  } else if (num < 20) {
    return “Large”;
  } else {
    return “Huge”;
    // Only change code above this line
  }
}
console.log(testSize(0));
console.log(testSize(4));
console.log(testSize(5));
console.log(testSize(8));
console.log(testSize(10));
console.log(testSize(14));
console.log(testSize(15));
console.log(testSize(17));
console.log(testSize(20));
console.log(testSize(25));
Tiny
Tiny
Small
Small
Medium
Medium
Large
Large

Golf Code 高爾夫球的程式碼

const names = [“Hole-in-one!”, “Eagle”, “Birdie”, “Par”, “Bogey”, “Double Bogey”, “Go Home!”];
function golfScore(par, strokes) {
  // Only change code below this line
  if (strokes == 1) {
    return names[0];
  } else if (strokes <= par – 2){
    return names[1];
  } else if (strokes == par – 1) {
    return names[2];
  } else if (strokes == par ) {
    return names[3];
  } else if (strokes == par + 1) {
    return names[4];
  } else if (strokes == par + 2) {
    return names[5];
  } else {
    return names[6];
  // Only change code above this line
  }
}
// console.log(golfScore(4, 1)); Hole-in-one!
// console.log(golfScore(4, 2)); Eagle
// console.log(golfScore(5, 2)); Eagle
// console.log(golfScore(4, 3)); Birdie
// console.log(golfScore(4, 4)); Par
// console.log(golfScore(1, 1)); Hole-in-one!
// console.log(golfScore(5, 5)); Par
// console.log(golfScore(4, 5)); Bogey
// console.log(golfScore(4, 6)); Double Bogey
// console.log(golfScore(4, 7)); Go Home!
// console.log(golfScore(5, 9)); Go Home!

Selecting from Many Options with Switch Statements

function caseInSwitch(val) {
  let answer = “”;
  // Only change code below this line
  switch(val){ // 轉換數值
    case 1:
      answer =”alpha”;
      break;
    case 2:
      answer =”beta”;
      break;
    case 3:
      answer =”gamma”;
      break;
    case 4:
      answer =”delta”;
      break;
  }
  // Only change code above this line
  return answer;
}
// console.log(caseInSwitch(1)); alpha
// console.log(caseInSwitch(2)); beta
// console.log(caseInSwitch(3)); gamma
// console.log(caseInSwitch(4)); delta

 


Adding a Default Option in Switch Statements

function switchOfStuff(val) {
  let answer = “”;
  // Only change code below this line
  switch(val){ // 轉換數值
    case “a”:
      answer =”apple”;
      break;
    case “b”:
      answer =”bird”;
      break;
    case “c”:
      answer =”cat”;
      break;
    default:
      answer = “stuff”;
      break;
  }
  // Only change code above this line
  return answer;
}
console.log(switchOfStuff(“a”));
console.log(switchOfStuff(“b”));
console.log(switchOfStuff(“c”));
console.log(switchOfStuff(“d”));
console.log(switchOfStuff(1));

Multiple Identical Options in Switch Statements

function sequentialSizes(val) {
  let answer = “”;
  // Only change code below this line
  switch(val){ // 轉換數值
    case 1:
    case 2:
    case 3:
      answer =”Low”;
      break;
    case 4:
    case 5:
    case 6:
      answer =”Mid”;
      break;
    case 7:
    case 8:
    case 9:
      answer =”High”;
      break;
  }
  // Only change code above this line
  return answer;
}
console.log(sequentialSizes(1));
console.log(sequentialSizes(2));
console.log(sequentialSizes(3));
console.log(sequentialSizes(4));
console.log(sequentialSizes(5));
console.log(sequentialSizes(6));
console.log(sequentialSizes(7));
console.log(sequentialSizes(8));
console.log(sequentialSizes(9));
Low
Low
Low
Mid
Mid
Mid
High
High
High

Replacing If Else Chains with Switch

If else method : 

function chainToSwitch(val) {
  let answer = “”;
  // Only change code below this line
  if (val === “bob”) {
    answer = “Marley”;
  } else if (val === 42) {
    answer = “The Answer”;
  } else if (val === 1) {
    answer = “There is no #1”;
  } else if (val === 99) {
    answer = “Missed me by this much!”;
  } else if (val === 7) {
    answer = “Ate Nine”;
  }
  // Only change code above this line
  return answer;
}

Switch method :

function chainToSwitch(val) {
  let answer = “”;
  // Only change code below this line
  switch(val) {
    case “bob”:
      answer = “Marley”;
      break;
    case 42:
      answer = “The Answer”;
      break;
    case 1:
      answer = “There is no #1”;
      break;
    case 99:
      answer = “Missed me by this much!”;
      break;
    case 7:
      answer = “Ate Nine”;
      break;
  }
  // Only change code above this line
  return answer;
}

Returning Boolean Values from Functions

function isLess(a, b) {
  // Only change code below this line
  return a < b;
  // 下面if else可以被上面那行取代
  // if (a < b) {
  //   return true;
  // } else {
  //   return false;
  // }
  // Only change code above this line
}

Return Early Pattern for Functions

// Setup
function abTest(a, b) {
  // Only change code below this line
  if (a < 0 || b < 0 ){
    return undefined;
  }
  // Only change code above this line
  return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
console.log(Math.sqrt(2))
console.log(Math.pow(Math.sqrt(2) + Math.sqrt(2),2))
console.log(Math.round(Math.pow(Math.sqrt(2) + Math.sqrt(2),2)))

 

The Math.SQRT2 property represents the square root of 2, approximately 1.414:

Math.SQRT2 = 2 ≈ 1.414

The Math.pow() static method, given two arguments, base and exponent, returns baseexponent.

The Math.round() function returns the value of a number rounded to the nearest integer.

Reference :  Math.round; Math.pow; Math.sqrt

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round


Counting Cards

let count = 0;
function cc(card) {
  // Only change code below this line
  switch(card){ // 轉換數值
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      count++;
      break;
    case 10:
    case ‘J’:
    case ‘Q’:
    case ‘K’:
    case ‘A’:
      count–;
      break;
  }
  if (count > 0) {
    return count + ” Bet”;
  } else {
    return count + ” Hold”;
  }
  // Only change code above this line
}
console.log(cc(3));
console.log(cc(2));
console.log(cc(‘A’));
console.log(cc(10));
console.log(cc(‘K’));
1 Bet
2 Bet
1 Bet
0 Hold
-1 Hold
let count = 0;
function cc(card) {
  // Only change code below this line
  var regex = /[JQKA]/;
  if (card > 1 && card < 7) {
    count++;
  } else if (card === 10 || regex.test(card)) {
    count–;
  }
  if (count > 0) return count + ” Bet”;
  return count + ” Hold”;
  // Only change code above this line
}

Build JavaScript Objects

const myDog = {
  // Only change code below this line
  “name”: “John”,
  “legs”: 4,
  “tails”: 1,
  “friends”: [“Bog”, “Tom”]
  // Only change code above this line
};

Accessing Object Properties with Dot Notation

// Setup
const testObj = {
  “hat”: “ballcap”,
  “shirt”: “jersey”,
  “shoes”: “cleats”
};
// Only change code below this line
const hatValue = testObj.hat;      // Change this line
const shirtValue = testObj.shirt;    // Change this line
// console.log(hatValue); ballcap
// console.log(shirtValue); jersey

Accessing Object Properties with Bracket Notation

// Setup
const testObj = {
  “an entree”: “hamburger”,
  “my side”: “veggies”,
  “the drink”: “water”
};
// Only change code below this line
const entreeValue = testObj[“an entree”];   // Change this line
const drinkValue = testObj[“the drink”];    // Change this line
// console.log(entreeValue); hamburger
// console.log(drinkValue); water

Accessing Object Properties with Variables

// Setup
const testObj = {
  12: “Namath”,
  16: “Montana”,
  19: “Unitas”
};
// Only change code below this line
const playerNumber = 16;  // Change this line
const player = testObj[playerNumber];   // Change this line
console.log(player);
Montana

Updating Object Properties

// Setup
const myDog = {
  “name”: “Coder”,
  “legs”: 4,
  “tails”: 1,
  “friends”: [“freeCodeCamp Campers”]
};
// Only change code below this line
myDog.name = “Happy Coder”;
console.log(myDog);
{ name: ‘Happy Coder’,
  legs: 4,
  tails: 1,
  friends: [ ‘freeCodeCamp Campers’ ] }

Add New Properties to a JavaScript Object

const myDog = {
  “name”: “Happy Coder”,
  “legs”: 4,
  “tails”: 1,
  “friends”: [“freeCodeCamp Campers”]
};
myDog.bark = “woof”;
console.log(myDog);
{ name: ‘Happy Coder’,
  legs: 4,
  tails: 1,
  friends: [ ‘freeCodeCamp Campers’ ],
  bark: ‘woof’ }

Delete Properties from a JavaScript Object

// Setup
const myDog = {
  “name”: “Happy Coder”,
  “legs”: 4,
  “tails”: 1,
  “friends”: [“freeCodeCamp Campers”],
  “bark”: “woof”
};
// Only change code below this line
delete myDog.tails;
console.log(myDog);
{ name: ‘Happy Coder’,
  legs: 4,
  friends: [ ‘freeCodeCamp Campers’ ],
  bark: ‘woof’ }

Using Objects for Lookups 不要使用switch if else

// Setup
function phoneticLookup(val) {
  let result = “”;
  // Only change code below this line
  // switch(val) {
  //   case “alpha”:
  //     result = “Adams”;
  //     break;
  //   case “bravo”:
  //     result = “Boston”;
  //     break;
  //   case “charlie”:
  //     result = “Chicago”;
  //     break;
  //   case “delta”:
  //     result = “Denver”;
  //     break;
  //   case “echo”:
  //     result = “Easy”;
  //     break;
  //   case “foxtrot”:
  //     result = “Frank”;
  // }
  const lookup = {
    “alpha”:”Adams”,
    “bravo”:”Boston”,
    “charlie”:”Chicago”,
    “delta”:”Denver”,
    “echo”:”Easy”,
    “foxtrot”:”Frank”
  };
  result = lookup[val];
  // Only change code above this line
  return result;
}
// console.log(phoneticLookup(“charlie”)); Chicago

Testing Objects for Properties

function checkObj(obj, checkProp) {
  // Only change code below this line
  if (obj.hasOwnProperty(checkProp)){
   return obj[checkProp];  // 不能用.checkProp要用[]
  } else {
    return “Not Found”;
  }
  // Only change code above this line
}
checkObj({gift: “pony”, pet: “kitten”, bed: “sleigh”}, “gift”)
const myObj = {
  gift: “pony”,
  pet: “kitten”,
  bed: “sleigh”
}
console.log(myObj.gift);
console.log(myObj[“gift”]);
pony

pony


Manipulating Complex Objects

JavaScript Object Notation or JSON is a related data interchange format used to store data.

const myMusic = [
  {
    “artist”: “Billy Joel”,
    “title”: “Piano Man”,
    “release_year”: 1973,
    “formats”: [
      “CD”,
      “8T”,
      “LP”
    ],
    “gold”: true
  },
  // Add a new album
  {
    “artist”: “Billy Joel”,
    “title”: “Piano Man”,
    “release_year”: 1973,
    “formats”: [“CD”, “8T”, “LP”]
  }
];
console.log(myMusic);

Accessing Nested Objects

const myStorage = {
  “car”: {
    “inside”: {
      “glove box”: “maps”,
      “passenger seat”: “crumbs”
     },
    “outside”: {
      “trunk”: “jack”
    }
  }
};
const gloveBoxContents = myStorage.car.inside[“glove box”];
console.log(gloveBoxContents);

Accessing Nested Arrays

const myPlants = [
  {
    type: “flowers”,
    list: [
      “rose”,
      “tulip”,
      “dandelion”
    ]
  },
  {
    type: “trees”,
    list: [
      “fir”,
      “pine”,
      “birch”
    ]
  }
];
const secondTree = myPlants[1].list[1];
console.log(secondTree);
// Setup
const recordCollection = {
  2548: {
    albumTitle: ‘Slippery When Wet’,
    artist: ‘Bon Jovi’,
    tracks: [‘Let It Rock’, ‘You Give Love a Bad Name’]
  },
  2468: {
    albumTitle: ‘1999’,
    artist: ‘Prince’,
    tracks: [‘1999’, ‘Little Red Corvette’]
  },
  1245: {
    artist: ‘Robert Palmer’,
    tracks: []
  },
  5439: {
    albumTitle: ‘ABBA Gold’
  }
};
// Only change code below this line
function updateRecords(records, id, prop, value) {
  return records;
}
updateRecords(recordCollection, 5439, ‘artist’, ‘ABBA’);

 


Iterate with JavaScript While Loops

// Setup
const myArray = [];
let i = 5;
while (i >= 0) {
  myArray.push(i);
  i–;
}
// Only change code below this line
console.log(myArray);
[ 5, 4, 3, 2, 1, 0 ]
const ourArray = [];
let y = 0;
while (y <= 5) {
  ourArray.push(y);
  y++;
}
console.log(ourArray);
[ 0, 1, 2, 3, 4, 5 ]

Iterate with JavaScript For Loops

// Setup
const myArray = [];
// Only change code below this line
for (let y = 1; y < 6; y++){
  myArray.push(y);
}
console.log(myArray)
[ 1, 2, 3, 4, 5 ]
const ourArray = [];
for (let i = 0; i < 5; i++) {
  ourArray.push(i);
}
console.log(ourArray);
[0, 1, 2, 3, 4]

Iterate Odd Numbers With a For Loop 用For數奇數

// Setup
const myArray = [];
// Only change code below this line
for (let i = 1; i < 10; i += 2) {
  myArray.push(i);
}
console.log(myArray);
[ 1, 3, 5, 7, 9 ]

Count Backwards With a For Loop 用For倒過來數奇數

// Setup
const myArray = [];
// Only change code below this line
for (let i = 9; i > 0; i -= 2) {
  myArray.push(i);
}
console.log(myArray);
[ 9, 7, 5, 3, 1 ]

Iterate Through an Array with a For Loop

// Setup
const myArr = [2, 3, 4, 5, 6];
// Only change code below this line
var total = 0;
for (let i = 0; i < myArr.length; i++){
  // console.log(myArr[i]);
  total = total + myArr[i];
  // console.log(total);
}
console.log(total); 20
total + myArr[0] -> 0 + 2 = 2
total + myArr[1] -> 2 + 3 = 5
total + myArr[2] -> 5 + 4 = 9
total + myArr[3] -> 9 + 5 = 14
total + myArr[4] -> 14 + 6 = 20

Nesting For Loops 迴圈裏面還有迴圈

function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line
  for (let i = 0; i < arr.length; i++){
    for (let j = 0; j < arr[i].length; j++){
      product = product * arr[i][j]
      // console.log(product);
    }
    // console.log(product);
  }
  // console.log(product);
  // Only change code above this line
  return product;
}
// console.log(multiplyAll([[1], [2], [3]]));
console.log(multiplyAll([[1, 2], [3, 4], [5, 6, 7]]));

Iterate with JavaScript Do…While Loops

Essentially, a do...while loop ensures that the code inside the loop will run at least once.

 

// Setup
const myArray = [];
let i = 10;
// Only change code below this line
do {
  myArray.push(i);
  i++;
} while (i < 10);
console.log(myArray);  =>> [10]
console.log(i);  =>> 11

Replace Loops using Recursion  遞回函式(recursive function)

function sum(arr, n) {
  // Only change code below this line
    if (n <= 0) {
      return 0;
    } else {
      return sum(arr, n – 1) + arr[n – 1];
    }
  // Only change code above this line
}
console.log(sum([1], 0));
console.log(sum([2, 3, 4], 1));

Profile Lookup (not understand)

要去查JSON資料庫metadata裡面的資料是否有 firstName, lastName, number, likes,查完會得到對應的值
// Setup
const contacts = [
  {
    firstName: “Akira”,
    lastName: “Laine”,
    number: “0543236543”,
    likes: [“Pizza”, “Coding”, “Brownie Points”],
  },
  {
    firstName: “Harry”,
    lastName: “Potter”,
    number: “0994372684”,
    likes: [“Hogwarts”, “Magic”, “Hagrid”],
  },
  {
    firstName: “Sherlock”,
    lastName: “Holmes”,
    number: “0487345643”,
    likes: [“Intriguing Cases”, “Violin”],
  },
  {
    firstName: “Kristian”,
    lastName: “Vos”,
    number: “unknown”,
    likes: [“JavaScript”, “Gaming”, “Foxes”],
  },
];
// prop = perperty
function lookUpProfile(name, prop) {
  // Only change code below this line
  for (let x = 0; x < contacts.length; x++){
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)){
         return contacts[x][prop];
        } else {
         return “No such property”;
        }
      }
    }
  return “No such contact”;
  // Only change code above this line
}
console.log(lookUpProfile(“Harry”, “likes”));
[ ‘Hogwarts’, ‘Magic’, ‘Hagrid’ ]

 


Generate Random Fractions with JavaScript 產生隨機從0-1生成的數字

function randomFraction() {
  // Only change code below this line
  return Math.random();
  // Only change code above this line
}
console.log(randomFraction());
函數 Math.random() 會回傳一個偽隨機小數 (pseudo-random) 介於0到1之間(包含 0,不包含1) ,大致符合數學與統計上的均勻分佈 (uniform distribution) ,您可以選定想要的數字區間,它會透過演算法被產生並且不允許使用者自行跳選或重設成特定數字。

Generate Random Whole Numbers with JavaScript 產生隨機的正整數

function randomWholeNum() {
  // Only change code below this line
  return Math.floor(Math.random() * 10);
}
// 先產生0-1之間的小數
// 放大10倍
// 然後再取最接近的整數
console.log(randomWholeNum());

Generate Random Whole Numbers within a Range 產生一個隨機有範圍的整數

Create a function called randomRange that takes a range myMin and myMax and returns a random whole number that’s greater than or equal to myMin, and is less than or equal to myMax, inclusive.

function randomRange(myMin, myMax) {
  // Only change code below this line
  return Math.floor(Math.random() * (myMax – myMin + 1)) + myMin;
  // Only change code above this line
}
console.log(randomRange(0, 10));
0 1 2 3 4 5 6 7 8 9 10 都有可能

 


Use the parseInt Function 將字串變成整數

function convertToInteger(str) {
  return parseInt(str);
}
console.log(convertToInteger(“56”));
console.log(convertToInteger(“77”));
console.log(convertToInteger(“JamesBond”));

Use the parseInt Function with a Radix

function convertToInteger(str) {
  return parseInt(str, 2);
}
convertToInteger(“10011”);
console.log(convertToInteger(“1”)); //1
console.log(convertToInteger(“10”)); //2
console.log(convertToInteger(“100”)); //4
console.log(convertToInteger(“1000”)); //8
console.log(convertToInteger(“10000”)); //16
console.log(convertToInteger(“10001”)); //17
console.log(convertToInteger(“10010”)); //18
console.log(convertToInteger(“10011”)); //19
console.log(convertToInteger(“100000”)); //32
console.log(convertToInteger(“111001”)); //57

radix從 2 到 36,能代表該進位系統的數字。例如說指定 10 就等於指定十進位。一定要定義這個參數以避免他人的困惑、也好預估函式的行為。如果沒有指定 radix 的話,給出的結果會按照實做不同而異,請注意,通常預設值不是 10 進位。


Use the Conditional (Ternary) Operator

function checkEqual(a, b) {
  return a === b ? “Equal” : “Not Equal”;
}

a ===b 是條件

True  是 “Equal”

False 是 “Not Equal”


Use Multiple Conditional (Ternary) Operators

簡化函數的寫法
function findGreaterOrEqual(a, b) {
  if (a === b) {
    return "a and b are equal";
  }
  else if (a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}

The above function can be re-written using multiple conditional operators:

function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" 
    : (a > b) ? "a is greater" 
    : "b is greater";
}
function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}
原本的if else if else寫法
function checkSign(num) {
  if (num > 0) {
    return "positive";
  }
  else if (num < 0) {
    return "negative";
  }
  else {
    return "zero";
  }
}
function checkSign(num) {
  return (num > 0) ? “positive” : (num < 0) ? “negative” : “zero”;
}
console.log(checkSign(10));
console.log(checkSign(-10));
console.log(checkSign(0));
positive
negative
zero

 


Use Recursion to Create a Countdown

// Only change code below this line
function countdown(n){
  if (n < 1) {
    return [];
  } else {
    const countArray = countdown(n – 1);
    countArray.unshift(n); //unshift 把n加到一開始的array
    return countArray;
  }
}
// Only change code above this line
console.log(countdown(10));

Use Recursion to Create a Range of Numbers

let countArray = [];
function rangeOfNumbers(startNum, endNum) {
  if (endNum – startNum === 0) {
    return [startNum];
  } else {
    const countArray = rangeOfNumbers(startNum, endNum – 1);
    countArray.push(endNum);
    return countArray;
  }
};
rangeOfNumbers(6, 7)

最後修改日期: 2022 年 4 月 23 日

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。