Basic JavaScript-freecodecamp

1.JavaScript中的注釋方式有以下兩種:
使用 // 來告訴JavaScript來忽略當(dāng)前行的代碼
// This is an in-line comment.
你也可以使用多行注釋來注釋你的代碼,以/開始,用/來結(jié)束,就像下面這樣:
/* This is a
multi-line comment */

2.在計(jì)算機(jī)科學(xué)中, data(數(shù)據(jù))就是一切,因?yàn)樗鼘?duì)于計(jì)算機(jī)的意義重大。JavaScript提供七種不同的data types(數(shù)據(jù)類型),它們是undefined(未定義), null(空), boolean(布爾型), string(字符串), symbol(符號(hào)), number(數(shù)字), and object(對(duì)象)。
舉個(gè)栗子, 計(jì)算機(jī)能夠分辨不同的數(shù)字, 例如數(shù)字 12和 strings,"12"和"dog", 或"123 cats", 都是字母的集合。 計(jì)算機(jī)能夠精確地操作數(shù)字, 但是對(duì)于字符串卻無能為力。
Variables(變量)允許計(jì)算機(jī)以一種動(dòng)態(tài)的形式來存儲(chǔ)和操作數(shù)據(jù),通過操作指向數(shù)據(jù)的指針而不是數(shù)據(jù)本身來避免了內(nèi)存泄露,以上的七種數(shù)據(jù)類型都可以存儲(chǔ)到一個(gè)變量(variable)中。
Variables 非常類似于你在數(shù)學(xué)中使用的x,y變量, 這意味著它們都是以一個(gè)簡(jiǎn)單命名的名字來代替我們賦值給它的數(shù)據(jù)。計(jì)算機(jī)中的variables(變量)與數(shù)學(xué)中的變量不同的是,計(jì)算機(jī)可以在不同的時(shí)間存儲(chǔ)不同類型的變量。
通過在變量的前面使用關(guān)鍵字var,我們告訴 JavaScript 來創(chuàng)建或者 declare(聲明)一個(gè)變量,就像這樣:
var ourName;
上面代碼的意思是創(chuàng)建一個(gè)名為ourName的variable(變量),在JavaScript中我們使用分號(hào)來結(jié)束一段聲明。
Variable (變量)的名字可以由數(shù)字、字母、$ 或者 _組成,但是不能包含空格或者以數(shù)字為首。

3.在JavaScript中,你可以通過assignment(分配)操作符把一個(gè)值存儲(chǔ)到變量中。
myVariable = 5;
把Number數(shù)字5賦給變量myVariable。
賦值過程是從右到左進(jìn)行的。所有 = 操作符右邊的值都會(huì)被賦到左邊的變量。
myVar = 5;
myNum = myVar;
數(shù)值 5 被賦給變量 myVar 中, 然后變量 myVar 又賦給變量 myNum ,這樣子 myNum 變量中的值也是 5 了。

4.i++;等效于i = i + 1;

5.JavaScript中只有字符串類型,沒有字符類型。那么如何獲取到字符串中的某個(gè)字符呢?
我們通過[索引] 來獲得對(duì)應(yīng)的字符。
大多數(shù)現(xiàn)代編程語言,如JavaScript,不同于人類從1開始計(jì)數(shù)。它們是從0開始計(jì)數(shù),這被稱為 基于零 的索引。
例如, 在單詞 "Charles" 中索引0上的字符為 "C",所以在 var firstName = "Charles" 中,你可以使用 firstName[0] 來獲得第一個(gè)位置上的字符。

6.可以把 多維 數(shù)組看作成是一個(gè) 數(shù)組中的數(shù)組。當(dāng)使用[]去訪問數(shù)組的時(shí)候,第一個(gè)[index]訪問的是第N個(gè)子數(shù)組,第二個(gè)[index]訪問的是第N個(gè)子數(shù)組的第N個(gè)元素。
例如

var arr = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [[10,11,12], 13, 14]
];
arr[0]; // 等于 [1,2,3]
arr[1][2]; // 等于 6
arr[3][0][1]; // 等于 11```

7.index  push()  unshift()  pop()  shift()

8.在一個(gè)函數(shù)內(nèi)聲明的變量,以及該函數(shù)的參數(shù)都是局部變量,意味著它們只在該函數(shù)內(nèi)可見。
這是在函數(shù) myTest內(nèi)聲明局部變量loc 的最佳例子:

function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // "foo"
console.log(loc); // "undefined"```
在函數(shù)外,loc 是未定義的。

9.一個(gè)程序中有可能具有相同名稱的 局部 變量 和 全局 變量。在這種情況下,局部 變量將會(huì)優(yōu)先于 全局 變量。
下面為例:

