Arrays
访问数组元素
如果你知道数组的下标的话你可以获取数组中的元素。数组元素的下标从0开始而且每次增加1,所以第一个元素的下标是0,第二个是1...
Syntax语法
array[index]
Example示例
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
primes[0]; // 2
primes[3]; // 7
primes[150]; // undefined
数组常量
你可以用两种方式创建数组。其中最常见的是用一对方括号[]列出所有值。JavaScript的数组可以包含任意类型的值,也就是说它的元素可以是任意类型。
Syntax
var arrayName = [element0, element1, ..., elementN]
Example
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
多维数组
二位数组是数组里面的元素又是一个数组,如果这个数组里面的元素又是数组填充的,那么就是三维数组....
Example
var multidimensionalArray = [[1,2,3],[4,5,6],[7,8,9]] // 二维, 3x3
数组构造函数
你也可以用数组构造函数创建一个数组。
Example
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.
Booleans
Boolean常量
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
"Truthy" and "Falsey"
只有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");
*/
Console
console.log
打印文本到控制台,常用于调试
Example
var name = "Codecademy";
console.log(name);
console.time
开始一个计时器用于跟踪代码的执行时间,你得给定时器一个独特的名字,当用相同的定时器名字调用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.
*/
Functions
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!
函数两种声明方式的差别(Function构造函数方式不在讨论范围)
函数声明与函数表达式
这两种定义函数的方式的区别在于解析器在向执行环境中加载数据的时候,解析器会率先读取函数声明,并使其在执行任何代码前有效,而函数表达式只有在解析器执行到它所在的代码行时才会执行。除了这个区别外这两种定义函数的方式是等价的。
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.');
}
if
Syntax // Form : Single If if (condition) { // code that runs if the condition is true } Example if (answer === 42) { console.log('Told you so!'); }
else
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!"); }
else if
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!"); }
Loops
For Loops
当你不知道要循环多少次时可以使用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--; }
While Loops
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++; }
Do While Loops
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);
Math
random Math.random() 返回一个介于0到1之间的随机数 floor 返回最大的整数少于或等于传入的num Math.floor(9.99); // 9 pow 返回num指数次幂的值 Math.pow(2,4); // gives 16 ceil 与floor相反 sqrt 开方
Numbers
%
返回一个数除以另一个数的余数(整数)
Syntax number1 % number2 Example 14 % 9 // returns 5
isNaN(Not a Number)
返回true如果提供的参数不是一个数字
if( isNaN("3") )
alert("bad");
//Not executed , because the string "3" gets converted into 3 ,and 3 is a number
Objects
对象字面量
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
弹出框
alert
弹出一个对话框带有特殊消息和一个确定按钮
Syntax
alert(message);
Example
alert("Hello World");
confirm
弹出一个对话框带有特殊消息和一个确定按钮和取消按钮,点击确定按钮返回true,取消按钮返回false
Syntax
confirm("message") //returns true if confirmed, false otherwise
Example
if ( confirm("Are you sure you want to delete this post?") ) {
deletePost();
}
prompt
弹出一个可接受用户输入的文本的消息框,如果点击取消按钮,将会返回null
Syntax
prompt(message);
Example
var name = prompt("Enter your name:");
console.log("Hello " + name + "!");
Strings
被单引号或者双引号包围的文本
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!"); } */
Variables
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