NBR-hugh / freecodecamp-practice

Practice everyday
0 stars 0 forks source link

FCC:Basic JavaScript #12

Open NBR-hugh opened 7 years ago

NBR-hugh commented 7 years ago

Comment your JavaScript Code

为代码添加注释的2种方式

  1. // This is an in-line comment.
  2. /* This is a multi-line comment */

/* * Your output will go here. * Any console.log() -type * statements will appear in * your browser's DevTools * JavaScript console as well. /

NBR-hugh commented 7 years ago

Declare JavaScript Variables

变量

NBR-hugh commented 7 years ago

Storing Values with the Assignment Operator

赋值

myVar = 5;
myNum = myVar;

Assigns 5 to myVar and then resolves myVar to 5 again and assigns it to myNum.

NBR-hugh commented 7 years ago

Understanding Uninitialized Variables

未定义变量

程序:

// 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!’

NBR-hugh commented 7 years ago

Understanding Case Sensitivity in Variables

变量的大小写敏感

NBR-hugh commented 7 years ago

Add Two Numbers with JavaScript

加减乘除,注意数字有个空格的规范。

var sum = 10 + 10; var difference = 45 - 33; var product = 8 * 10; var quotient = 66 / 33;

NBR-hugh commented 7 years ago

Increment a Number with JavaScript

连加减

连加 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;

NBR-hugh commented 7 years ago

Create Decimal Numbers with JavaScript

小数

小数
`var myDecimal = 1.1;`  
乘
var product = 2.0 * 2.5;
除
var quotient = 4.4 / 2.0;
取余
var remainder = 11 % 3;
NBR-hugh commented 7 years ago

Compound Assignment With Augmented Subtraction

单个对象本身运算的简化写法

myVar = myVar - 5; will subtract 5 from myVar. This can be rewritten as: myVar -= 5;

NBR-hugh commented 7 years ago

Convert Celsius to Fahrenheit

摄氏度转华氏度

学会设置简单函数

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);
NBR-hugh commented 7 years ago

Declare String Variables

字符变量

* 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\"."; !!! 小心\不是/

NBR-hugh commented 7 years ago

Quoting Strings with Single Quotes

单引号的作用

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.'

NBR-hugh commented 7 years ago

15

Escape Sequences in Strings

字符中的逸出序列

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"

NBR-hugh commented 7 years ago

Use Bracket Notation to Find the First Character in a String

括号记法寻找字符串首字母

NBR-hugh commented 7 years ago

Understand String Immutability

字符串的不变性

错误:

var myStr = "Bob";
myStr[0] = "J";

正确:

var myStr = "Bob";
myStr = "Job";
NBR-hugh commented 7 years ago

Word Blanks

填词游戏

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");
NBR-hugh commented 7 years ago

Store Multiple Values in one Variable using JavaScript Arrays

在一个变量中存贮多个值(不同类型)-多重数组

NBR-hugh commented 7 years ago

Access Array Data with Indexes 数组

程序:

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]
NBR-hugh commented 7 years ago

Manipulate Arrays With push

push()函数为复杂数组的末尾添加元素

var arr = [1,2,3]; arr.push(4); // arr is now [1,2,3,4]

NBR-hugh commented 7 years ago

Manipulate Arrays With pop

.pop()函数将数组末位的元素剪切给某一变量

.shift()类似,剪切首位 <——>.unshift()反向添加

NBR-hugh commented 7 years ago

Write Reusable JavaScript with Functions

编写可复用的函数

控制台输出

function ourReusableFunction() { console.log("Heyya, World"); }

ourReusableFunction();

NBR-hugh commented 7 years ago

Local Scope and Functions/Global Scope and Functions

函数外设置的变量为全局变量,函数内为局部变量

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.

NBR-hugh commented 7 years ago

Return a Value from a Function with Return

函数:基础计算

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);

NBR-hugh commented 7 years ago

Stand in Line

这个挑战卡住了很久,最终在帮助论坛里得到答案

image

这个挑战让我明白了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));
NBR-hugh commented 7 years ago

Understanding Boolean Values

布尔值

function welcomeToBooleans() {

// Only change code below this line.

return true; // Change this line

// Only change code above this line.
}
NBR-hugh commented 7 years ago

Statements

If Statements

If 结构与布尔数据的配合使用

function ourTrueOrFalse(isItTrue) {
  if (isItTrue) { 
    return "Yes, it's true";
  }
  return "No, it's false";
}
 ourTrueOrFalse(True);

Else Statements

if (num > 10) {
  return "Bigger than 10";
} else {
  return "10 or Less";
}

Else If Statements

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",虽然没错但不够准确,因此在嵌套时注意逻辑顺序,使得输出结果更准确;

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";
  }

  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"

NBR-hugh commented 7 years ago

Comparison

比较判断真假

数学运算

the Equality Operator 相等 ==

function equalityTest(myVal) {
  if (myVal == 10) {
     return "Equal";
  }
  return "Not Equal";
}

1 == 1 // true 1 == 2 // false 1 == '1' // true "3" == 3 // true

the Strict Equality Operator 严格相等 ===

Examples

3 === 3 // true 3 === '3' // false In the second example, 3 is a Number type and '3' is a String type.

the Inequality Operator 不等 !=

Examples

1 != 2 // true 1 != "1" // false 1 != '1' // false 1 != true // false 0 != false // false

the Strict Inequality Operator 严格不等 !==

Examples

3 !== 3 // false 3 !== '3' // true 4 !== 3 // true

the Greater Than Operator 大于 >

Examples

5 > 3 // true 7 > '3' // true 2 > 3 // false '1' > 9 // false

the Greater Than Or Equal To Operator 大于等于 >=(非严格)

Less Than Operator 小于<

the Less Than Or Equal To Operator 小于等于 <=

逻辑运算

the Logical And Operator 逻辑和 &&

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";

逻辑或 ||

NBR-hugh commented 7 years ago

Statements

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;  
}

// Change this value to test
caseInSwitch(1);

Adding a default option in Switch statements 无法全覆盖,设置默认选项

switch (num) { case value1: statement1; break; case value2: statement2; break; ... default: defaultStatement; }

  • value 可以是数字,也可以是字符串;
  • 注意 ;:

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;  
}

// Change this value to test
sequentialSizes(1);

Replacing If Else Chains with Switch 转换

又是return

function isLess(a, b) {
  // Fix this code
return a < b;
}

可代替

function isLess(a, b) {
if (a < b) {
    return true;
  } else {
    return false;
  }
}
NBR-hugh commented 7 years ago

Build JavaScript Objects

对象

var cat = {
  "name": "Whiskers",
  "legs": 4,
  "tails": 1,
  "enemies": ["Water", "Dogs"]
};

Accessing Objects Properties 获取对象特性:点操作符/括号记法

similar to an array,two ways to access the properties of an object

  1. dot operator(.)
var myObj = {
  prop1: "val1",
  prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
  1. bracket notation ([])
var myObj = {
  "Space Name": "Kirk",
  "More Space": "Spock"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock

Updating Object Properties 更新/添加/删除对象性质

  1. 更新对象ourDog 中的name性质;ourDog.name = "Happy Camper";
  2. 添加性质则类似,修改.后的性质名称与新性质的值即可;myDog.bark = "woof";
  3. 删除对象某一条性质:delete ourDog.bark;
var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};
ourDog.name = "Happy Camper";
myDog.bark = "woof";
delete ourDog.bark;

Using Objects for Lookups 运用对象查询

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"

Testing Objects for Properties 测试对象性质是否存在

  1. .hasOwnProperty(propname) returns true or false if the property is found or not.
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");

Manipulating Complex Objects 操作复杂对象

var ourMusic = [
  {
    "artist": "Daft Punk",
    "title": "Homework",
    "release_year": 1997,
    "formats": [ 
      "CD", 
      "Cassette", 
      "LP" ],
    "gold": true
  }
];

Accessing Nested Objects 对象的调用

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"] ; 

Accessing Nested Arrays 数组(队列)的调用

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];
NBR-hugh commented 7 years ago

Record Collection 记录集 【stuck】

首先按照要求逐条使用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. .hasOwnProperty()括号内变量没有加引号,无法识别!
  2. track提示是未定义变量,所以添加了一句 var tracks
  3. collection后面缺了一个[id]

教训

1.出问题了一条条代码去尝试,定位错误源,用小黄鸭调试法进行排查。 2,没有什么问题是细心排查解决不了的,最大的敌人是畏难与烦躁的内心,提高大脑的运算速度,想可能的原因,测试,验证或者排除,再不断尝试,问题就解决了。

NBR-hugh commented 7 years ago

loop 循环

For 循环

Iterate with JavaScript For Loops FOR循环 迭代/累加奇偶/累乘

for (var i = 0;i < 6; i++){
  myArray.push(i);
}

Nesting For Loops数列的循环引用

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]]);
NBR-hugh commented 7 years ago

loop循环

While Loops

var myArray = [];
var i=0;
while (i<5){
  myArray.push(i);
  i++;
}
NBR-hugh commented 7 years ago

Profile Lookup 文件搜索【stuck】

[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";
  }
NBR-hugh commented 7 years ago

Generate Random Fractions with JavaScript 随机数生成

NBR-hugh commented 7 years ago

Regular Expressions

Sift through Text with Regular Expressions 寻找文本

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.

Find Numbers with Regular Expressions 寻找数字

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;**

Find Whitespace with Regular Expressions 寻找空白

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;

Invert Regular Expression Matches with JavaScript

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.

不是十分明了这个regular expressions的作用是什么?应用在什么场景?可以实现什么功能?