var someVar = "Hat";
function myFun() {
  var someVar = "Head";
  return someVar;
}```
函數(shù) myFun 將會(huì)返回 "Head",因?yàn)?局部變量 優(yōu)先級(jí)更高。

10.在計(jì)算機(jī)科學(xué)中 隊(duì)列(queue)是一個(gè)抽象的數(shù)據(jù)結(jié)構(gòu),隊(duì)列中的條目都是有秩序的。新的條目會(huì)被加到 隊(duì)列 的末尾,舊的條目會(huì)從 隊(duì)列 的頭部被移出。
>寫一個(gè)函數(shù) queue ,用一個(gè)數(shù)組arr和一個(gè)數(shù)字item作為參數(shù)。數(shù)字item添加到數(shù)組的結(jié)尾,然后移出數(shù)組的第一個(gè)元素,最后隊(duì)列函數(shù)應(yīng)該返回被刪除的元素。

function queue(arr, item) {
// Your code here
arr.push(item);
var aArr = arr.shift();
return aArr; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(queue(testArr, 3)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));```

11、 運(yùn)算符 ==

在高爾夫golf游戲中,每個(gè)洞都有自己的標(biāo)準(zhǔn)桿數(shù)par,代表著距離。根據(jù)你把球打進(jìn)洞所揮桿的次數(shù)strokes,可以計(jì)算出你的高爾夫水平。
函數(shù)將會(huì)傳送2個(gè)參數(shù),分別是標(biāo)準(zhǔn)桿數(shù)par 和 揮桿次數(shù)strokes ,根據(jù)下面的表格返回正確的水平段位。
par 和 strokes 必須是數(shù)字而且是正數(shù)。


Paste_Image.png

無法通過,一直顯示為"Hole-in-one!"

function golfScore(par, strokes) {
  // Only change code below this line
   if(strokes=1){
    return "Hole-in-one!";
  }else if(strokes<= par - 2){
    return "Eagle";
  }else if(strokes=par-1){
    return "Birdie";
  }else if(strokes=par){
    return "Par";
  }else if(strokes=par+1){
    return "Bogey";
  }else if(strokes=par + 2){
    return "Double Bogey";
  }
  
  else if(strokes>= par + 3){
    return "Go Home!";
  } 
  
  // Only change code above this line
}

// Change these values to test
golfScore(5, 4);

相等操作符,正解如下:

function golfScore(par, strokes) {
  // Only change code below this line
   if(strokes==1){
    return "Hole-in-one!";
  }else if(strokes<= par - 2){
    return "Eagle";
  }else if(strokes==par-1){
    return "Birdie";
  }else if(strokes==par){
    return "Par";
  }else if(strokes==par+1){
    return "Bogey";
  }else if(strokes==par + 2){
    return "Double Bogey";
  }
  
  else if(strokes>= par + 3){
    return "Go Home!";
  } 
  
  // Only change code above this line
}

// Change these values to test
golfScore(5, 4);

12.把串聯(lián)的 if/if else 語句改成 switch 語句。

 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";
  }```
##不能通過,什么問題??  

switch(val){
case val === "bob":
answer = "Marley";
break;
case val === 42:
answer = "The Answer";
break;
case val === 1:
answer = "There is no #1";
break;
case val === 99:
answer = "Missed me by this much!";
break;
case val === 7:
answer = "Ate Nine";
break;
default:
answer = "empty string";
}

// Only change code above this line
return answer;
}

// Change this value to test
myTest(7);```

case 后直接跟條件即可。正解如下:

function myTest(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; 
}

// Change this value to test
myTest(7);```

#13.?? 邏輯上可行呀   
>【Counting Cards】你需要寫一個(gè)函數(shù),實(shí)現(xiàn)21點(diǎn)算法,它根據(jù)參數(shù) card的值來遞增或遞減變量count,函數(shù)返回一個(gè)由當(dāng)前count和 "Bet"(count>0)或"Hold"(count<=0) 拼接的字符串。注意count和"Bet" 或 "Hold"應(yīng)該用空格分開。
例如:
"-3 Hold"
"5 Bet"
提示:既然card的值為7、8、9時(shí),count值不變,那我們就可以忽略這種情況。
![Paste_Image.png](http://upload-images.jianshu.io/upload_images/316258-eb008e96936d3efa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

var count = 0;

function cc(card) {
// Only change code below this line
if(card=2 || card=3 || card=4 || card=5 || card=6){
return count++;
}else if(card=10 || card='J' || card='Q' || card='K' || card='A'){
return count--;
}

if(count>0){
return "count Bet";
}else{
return "count Hold";
}

// Only change code above this line
}

// Add/remove calls to test your function.
// 提示: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');```

正解如下:

