Open NBR-hugh opened 7 years ago
myVar = 5;
myNum = myVar;
Assigns 5 to myVar and then resolves myVar to 5 again and assigns it to myNum.
程序:
// Initialize these three variables
var a=5;
var b=10;
var c="I am a";
// Do not change code below this line
a = a + 1;
b = b + 5;
c = c + " String!";
结果: a=6,b=15,c=‘I am a String!’
Add Two Numbers with JavaScript
var sum = 10 + 10; var difference = 45 - 33; var product = 8 * 10; var quotient = 66 / 33;
连加 You can easily increment or add one to a variable with the ++ operator. i++; is the equivalent of i = i + 1;
连减 You can easily decrement or decrease a variable by one with the -- operator. i--; is the equivalent of i = i - 1;
小数
`var myDecimal = 1.1;`
乘
var product = 2.0 * 2.5;
除
var quotient = 4.4 / 2.0;
取余
var remainder = 11 % 3;
myVar = myVar - 5; will subtract 5 from myVar. This can be rewritten as: myVar -= 5;
学会设置简单函数
function convertToF(celsius) {
var fahrenheit;
// Only change code below this line
fahrenheit = 9 * celsius/5 +32;
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
* var myName = "your name";
"your name" is called a string literal. It is a string because it is a series of zero or more characters enclosed in single or double quotes.
In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash () in front of the quote.
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
!!! 小心\不是/
If you have a string with many double quotes, this can be difficult to read and write. Instead, use single quotes:
'This string has "double quotes" in it. And "probably" lots of them.'
Code Output \' single quote \" double quote \ backslash \n newline \r carriage ##return \t tab \b backspace \f form feed Note that the backslash itself must be escaped in order to display as a backslash.
程序:
var myStr ="FirstLine\n\\SecondLine\\\rThirdLine"
字符串的不变性
错误:
var myStr = "Bob";
myStr[0] = "J";
正确:
var myStr = "Bob";
myStr = "Job";
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = myAdjective +" " + myNoun + " " + myVerb + " " + myAdverb + ".";
// Your code below this line
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("FISH", "big", "ran", "quickly");
var ourArray = [["the universe", 42], ["everything", 101010]];
程序:
var array = [1,2,3];
array[0]; // equals 1
var data = array[1]; // equals 2
结果:
myArray = [1,2,3], myData = 1
var ourArray = [3,2,1];
ourArray[0] = 1; // equals [1,2,1]
var arr = [1,2,3]; arr.push(4); // arr is now [1,2,3,4]
function ourReusableFunction() { console.log("Heyya, World"); }
ourReusableFunction();
var someVar = "Hat"; function myFun() { var someVar = "Head"; return someVar; }
The function myFun will return "Head" because the local version of the variable is present.
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
将函数计算值赋予变量 var changed = 0;
function change(num) { return (num + 5) / 3; }
changed = change(10);
和函数 ourSum = sum(5, 12);
这个挑战卡住了很久,最终在帮助论坛里得到答案
这个挑战让我明白了return命令的作用:除了输出调用函数的值并跳回主函数,还可以可以执行命令与运算,因此在我的程序中.shift()运行了两次,致使无法通过挑战:
function nextInLine(arr, item) {
// Your code here
arr.push (item);
arr.shift();
return arr.shift(); // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
function welcomeToBooleans() {
// Only change code below this line.
return true; // Change this line
// Only change code above this line.
}
function ourTrueOrFalse(isItTrue) {
if (isItTrue) {
return "Yes, it's true";
}
return "No, it's false";
}
ourTrueOrFalse(True);
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
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";
}
}
说明:<5在最外层,输入4时输出"Less than 5",而<10在最外层时,输入4时输出"Less than 10",虽然没错但不够准确,因此在嵌套时注意逻辑顺序,使得输出结果更准确;
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";
}
return "Change Me";
// Only change code above this line
}
// Change this value to test
testSize(90);
实现: num < 5 - return "Tiny" num < 10 - return "Small" num < 15 - return "Medium" num < 20 - return "Large" num >= 20 - return "Huge"
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
1 == 1 // true 1 == 2 // false 1 == '1' // true "3" == 3 // true
Examples
3 === 3 // true 3 === '3' // false In the second example, 3 is a Number type and '3' is a String type.
Examples
1 != 2 // true 1 != "1" // false 1 != '1' // false 1 != true // false 0 != false // false
Examples
3 !== 3 // false 3 !== '3' // true 4 !== 3 // true
Examples
5 > 3 // true 7 > '3' // true 2 > 3 // false '1' > 9 // false
if (num > 5) {
if (num < 10) {
return "Yes";
}
}
return "No";
will only return "Yes" if num is between 6 and 9 (6 and 9 included). The same logic can be written as:
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
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;
}
// Change this value to test
caseInSwitch(1);
switch (num) { case value1: statement1; break; case value2: statement2; break; ... default: defaultStatement; }
- value 可以是数字,也可以是字符串;
- 注意 ; 与 :
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;
}
// Change this value to test
sequentialSizes(1);
function isLess(a, b) {
// Fix this code
return a < b;
}
可代替
function isLess(a, b) {
if (a < b) {
return true;
} else {
return false;
}
}
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
similar to an array,two ways to access the properties of an object
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
ourDog.name = "Happy Camper";
myDog.bark = "woof";
delete ourDog.bark;
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.name = "Happy Camper";
myDog.bark = "woof";
delete ourDog.bark;
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"
var value = 2;
alpha[value]; // "Y"
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
var result = myObj.hasOwnProperty(checkProp);
if (result === true){
return myObj[checkProp];
}else{
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("gift");
var ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP" ],
"gold": true
}
];
var gloveBoxContents = myStorage.car.inside["glove box"] ;
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
// Only change code below this line
var gloveBoxContents = myStorage.car.inside["glove box"] ;
var secondTree = myPlants[1].list[1];
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
// Only change code below this line
var secondTree = myPlants[1].list[1];
首先按照要求逐条使用if语句实现:
If prop isn't "tracks" and value isn't empty (""), update or set the value for that record album's property.
Your function must always return the entire collection object.
There are several rules for handling incomplete data:
If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the album's corresponding property.
If prop is "tracks" and value isn't empty (""), push the value onto the end of the album's existing tracks array.
If value is empty (""), delete the given prop property from the album.
得出程序:
function updateRecords(id, prop, value) {
if ( prop != "tracks"&& value !==""){
collection[id][prop]=value;
}
if (prop == "tracks" && collection[id].hasOwnProperty("tracks") === false){
var tracks;
collection[id][prop]=[value];
}
if (prop == "tracks"&&value !== ""){ //meet the 4th 5th ? 2th和 4th 没有区别
collection[id][prop].push(value);
}
if (value === ""){ // meet 3th 5th 6th
delete collection[id][prop];
}
第一次没有一条要求符合,就一条一体if语句测试,发现问题在于这个if语句:
if (prop == "tracks" && collection[id].hasOwnProperty("tracks") === false){
var tracks;
collection[id][prop]=[value];
3个错误:
1.出问题了一条条代码去尝试,定位错误源,用小黄鸭调试法进行排查。 2,没有什么问题是细心排查解决不了的,最大的敌人是畏难与烦躁的内心,提高大脑的运算速度,想可能的原因,测试,验证或者排除,再不断尝试,问题就解决了。
for (var i = 0;i < 6; i++){
myArray.push(i);
}
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i=0;i<3;i++){
for(var j=0;j<arr[i].length;j++){
product *= arr[i][j];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
var myArray = [];
var i=0;
while (i<5){
myArray.push(i);
i++;
}
[If both are true, then return the "value" of that property. 有名字有属性,输出该属性的值 If firstName does not correspond to any contacts then return "No such contact" 没有名字,输出文字"No such contact" If prop does not correspond to any valid properties then return "No such property" 没有属性,输出文字"No such property"
- 所要搜索文件的程序:
var 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"]
}
];
然后循环,重复以上过程,直至历遍每个元素; 困难在于:如果过直接输出,直接return,那么就跳出函数,无法循环历遍所有元素,因此想到用变量j指代输出的3种情况,采用0,1与-1在循环下计算累加结果,用a记录符合两真的数组号码,然后再根据j的值进行return输出。
function lookUpProfile(firstName, prop){
// Only change code below this line
var j=0;
var a=0;
for (var i=0;i<4;i++){
if ( contacts[i].firstName !== firstName){
j += 0;}
else if(contacts[i].hasOwnProperty(prop) === false){
j -= 1;}
else {j += 1; a = i; }
}
switch(j){
case 0:
return "No such contact";
case 1:
return contacts[a][prop];
case -1:
return "No such property";
}
Regular expressions are used to find certain words or patterns inside of strings. For example, if we wanted to find the word the in the string The dog chased the cat, we could use the following regular expression: /the/gi Let's break this down a bit:
/ is the start of the regular expression.
the is the pattern we want to match.
/ is the end of the regular expression.
g means global, which causes the pattern to return all matches in the string, not just the first one.
i means that we want to ignore the case (uppercase or lowercase) when searching for the pattern.
One such selector is the digit selector \d which is used to retrieve one digit (e.g. numbers 0 to 9) in a string.
In JavaScript, it is used like this: /\d/g.
Appending a plus sign (+) after the selector, e.g. /\d+/g allows this regular expression to match one or more digits
var testString = "There are 3 cats but 4 dogs.";
// Only change code below this line.
var expression = /\d+/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
**var digitCount = testString.match(expression).length;**
We can also use regular expression selectors like \s to find whitespace in a string.
The whitespace characters are " " (space), \r (the carriage return), \n (newline), \t (tab), and \f (the form feed).
var expression = /\s+/g;
You can invert any match by using the uppercase version of the regular expression selector.
For example, \s will match any whitespace, and \S will match anything that isn't whitespace.
Comment your JavaScript Code
为代码添加注释的2种方式