若是你知道數組的下標的話你能夠獲取數組中的元素。數組元素的下標從0開始並且每次增長1,因此第一個元素的下標是0,第二個是1...javascript
Syntax語法php
array[index]
Example示例java
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; primes[0]; // 2 primes[3]; // 7 primes[150]; // undefined
你能夠用兩種方式建立數組。其中最多見的是用一對方括號[]列出全部值。JavaScript的數組能夠包含任意類型的值,也就是說它的元素能夠是任意類型。express
Syntax數組
var arrayName = [element0, element1, ..., elementN]
Example瀏覽器
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
二位數組是數組裏面的元素又是一個數組,若是這個數組裏面的元素又是數組填充的,那麼就是三維數組....ruby
Examplebash
var multidimensionalArray = [[1,2,3],[4,5,6],[7,8,9]] // 二維, 3x3
你也能夠用數組構造函數建立一個數組。less
Exampledom
var stuff = new Array(); stuff[0] = 34; stuff[4] = 20; stuff // [34, undefined, undefined, undefined, 20]
Example
var myArray = new Array(45 , "Hello World!" , true , 3.2 , undefined); console.log(myArray); // output: [ 45, 'Hello World!', true, 3.2, undefined ]
獲取多維數組元素和獲取一維數組元素的原理相似,他們用[index][index]...獲取數組元素(他們的數值取決於你想獲取的第幾個數組裏的第幾個元素)
Syntax
array[index][index]....
Example
var myMultiArray = [ [1,2,3,4,5, [1,2,3,4,5] ], [6,7,8,9,10 , [1,2,3,4,6] ], [11,12,13,14,15 , [1,2,3,4,5] ], [16,17,18,19,20, [1,2,3,4,5] ] ]; console.log( myMultiArray[1][5][4] ); // Outputs 6 ,myMultiArray[1] =[6,7,8,9,10 , [1,2,3,4,6] ],myMultiArray[1][5] = [1,2,3,4,6], 因此myMultiArray[1][5][4]=6.
Syntax
true false
Syntax
expression1 && expression2 //返回true若是兩個表達式都爲真 expression3 || expression4 //返回真若是其中有一個表達式爲真 !expression5 //返回相對於表達式相反的布爾值
Example
1 Example 2 3 if ( true && false )alert("Not executed!"); 4 //由於第二個表達式爲false,因此不執行 5 6 if( false || true )alert("Executed!"); 7 //由於有一個表達式爲true,因此執行 8 9 if( !false )alert("Executed!"); 10 // !false == true 11 12 !!true // remains true
13 Example 14 一個要注意的地方是運算符的優先級,() > ! > && > ||,爲了不出現錯誤,&& 與 || 一塊兒出現時最好帶上括號,避免混淆 15 if(!false && ( false || (false && true) ))alert("Guess what..."); 16 !false && (false || false ) --> !false && false --> true && false
Syntax
x === y // returns true if two things are equal x !== y // returns true if two things are not equal x <= y // returns true if x is less than or equal to y x >= y // returns true if x is greater than or equal to y x < y // returns true if x is less than y x > y // returns true if x is greater than y
只有Boolean常量(true and false)斷言爲true或false,可是還有其餘方式判斷真假,來看示例。
Example
if(1)console.log("True!"); // output True! , 全部非0數字都將轉換爲true if(0)console.log("I doubt if this gets executed"); // not executed , 0將轉換爲false if("Hello")alert("So, any non-empty String is also true."); //Gets executed 全部非空字符串都將轉換爲true if("")alert("Hence , an empty String is false"); // Not executed 空字符串false 還有undifined也爲false
==
vs. ===
簡單的解釋是==只檢查值是否相等而不檢查類型,而===值和類型都檢查。建議不要使用==,由於==常常返回不被指望的結果,下面來看示例
expression == expression expression === expression
Example
'1' == 1 //true (相同的值) '1' === 1 // false (不一樣的類型,一個字符串,一個數值) true == 1 // true (由於1將轉換爲true,雖然不是相同的類型仍是相等) true === 1 // false (不一樣的類型)
代碼註釋不會執行,用於提示這段代碼的做用等等
Example
console.log("This code will be run") //console.log("Because this line is in a comment, this code will not be run.") // This is a single line comment.
Example
/* alert("Hello,I won't be executed."); console.log("Hello ,I also will not be executed"); */
打印文本到控制檯,經常使用於調試
Example
var name = "Codecademy"; console.log(name);
開始一個計時器用於跟蹤代碼的執行時間,你得給定時器一個獨特的名字,當用相同的定時器名字調用console.timeEnd(),瀏覽器將會輸出跟蹤的代碼塊執行所需的時間,單位爲毫秒
Example
console.time("My Math"); var x = 5 + 5; console.log(x); console.timeEnd("My Math"); console.log("Done the math.");
/* Output: 10 My Math: 0.045ms Done the math. */
Syntax
function name(argument1 , argument2 .... argumentN){ statement1; statement2; .. statementN; }
Example
function greet(name) { return "Hello" + name + "!"; }
Syntax
functionName(argument1, argument2, ..., argumentN);
Example
greet("Anonymous"); // Hello Anonymous!
函數聲明與函數表達式
這兩種定義函數的方式的區別在於解析器在向執行環境中加載數據的時候,解析器會率先讀取函數聲明,並使其在執行任何代碼前有效,而函數表達式只有在解析器執行到它所在的代碼行時纔會執行。除了這個區別外這兩種定義函數的方式是等價的。
Example
hoistedFunction(); // Hello! I am defined immediately! notHoistedFunction(); // ReferenceError: notHoistedFunction is not defined 會報undefined錯誤,由於notHoistedFunction還未聲明 function hoistedFunction () { console.log('Hello! I am defined immediately!'); } var notHoistedFunction = function () { console.log('I am not defined immediately.'); }
Syntax // Form : Single If if (condition) { // code that runs if the condition is true } Example if (answer === 42) { console.log('Told you so!'); }
Syntax // If the condition is true, statement1 will be executed. // Otherwise, statement2 will be executed. if (condition) { // statement1: code that runs if condition is true } else { // statement2: code that runs if condition is false } Example if (gender == "male") { console.log("Hello, sir!"); } else { console.log("Hello, ma'am!"); }
Syntax // Form : else if . If the condition is true, statement1 will be executed. Otherwise, condition2 is checked . if it is true , then statement2 is executed. Else , if nothing is true , statement3 is executed. if (condition1) { statement1; } else if (condition2) { statement2; } else { statement3; } Example if (someNumber > 10) { console.log("Numbers larger than 10 are not allowed."); } else if (someNumber < 0) { console.log("Negative numbers are not allowed."); } else { console.log("Nice number!"); }
當你不知道要循環多少次時可使用for循環
Syntax for ([var i = startValue];[i < endValue]; [i+=stepValue]) { // Your code here } Example for (var i = 0; i < 5; i++) { console.log(i); // Prints the numbers from 0 to 4 } Example var i; // "outsourcing" the definition for (i = 10; i >= 1; i--) { console.log(i); // Prints the numbers from 10 to 1 } Example /* Note that all of the three statements are optional, i.e. , */ var i = 9; for(;;){ if(i === 0)break; console.log(i); i--; }
Syntax while (condition) { // Your code here } Example var x = 0; while (x < 5) { console.log(x); // Prints numbers from 0 to 4 x++; } Example var x = 10; while (x <= 5) { console.log(x); // Won't be executed x++; }
Syntax do { // Your code here } while (condition); Example var x = 0; do { console.log(x); // Prints numbers from 0 to 4 x++; } while (x < 5); Example var x = 10; do { console.log(x); // Prints 10 x++; } while (x <= 5);
random Math.random() 返回一個介於0到1之間的隨機數 floor 返回最大的整數少於或等於傳入的num Math.floor(9.99); // 9 pow 返回num指數次冪的值 Math.pow(2,4); // gives 16 ceil 與floor相反 sqrt 開方
%
返回一個數除以另外一個數的餘數(整數)
Syntax number1 % number2 Example 14 % 9 // returns 5
返回true若是提供的參數不是一個數字
if( isNaN("3") ) alert("bad");
//Not executed , because the string "3" gets converted into 3 ,and 3 is a number
對象字面量
Syntax { "property 1": value1, property2: value2, number: value3 } Example var obj = { name: "Bob", married: true, "mother's name": "Alice", "year of birth": 1987, getAge: function () { return 2012 - obj["year of birth"]; }, 1: 'one' };
Syntax name1[string] name2.identifier Example obj['name']; // 'Bob' obj.name; // 'Bob' obj.getAge(); // 24
彈出一個對話框帶有特殊消息和一個肯定按鈕
Syntax
alert(message);
Example
alert("Hello World");
彈出一個對話框帶有特殊消息和一個肯定按鈕和取消按鈕,點擊肯定按鈕返回true,取消按鈕返回false
Syntax
confirm("message") //returns true if confirmed, false otherwise
Example
if ( confirm("Are you sure you want to delete this post?") ) { deletePost(); }
彈出一個可接受用戶輸入的文本的消息框,若是點擊取消按鈕,將會返回null
Syntax
prompt(message);
Example
var name = prompt("Enter your name:"); console.log("Hello " + name + "!");
被單引號或者雙引號包圍的文本
Syntax "string of text" 'string of text' Syntax string1 + string2
Example "some" + "text"; // returns "sometext" var first = "my"; var second = "string"; var union = first + second; // union variable has the string "mystring"
length Returns the length of the string. Syntax string.length
Example "My name".length // 7 , white space is also counted "".length // 0
toUpperCase(), toLowerCase() 轉換大小寫 Changes the cases of all the alphabetical letters in the string. Example "my name".toUpperCase(); // Returns "MY NAME" "MY NAME".toLowerCase(); // Returns "my name"
trim() 去除字符串兩端的空格 Removes whitespace from both ends of the string. Syntax string.trim()
Example " a ".trim(); // 'a' " a a ".trim(); // 'a a' replace() 替換字符串 Returns a string with the first match substring replaced with a new substring. Example "original string".replace("original", "replaced"); // returns "replaced string"
charAt() 返回指定位置的字符,第一個字符的下標爲0,最後一個字符的下標爲length-1,若是指定位置超出了字符串的長度則返回'' Returns the specified character from a string. Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string. Syntax string.charAt(index) // index is an integer between 0 and 1 less than the length of the string. Example "Hello World!".charAt(0); // 'H' "Hello World!".charAt(234); // '' substring() 截取兩個index之間的字符串 Returns the sequence of characters between two indices within a string. Syntax string.substring(indexA[, indexB]) //indexA : An integer between 0 and the length of the string // indexB : (optional) An integer between 0 and the length of the string. Example "adventures".substring(2,9); // Returns "venture" // 從index(2)開始,到index(9)但不包含index(9) "hello".substring(1); // returns "ello" "Web Fundamentals".substring(111); // returns '' "In the market".substring(2,999); // returns ' the market' "Fast and efficient".substring(3,3); // returns '' "Go away".substring("abcd" , 5); // returns 'Go aw' 任何非num會被當作0 indexOf() 返回字符第一次出現的位置,若是沒有找到則返回-1 Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, Returns -1 if the value is not found. The indexOf method is case sensitive. Syntax string.indexOf(searchValue[, fromIndex]) //fromIndex is optional.It specifies from which index should the search start.Its default value is 0.開始搜索的位置 Example "My name is very long.".indexOf("name"); // returns 3 "My name is very long.".indexOf("Name"); // returns -1 , it's case sensitive "Where are you going?".indexOf("are",11); //returns -1 "Learn to Code".indexOf(""); //returns 0 "Learn to Code".indexOf("",3); //returns 3 "Learn to Code".indexOf("",229); returns 13 , which is the string.length
常常用於簡化if else的使用
Syntax condition ? expr1 : expr2 Example var grade = 85; console.log("You " + (grade > 50 ? "passed!" : "failed!")); //Output: You passed! /* 上面的代碼等效於如下 if(grade > 50){ console.log("You " + "passed!"); //or simply "You passed!" } else{ console.log("You " + "failed!"); } */
JavaScript是弱類型語言,變量的聲明都是使用var來聲明
Syntax var name = value; Example var x = 1; var myName = "Bob"; var hisName = myName;
改變變量的值 Syntax varname = newValue Example var name = "Michael" //declare variable and give it value of "Michael" name = "Samuel" //change value of name to "Samuel"
翻譯自https://www.codecademy.com/articles/glossary-javascript