var count = 0;

function cc(card) {
  // Only change code below this line
  var values = {
    2:1,3:1,4:1,5:1,6:1,
    7:0,8:0,9:0,
    10:-1,'J':-1,'Q':-1,'K':-1,'A':-1
  }
  count += values[card];
  return count + ' ' + (count > 0 ? "Bet" : "Hold");
  
  // Only change code above this line
}

// Add/remove calls to test your function.
// 提示: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');```

14.有兩種方式訪問對(duì)象屬性,一個(gè)是點(diǎn)操作符(.),一個(gè)是中括號(hào)操作符([])。
當(dāng)你知道屬性的名稱的時(shí)候,使用點(diǎn)操作符。

##15.playerNumber
使用變量playerNumber,通過中括號(hào)操作符找到testObj中的16。

/ Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};

// Only change code below this line;

var playerNumber; // Change this Line
var player = testObj[16]; // Change this Line


#正解如下:

// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};

// Only change code below this line;

var playerNumber=16; // Change this Line
var player = testObj[playerNumber]; // Change this Line


16.1 有兩種方式訪問對(duì)象屬性,一個(gè)是點(diǎn)操作符(.),一個(gè)是中括號(hào)操作符([])。
當(dāng)你知道屬性的名稱的時(shí)候,使用點(diǎn)操作符。這是一個(gè)使用點(diǎn)操作符讀取對(duì)象屬性的例子:

var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2```

把switch語句轉(zhuǎn)化為一個(gè)叫做lookup的對(duì)象。


16.2第二種訪問對(duì)象的方式就是中括號(hào)操作符([]),如果你想訪問的屬性的名稱有一個(gè)空格,這時(shí)你只能使用中括號(hào)操作符([])。這是一個(gè)使用中括號(hào)操作符([])讀取對(duì)象屬性的例子:

var myObj = {
"Space Name": "Kirk",
"More Space": "Spock"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock```
提示:屬性名稱中如果有空格,必須把屬性名稱用單引號(hào)或雙引號(hào)包裹起來。

16.3

中括號(hào)操作符的另一個(gè)使用方式是用變量來訪問一個(gè)屬性。當(dāng)你需要遍歷對(duì)象的屬性列表或查表時(shí),這種方式極為有用。
這有一個(gè)使用變量來訪問屬性的例子:

var someProp = "propName";
var myObj = {
  propName: "Some Value"
}
myObj[someProp]; // "Some Value"```
還有更多:

var myDog = "Hunter";
var dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
}
var breed = dogs[myDog]; // "Hunter"
console.log(breed)// "Doberman"```
提示:當(dāng)我們通過變量名訪問屬性的時(shí)候,不需要給變量名包裹引號(hào)。因?yàn)閷?shí)際上我們使用的是變量的值,而不是變量的名稱。

16.4

把switch語句轉(zhuǎn)化為一個(gè)叫做lookup的對(duì)象。

// Setup
function phoneticLookup(val) {
  var 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";
  }
  // Only change code above this line
  return result;
}
// Change this value to test
phoneticLookup("charlie");

有問題,怎么改?

// Setup
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"
    

  // Only change code above this line
  return result;
}

// Change this value to test
phoneticLookup("charlie");

正解如下:

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

// Change this value to test
phoneticLookup("charlie");```

#17. 已解決
>修改函數(shù)checkObj檢查myObj是否有checkProp屬性,如果屬性存在,返回屬性對(duì)應(yīng)的值,如果不存在,返回 "Not Found"。
注意:如果你需要通過變量來訪問對(duì)象的屬性值,請(qǐng)用中括號(hào)操作符,點(diǎn)操作符不支持變量。

// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};

function checkObj(checkProp) {
// Your Code Here
if(myObj.hasOwnProperty("checkProp")){
return checkObj["checkProp"];// return what???
}else{
return "Not Found";
}

}

// Test your code by modifying these values
checkObj("gift");```

正解如下:

// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
  // Your Code Here
  
  return myObj.hasOwnProperty(checkProp) ? myObj[checkProp] : "Not Found";
}

// Test your code by modifying these values
checkObj("gift");

18.JavaScript Object Notation 簡(jiǎn)稱 JSON,它使用JavaScript對(duì)象的格式來存儲(chǔ)數(shù)據(jù)。JSON是靈活的,因?yàn)樗试S 數(shù)據(jù)結(jié)構(gòu) 是 字符串,數(shù)字,布爾值,字符串,和 對(duì)象 的任意組合。

