JavaScript基础

JavaScript基础这一部分算是非常入门级的内容,包括JS的基本变量类型以及相应的基本操作。这一部分就不做过多的总结了,习题解答如下:

Introduction to JavaScript

  • Comment Your JavaScript Code

    //This is a single-line comment
    /* This is a 
        multiline comment */
    
  • Declare JavaScript Variables

    var myName;
    
  • Storing Values with the Assignment Operator

    a = 7;
    b = a; 
    
  • Initializing Variables with the Assignment Operator

    var a = 9;
    
  • Understanding Uninitialized Variables

    var a = 5;
    var b = 10;
    var c = "I am a";
    
  • Understanding Case Sensitivity in Variables

    // Declarations
    var studlyCapVar;
    var properCamelCase;
    var titleCaseOver;
    
    // Assignments
    studlyCapVar = 10;
    properCamelCase = "A String";
    titleCaseOver = 9000;
    
  • Add Two Numbers with JavaScript

    var sum = 10 + 10;
    
  • Subtract One Number from Another with JavaScript

    var difference = 45 - 33;
    
  • Multiply Two Numbers with JavaScript

    var product = 8 * 10;
    
  • Divide One Number by Another with JavaScript

    var quotient = 66 / 33;
    
  • Increment a Number with JavaScript

    myVar++;
    
  • Decrement a Number with JavaScript

    myVar--;
    
  • Create Decimal Numbers with JavaScript

    var myDecimal = 3.2;
    
  • Multiply Two Decimals with JavaScript

    var product = 2.0 * 2.5;
    
  • Divide One Decimal by Another with JavaScript

    var quotient = 4.4 / 2.0; 
    
  • Finding a Remainder in JavaScript

    var remainder = 11 % 3;
    
  • Compound Assignment With Augmented Addition

    a += 12;
    b += 9;
    c += 7;
    
  • Compound Assignment With Augmented Subtraction

    a -= 6;
    b -= 15;
    c -= 1;
    
  • Compound Assignment With Augmented Multiplication

    a *= 5;
    b *= 3;
    c *= 10;
    
  • Compound Assignment With Augmented Division

    a /= 12;
    b /= 4;
    c /= 11;
    
  • Declare String Variables

    var myFirstName = "Nikkkki";
    var myLastName = "Xu";
    
  • Escaping Literal Quotes in Strings

    var myStr = "I am a \"double quoted\" string inside \"double quotes\"."; 
    
  • Quoting Strings with Single Quotes

    var myStr = 'Link';
    
  • Escape Sequences in Strings

    var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
    
    JavaScript基础_第1张图片
    image.png
  • Concatenating Strings with Plus Operator

    var myStr = "This is the start. " + "This is the end.";
    
  • Concatenating Strings with the Plus Equals Operator

    var myStr = "This is the first sentence. ";
    myStr += "This is the second sentence.";
    
  • Constructing Strings with Variables

    var myName = "Nikkkki";
    var myStr = "My name is " + myName + " and I am well!";
    
  • Appending Variables to Strings

    var someAdjective = "interesting";
    var myStr = "Learning to code is ";
    myStr += someAdjective;
    
  • Find the Length of a String

    lastNameLength = lastName.length;
    
  • Use Bracket Notation to Find the First Character in a String

    firstLetterOfLastName = lastName[0];
    
  • Understand String Immutability

    myStr = "Hello World";
    
  • Use Bracket Notation to Find the Nth Character in a String

    var thirdLetterOfLastName = lastName[2];
    
  • Use Bracket Notation to Find the Last Character in a String

    var lastLetterOfLastName = lastName[lastName.length - 1];
    
  • Use Bracket Notation to Find the Nth-to-Last Character in a String

    var secondToLastLetterOfLastName = lastName[lastName.length-2];
    
  • Word Blanks

    function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
      // Your code below this line
      var result = "";
        result = myNoun + " " + myAdjective + " " + myVerb + " " + myAdverb;
      // Your code above this line
      return result;
    }
    
  • Store Multiple Values in one Variable using JavaScript Arrays

    var myArray = ["kitty", 5];
    
  • Nest one Array within Another Array

    var myArray = [["dog", 5], ["cat", 3]];
    
  • Access Array Data with Indexes

    var myData = myArray[0];
    
  • Modify Array Data With Indexes

    myArray[0] = 45;
    
  • Access Multi-Dimensional Arrays With Indexes

    var myData = myArray[2][1];
    
  • Manipulate Arrays With push()

    myArray.push(["dog", 3]);
    
  • Manipulate Arrays With pop()

    var removedFromMyArray = myArray.pop();
    
  • Manipulate Arrays With shift()

    var removedFromMyArray = myArray.shift();
    
  • Manipulate Arrays With unshift()

    myArray.unshift(["Paul", 35]);
    
  • Shopping List

    var myList = [["milk", 4], ["biscuits", 22], ["chocolate", 6], ["honey", 2], ["ice cream", 9]];
    
  • Write Reusable JavaScript with Functions

    function reusableFunction() {
        console.log("Hi World");
    }
    reusableFunction();
    
  • Passing Values to Functions with Arguments

    function functionWithArgs(param1, param2) {
      console.log(param1 + param2);
    }
    functionWithArgs(3, 2);
    
  • Global Scope and Functions

    // Declare your variable here
    var myGlobal = 10;
    
    function fun1() {
      // Assign 5 to oopsGlobal Here
      oopsGlobal = 5;
    }
    
    // Only change code above this line
    function fun2() {
      var output = "";
      if (typeof myGlobal != "undefined") {
        output += "myGlobal: " + myGlobal;
      }
      if (typeof oopsGlobal != "undefined") {
        output += " oopsGlobal: " + oopsGlobal;
      }
      console.log(output);
    }
    
  • Local Scope and Functions

    function myLocalScope() {
      'use strict'; // you shouldn't need to edit this line
      var myVar = "hello";
      console.log(myVar);
    }
    myLocalScope();
    
    // Run and check the console
    // myVar is not defined outside of myLocalScope
    // console.log(myVar);
    
  • Global vs. Local Scope in Functions

    function myOutfit() {
      // Only change code below this line
      var outerWear = "sweater";
      // Only change code above this line
      return outerWear;
    }
    
  • Return a Value from a Function with Return

    function timesFive(num) {
      return num * 5;
    }
    console.log(timesFive(2));
    
  • Understanding Undefined Value returned from a Function

    function addFive() {
      sum = sum + 5;
    }
    
  • Assignment with a Returned Value

    processed = processArg(7);
    
  • Stand in Line

    function nextInLine(arr, item) {
      // Your code here
      arr.push(item);
      var result = arr.shift();
      return result;  // Change this line
    }
    
  • Understanding Boolean Values

    function welcomeToBooleans() {
      // Only change code below this line.
    
      return true; // Change this line
    
      // Only change code above this line.
    }
    
  • 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

    function testEqual(val) {
      if (val == 12) { // Change this line
        return "Equal";
      }
      return "Not Equal";
    }
    
  • Comparison with the Strict Equality Operator

    function compareEquality(a, b) {
      if (a === b) { // Change this line
        return "Equal";
      }
      return "Not Equal";
    }
    
  • Practice comparing different values

    function testNotEqual(val) {
      if (val!=99) { // Change this line
        return "Not Equal";
      }
      return "Equal";
    }
    
  • Comparison with the Inequality Operator

    function testStrictNotEqual(val) {
      // Only Change Code Below this Line
      if (val !== 17) {
      // Only Change Code Above this Line
        return "Not Equal";
      }
      return "Equal";
    }
    
  • Comparison with the Strict Inequality 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";
    }
    
  • Comparison with the Greater Than 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";
    }
    
  • Comparison with the Greater Than Or Equal To 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 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";
    }
    
  • Comparison with the Less Than Or Equal To Operator

    function testLogicalAnd(val) {
      // Only change code below this line
      if (val <= 50 && val >= 25) {
        return "Yes";
      }
      // Only change code above this line
      return "No";
    }
    
  • Comparisons with the Logical And Operator

    function testLogicalOr(val) {
      // Only change code below this line
      if (val > 20 || val < 10) {
        return "Outside";
      }
      // Only change code above this line
      return "Inside";
    }
    
  • Comparisons with the Logical Or Operator

    function testElse(val) {
      var 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;
    }
    
  • Introducing Else 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";
      }
    }
    
  • 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";
      }
    }
    
  • 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
    }
    
  • Golf Code

    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
    }
    
  • Selecting from Many Options with Switch Statements

    function caseInSwitch(val) {
      var 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;  
    }
    
  • Adding a Default Option in Switch Statements

    function switchOfStuff(val) {
      var 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;  
    }
    
  • Multiple Identical Options in Switch Statements

    function sequentialSizes(val) {
      var 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;  
    }
    
  • Replacing If Else Chains with Switch

    function chainToSwitch(val) {
      var 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) {
      // Fix this code
        return a < b;
    }
    
  • Return Early Pattern for Functions

    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));
    }
    
  • Counting Cards

    function cc(card) {
      // Only change code below this line
      switch(card) {
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
          count += 1;
          break;
        case 10:
        case 'J':
        case 'Q':
        case 'K':
        case 'A':
          count -= 1;
          break;
      }
      var str ='';
      if(count > 0) {
        str = "Bet";
      } else {
        str = "Hold";
      } 
      return count + " " + str;
      // Only change code above this line
    }
    
  • Build JavaScript Objects

    var myDog = {
      "name" : "Stone",
      "legs": 4,
      "tails": 1,
      "friends": ["Pepe"]
    };
    
  • Accessing Object Properties with Dot Notation

    var hatValue = testObj.hat;      // Change this line
    var shirtValue = testObj.shirt;    // Change this line
    
  • Accessing Object Properties with Bracket Notation

    var entreeValue = testObj["an entree"];   // Change this line
    var drinkValue = testObj["the drink"];    // Change this line
    
  • Accessing Object Properties with Variables

    var playerNumber = 16;       // Change this Line
    var player = testObj[playerNumber];   // Change this Line
    
  • Updating Object Properties

    myDog.name = "Happy Coder";
    
  • Add New Properties to a JavaScript Object

    myDog.bark = "woof";
    
  • Delete Properties from a JavaScript Object

    delete myDog.tails;
    
  • Using Objects for Lookups

    function phoneticLookup(val) {
      var result = "";
      // Only change code below this line
      var lookup = {
        "alpha": "Adams",
        "bravo": "Boston",
        "charlie": "Chicago",
        "delta": "Denver",
        "echo": "Easy",
        "foxtrot": "Frank"
      }
      result = lookup[val];
      // Only change code above this line
      return result;
    }
    
  • Testing Objects for Properties

    function checkObj(checkProp) {
      // Your Code Here
      if(myObj.hasOwnProperty(checkProp)) {
        return myObj[checkProp];
      }
      return "Not Found";
    }
    
  • Manipulating Complex Objects

    var myMusic = [
      {
        "artist": "Billy Joel",
        "title": "Piano Man",
        "release_year": 1973,
        "formats": [ 
          "CD",
          "8T",
          "LP"
        ],
        "gold": true
      },
      // Add record here
      {
        "artist": "Alicia Keys",
        "title": "If I ain't got you",
        "release_year": 2000,
        "formats": [
          "CD",
          "LP"
        ]
      }
    ];
    
  • Accessing Nested Objects

    var gloveBoxContents = myStorage.car.inside["glove box"];
    
  • Accessing Nested Arrays

    var secondTree = myPlants[1].list[1];
    
  • Record Collection

    function updateRecords(id, prop, value) {
      if(prop !== "tracks" && value !== "") {
        collection[id][prop] = value;
      } else if(prop === "tracks" && !collection[id].hasOwnProperty("tracks")) {
        collection[id].tracks = [];
        collection[id].tracks.push(value);
      } else if (prop === "tracks" && value !== "") {
        collection[id].tracks.push(value);
      } else if (value === "") {
        delete collection[id][prop];
      }
      return collection;
    }
    
  • Iterate with JavaScript While Loops

    var i = 0;
    while(i < 5) {
      myArray.push(i);
      i ++;
    }
    
  • Iterate with JavaScript For Loops

    for(var i = 1; i < 6; i ++) {
        myArray.push(i);
    }
    
  • Iterate Odd Numbers With a For Loop

    for(var i = 1; i < 10; i += 2) {
      myArray.push(i);
    }
    
  • Count Backwards With a For Loop

    for(var i = 9; i > 0; i -= 2) {
      myArray.push(i);
    }
    
  • Iterate Through an Array with a For Loop

    var total = 0;
    for(var i = 0; i < myArr.length; i ++) {
      total += myArr[i];
    }
    
  • Nesting For Loops

    function multiplyAll(arr) {
      var product = 1;
      // Only change code below this line
      for(var i = 0; i < arr.length; i ++) {
        for(var j = 0; j 
  • Iterate with JavaScript Do...While Loops

    do {
      myArray.push(i);
      i++
    } while(i<5);
    
  • Profile Lookup

    function lookUpProfile(name, prop){
    // Only change code below this line
      for(var i = 0; i < contacts.length; i ++) {
        if(contacts[i].firstName === name) {
          if(contacts[i].hasOwnProperty(prop)) {
            return contacts[i][prop];
          } else {
            return "No such property";
          }
        } 
      }
      return "No such contact";
    // Only change code above this line
    }
    
  • Generate Random Fractions with JavaScript

    function randomFraction() {
      // Only change code below this line.
      return Math.random();
      // Only change code above this line.
    }
    
  • Generate Random Whole Numbers with JavaScript

    function randomWholeNum() {
      // Only change code below this line.
      return Math.floor(Math.random()*10);
    }
    
  • Generate Random Whole Numbers within a Range

    function randomRange(myMin, myMax) {
      return Math.floor(Math.random()*(myMax-myMin+1)) + myMin; // Change this line
    }
    
  • Use the parseInt Function

    function convertToInteger(str) {
      return parseInt(str);
    }
    
  • Use the parseInt Function with a Radix

    function convertToInteger(str) {
      return parseInt(str, 2);
    }
    
  • Use the Conditional (Ternary) Operator

    function checkEqual(a, b) {
      return a === b ? true : false;
    }
    
  • Use Multiple Conditional (Ternary) Operators

    function checkSign(num) {
      return num > 0 ? "positive" : (num === 0) ? "zero" : "negative";
    }
    

你可能感兴趣的:(JavaScript基础)