JavaScript基础这一部分算是非常入门级的内容,包括JS的基本变量类型以及相应的基本操作。这一部分就不做过多的总结了,习题解答如下:
Introduction to JavaScript
-
1
2
3//This is a single-line comment
/* This is a
multiline comment */ -
1
var myName;
Storing Values with the Assignment Operator
1
2a = 7;
b = a;Initializing Variables with the Assignment Operator
1
var a = 9;
Understanding Uninitialized Variables
1
2
3var a = 5;
var b = 10;
var c = "I am a";Understanding Case Sensitivity in Variables
1
2
3
4
5
6
7
8
9// Declarations
var studlyCapVar;
var properCamelCase;
var titleCaseOver;
// Assignments
studlyCapVar = 10;
properCamelCase = "A String";
titleCaseOver = 9000;Add Two Numbers with JavaScript
1
var sum = 10 + 10;
Subtract One Number from Another with JavaScript
1
var difference = 45 - 33;
Multiply Two Numbers with JavaScript
1
var product = 8 * 10;
Divide One Number by Another with JavaScript
1
var quotient = 66 / 33;
Increment a Number with JavaScript
1
myVar++;
Decrement a Number with JavaScript
1
myVar--;
Create Decimal Numbers with JavaScript
1
var myDecimal = 3.2;
Multiply Two Decimals with JavaScript
1
var product = 2.0 * 2.5;
Divide One Decimal by Another with JavaScript
1
var quotient = 4.4 / 2.0;
Finding a Remainder in JavaScript
1
var remainder = 11 % 3;
Compound Assignment With Augmented Addition
1
2
3a += 12;
b += 9;
c += 7;Compound Assignment With Augmented Subtraction
1
2
3a -= 6;
b -= 15;
c -= 1;Compound Assignment With Augmented Multiplication
1
2
3a *= 5;
b *= 3;
c *= 10;Compound Assignment With Augmented Division
1
2
3a /= 12;
b /= 4;
c /= 11;-
1
2var myFirstName = "Nikkkki";
var myLastName = "Xu"; Escaping Literal Quotes in Strings
1
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
Quoting Strings with Single Quotes
1
var myStr = '<a href="http://www.example.com" target="_blank">Link</a>';
-
1
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
Concatenating Strings with Plus Operator
1
var myStr = "This is the start. " + "This is the end.";
Concatenating Strings with the Plus Equals Operator
1
2var myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";Constructing Strings with Variables
1
2var myName = "Nikkkki";
var myStr = "My name is " + myName + " and I am well!";Appending Variables to Strings
1
2
3var someAdjective = "interesting";
var myStr = "Learning to code is ";
myStr += someAdjective;-
1
lastNameLength = lastName.length;
Use Bracket Notation to Find the First Character in a String
1
firstLetterOfLastName = lastName[0];
Understand String Immutability
1
myStr = "Hello World";
Use Bracket Notation to Find the Nth Character in a String
1
var thirdLetterOfLastName = lastName[2];
Use Bracket Notation to Find the Last Character in a String
1
var lastLetterOfLastName = lastName[lastName.length - 1];
Use Bracket Notation to Find the Nth-to-Last Character in a String
1
var secondToLastLetterOfLastName = lastName[lastName.length-2];
-
1
2
3
4
5
6
7function 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
1
var myArray = ["kitty", 5];
Nest one Array within Another Array
1
var myArray = [["dog", 5], ["cat", 3]];
Access Array Data with Indexes
1
var myData = myArray[0];
Modify Array Data With Indexes
1
myArray[0] = 45;
Access Multi-Dimensional Arrays With Indexes
1
var myData = myArray[2][1];
-
1
myArray.push(["dog", 3]);
-
1
var removedFromMyArray = myArray.pop();
Manipulate Arrays With shift()
1
var removedFromMyArray = myArray.shift();
Manipulate Arrays With unshift()
1
myArray.unshift(["Paul", 35]);
-
1
var myList = [["milk", 4], ["biscuits", 22], ["chocolate", 6], ["honey", 2], ["ice cream", 9]];
Write Reusable JavaScript with Functions
1
2
3
4function reusableFunction() {
console.log("Hi World");
}
reusableFunction();Passing Values to Functions with Arguments
1
2
3
4function functionWithArgs(param1, param2) {
console.log(param1 + param2);
}
functionWithArgs(3, 2);-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// 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);
} -
1
2
3
4
5
6
7
8
9
10function 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
1
2
3
4
5
6function 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
1
2
3
4function timesFive(num) {
return num * 5;
}
console.log(timesFive(2));Understanding Undefined Value returned from a Function
1
2
3function addFive() {
sum = sum + 5;
}Assignment with a Returned Value
1
processed = processArg(7);
-
1
2
3
4
5
6function nextInLine(arr, item) {
// Your code here
arr.push(item);
var result = arr.shift();
return result; // Change this line
} -
1
2
3
4
5
6
7function welcomeToBooleans() {
// Only change code below this line.
return true; // Change this line
// Only change code above this line.
} Use Conditional Logic with If Statements
1
2
3
4
5
6
7
8function 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
1
2
3
4
5
6function testEqual(val) {
if (val == 12) { // Change this line
return "Equal";
}
return "Not Equal";
}Comparison with the Strict Equality Operator
1
2
3
4
5
6function compareEquality(a, b) {
if (a === b) { // Change this line
return "Equal";
}
return "Not Equal";
}Practice comparing different values
1
2
3
4
5
6function testNotEqual(val) {
if (val!=99) { // Change this line
return "Not Equal";
}
return "Equal";
}Comparison with the Inequality Operator
1
2
3
4
5
6
7
8function 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
1
2
3
4
5
6
7
8
9function 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
1
2
3
4
5
6
7
8
9function 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
1
2
3
4
5
6
7
8
9function 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
1
2
3
4
5
6
7
8
9function 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
1
2
3
4
5
6
7
8function 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
1
2
3
4
5
6
7
8function 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
1
2
3
4
5
6
7
8
9
10
11function 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;
}-
1
2
3
4
5
6
7
8
9function 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
1
2
3
4
5
6
7
8
9function 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";
}
}-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function 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
} -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19function 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20function 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20function 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23function 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23function 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
1
2
3
4function isLess(a, b) {
// Fix this code
return a < b;
}Return Early Pattern for Functions
1
2
3
4
5
6
7
8function 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));
}-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27function 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
} -
1
2
3
4
5
6var myDog = {
"name" : "Stone",
"legs": 4,
"tails": 1,
"friends": ["Pepe"]
}; Accessing Object Properties with Dot Notation
1
2var hatValue = testObj.hat; // Change this line
var shirtValue = testObj.shirt; // Change this lineAccessing Object Properties with Bracket Notation
1
2var entreeValue = testObj["an entree"]; // Change this line
var drinkValue = testObj["the drink"]; // Change this lineAccessing Object Properties with Variables
1
2var playerNumber = 16; // Change this Line
var player = testObj[playerNumber]; // Change this Line-
1
myDog.name = "Happy Coder";
Add New Properties to a JavaScript Object
1
myDog.bark = "woof";
Delete Properties from a JavaScript Object
1
delete myDog.tails;
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function 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
1
2
3
4
5
6
7function checkObj(checkProp) {
// Your Code Here
if(myObj.hasOwnProperty(checkProp)) {
return myObj[checkProp];
}
return "Not Found";
}-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23var 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"
]
}
]; -
1
var gloveBoxContents = myStorage.car.inside["glove box"];
-
1
var secondTree = myPlants[1].list[1];
-
1
2
3
4
5
6
7
8
9
10
11
12
13function 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
1
2
3
4
5var i = 0;
while(i < 5) {
myArray.push(i);
i ++;
}Iterate with JavaScript For Loops
1
2
3for(var i = 1; i < 6; i ++) {
myArray.push(i);
}Iterate Odd Numbers With a For Loop
1
2
3for(var i = 1; i < 10; i += 2) {
myArray.push(i);
}Count Backwards With a For Loop
1
2
3for(var i = 9; i > 0; i -= 2) {
myArray.push(i);
}Iterate Through an Array with a For Loop
1
2
3
4var total = 0;
for(var i = 0; i < myArr.length; i ++) {
total += myArr[i];
}-
1
2
3
4
5
6
7
8
9
10
11function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(var i = 0; i < arr.length; i ++) {
for(var j = 0; j <arr[i].length; j ++) {
product *= arr[i][j];
}
}
// Only change code above this line
return product;
} Iterate with JavaScript Do…While Loops
1
2
3
4do {
myArray.push(i);
i++
} while(i<5);-
1
2
3
4
5
6
7
8
9
10
11
12
13
14function 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
1
2
3
4
5function randomFraction() {
// Only change code below this line.
return Math.random();
// Only change code above this line.
}Generate Random Whole Numbers with JavaScript
1
2
3
4function randomWholeNum() {
// Only change code below this line.
return Math.floor(Math.random()*10);
}Generate Random Whole Numbers within a Range
1
2
3function randomRange(myMin, myMax) {
return Math.floor(Math.random()*(myMax-myMin+1)) + myMin; // Change this line
}-
1
2
3function convertToInteger(str) {
return parseInt(str);
} Use the parseInt Function with a Radix
1
2
3function convertToInteger(str) {
return parseInt(str, 2);
}Use the Conditional (Ternary) Operator
1
2
3function checkEqual(a, b) {
return a === b ? true : false;
}Use Multiple Conditional (Ternary) Operators
1
2
3function checkSign(num) {
return num > 0 ? "positive" : (num === 0) ? "zero" : "negative";
}