什么是 JSON ?
JSON 指的是 JavaScript 對(duì)象表示法(JavaScript Object Notation)
JSON 是輕量級(jí)的文本數(shù)據(jù)交換格式
JSON 獨(dú)立于語言 *
JSON 具有自我描述性,更易理解

  • JSON 使用 JavaScript 語法來描述數(shù)據(jù)對(duì)象,但是 JSON 仍然獨(dú)立于語言和平臺(tái)。JSON 解析器和 JSON 庫(kù)支持許多不同的編程語言。

19.通過串聯(lián)起來的點(diǎn)操作符或中括號(hào)操作符來訪問JSON對(duì)象的嵌套屬性。
下面是一個(gè)嵌套的JSON對(duì)象:

var ourStorage = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
}
ourStorage.cabinet["top drawer"].folder2;  // "secrets"
ourStorage.desk.drawer; // "stapler"```

##20.
>使用點(diǎn)操作符和中括號(hào)操作符來檢索變量 myPlants 的第二棵樹。

// Setup
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] ; // Change this line```

寫一個(gè)函數(shù),它有個(gè)三個(gè)參數(shù),id、prop、 value。
如果 value !='' 而且prop != 'tracks' ,collectionCopy[id][prop]=value;。
如果 value !='' 而且prop == 'tracks' ,collectionCopy[id][prop].push(value);。
如果 value == '' ,delete collectionCopy[id][prop];。
記住:函數(shù)返回的永遠(yuǎn)是整個(gè)對(duì)象。

??題目什么意思,不太明白

// Setup
var collection = {
    2548: {
      album: "Slippery When Wet",
      artist: "Bon Jovi",
      tracks: [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    2468: {
      album: "1999",
      artist: "Prince",
      tracks: [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    1245: {
      artist: "Robert Palmer",
      tracks: [ ]
    },
    5439: {
      album: "ABBA Gold"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line
function update(id, prop, value) {
  if(value != '' && prop != 'tracks' ){
   return collectionCopy[id][prop]=value;
  }else if(value !=''&&){
    
  }

  return collection;
}

// Alter values below to test your code
update(5439, "artist", "ABBA");```

#22.??完全沒思路
>我們有一個(gè)對(duì)象數(shù)組,里面存儲(chǔ)著通訊錄。
函數(shù) lookUp 有兩個(gè)預(yù)定義參數(shù):firstName值和prop屬性 。
函數(shù)將會(huì)檢查通訊錄是否存在一個(gè)聯(lián)系人的firstName屬性等于firstName值,還會(huì)檢查對(duì)應(yīng)聯(lián)系人是否存在 prop屬性。
如果它們都存在,函數(shù)返回prop屬性對(duì)應(yīng)的值。
如果firstName 值不存在,返回 "No such contact"。
如果prop 屬性不存在,返回 "No such property"。

//Setup
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"]
}
];

function lookUp(firstName, prop){
// Only change code below this line
for(var i=0;i<contacts.length;i++){
if(contacts[i].hasOwnProperty("firstName") && contacts[i].hasOwnProperty("prop") ){
return prop;
}
if(contacts[i].hasOwnProperty("firstName") === false){
return "No such contact";
}

if(contacts[i].hasOwnProperty("prop")===false){
return "No such property";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUp("Akira", "likes");```

正解如下:

//Setup
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"]
    }
];


function lookUp(firstName, prop){
// Only change code below this line
for(var i=0;i<contacts.length;i++){
    if(contacts[i].firstName == firstName){
        if(contacts[i].hasOwnProperty(prop)){
             return contacts[i][prop];
             } 
              return "No such property";       
         }
    } 
     return "No such contact";
  
  
// Only change code above this line
}

// Change these values to test your function
lookUp("Akira", "likes");

23.我們之前生成的隨機(jī)數(shù)是在0到某個(gè)數(shù)之間,現(xiàn)在我們要生成的隨機(jī)數(shù)是在兩個(gè)指定的數(shù)之間。
我們需要定義一個(gè)最小值和一個(gè)最大值。
下面是我們將要使用的方法,仔細(xì)看看并嘗試?yán)斫膺@行代碼到底在干嘛:
Math.floor(Math.random() * (max - min + 1)) + min

24.Regular expressions 正則表達(dá)式被用來根據(jù)某種匹配模式來尋找strings中的某些單詞。
舉例:如果我們想要找到字符串The dog chased the cat中單詞 the,我們可以使用下面的正則表達(dá)式: /the/gi
我們可以把這個(gè)正則表達(dá)式分成幾段:
/ 是這個(gè)正則表達(dá)式的頭部
the 是我們想要匹配的模式
/ 是這個(gè)正則表達(dá)式的尾部
g 代表著 global(全局),意味著返回所有的匹配而不僅僅是第一個(gè)。
i 代表著忽略大小寫,意思是當(dāng)我們尋找匹配的字符串的時(shí)候忽略掉字母的大小寫

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容