JavaScript基础
https://channel9.msdn.com/Series/Beginners-Series-to-JavaScript?WT.mc_id=beginner-c9-ninerhttps://github.com/microsoft/beginners-intro-javascript-nodehttps://developer.mozilla.org/zh-CN/docs/Learn/JavaScript
变量
- var:没有作用域(基本不用)
- let:有作用域
- const:类似 let,但不能改变(不能给变量重新赋值,“内部”能变)
类型:
简单类型:
- Number(float)
- String
- Boolean
- Date
- Function
- Array
- Object
特别类型:
- NaN:Not a number
- null:空
- undefined:未定义
类型检查:
- typeof:返回字符串
- instanceof:返回 boolean 是否匹配类型
类型能改变:
let x = 'something';
x = 1;
x = 1 + 'hello';
相等:
let x = 0 == ''; // true
let y = 0 === ''; // false, 关心类型
示例:
const people = ['Valentina', 'Niko', 'Eriberto'];
const one = 0; // 没有调用构造:new Number(1);
const str = 'hello world'; // 没有调用构造:new String("hello world")
const b = true;
const person = {
name: 'Valentina',
age: 18,
};
function sayHello(person) {
console.log('Hello ' + person.name);
}
console.log('-- typeof --');
console.log(typeof people); // object(array也是object)
console.log(Array.isArray(people)); // true
console.log(typeof one); // number
console.log(typeof str); // string
console.log(typeof b); // boolean
console.log(typeof person); // object
console.log(typeof sayHello); // function
console.log('-- instanceof --');
console.log(people instanceof Array);
console.log(one instanceof Number); // false 因为没有调用构造
console.log(str instanceof String); // false
console.log(b instanceof Boolean); // false
console.log(person instanceof Object); // true
console.log(sayHello instanceof Function); // true
Control flow and error handling
Overview: Control flow and error handling
if...else
switch
try/catch/throw
Error objects
if...else
statament
Syntax:
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}
False Value:
- false
- undefined
- null
- 0
- NaN
- the empty string ("")
Example:
// < 小于
// <= 小于等于
// > 大于
// >= 大于等于
// == 等等:检查值
// '42' == 42 tests as true
// === 等等:检查值和类型
// '42' === 42 tests as false
// != 不等于:检查值
// !== 不等于:检查值和类型
const status = 200;
if (status === 200) {
console.log('OK!');
} else if (status === 400) {
console.log('Error!');
} else {
console.log('Unknown status');
}
const message = status === 200 ? 'OK!' : 'Error!';
console.log(message);
比较组合:
// And (both sides must be true)
(x & y)(x && y)(
// or (either side can be true)
x | y
)(x || y)(
// Shortcut operators && and ||
// stops evaluation if the answer is already known
x && y
)(
// y not evaluated if x is false
y || y
); // y not evaluated if x is true
switch
statament
Syntax:
switch (expression) {
case label1:
statements1;
break;
case label2:
statements2;
break;
// …
default:
statementsDefault;
}
Example:
const status = 200;
switch (status) {
case 200:
console.log('OK!');
break;
case 400:
case 500:
console.log('Error!');
break;
default:
console.log('Unknown value');
break;
}
try/catch/throw
statament
Example:
function criticalCode() {
throw 'throwing an exception';
}
function logError(theException) {
console.log(theException);
}
console.log('-- throwing exception --');
throw 'myExcption';
throw true;
console.log('-- try catch --');
try {
criticalCode();
} catch (error) {
console.log('Got an error');
logError(error);
}
console.log('-- throwing try catch --');
try {
throw 'An Exception that is thrown every time';
} catch (error) {
console.log('Got an error');
logError(error);
}
console.log('-- try catch finally--');
try {
criticalCode();
} catch (error) {
console.log('Got an error');
logError(error);
} finally {
console.log('Code that always will run');
}
Error objects
依赖于 Error 的类型,一般会用 name 和 message 属性获取更多详细的描述信息:
name
:Error 的类型message
:具体错误的描述信息
Example:
function doSomethingErrorProne() {
if (ourCodeMakesAMistake()) {
throw new Error('The message');
} else {
doSomethingToGetAJavaScriptError();
}
}
try {
doSomethingErrorProne();
} catch (e) {
// Now, we actually use `console.error()`
console.error(e.name); // 'Error'
console.error(e.message); // 'The message', or a JavaScript error message
}
Loops and iteration
Overview: Loops and iteration
for
while
do...while
continue
break
for...in
for...of
for
statement
Syntax:
for (initialization; condition; afterthought) {
statement;
}
while
statement
Syntax:
while (condition) {
statement;
}
do...while
statement
Syntax:
do {
statement;
} while (condition);
continue
statement
Syntax:
continue;
continue label;
break
statement
Syntax:
break;
break label;
for...in
statement
Syntax:
for (variable in object) {
statement;
}
Example:
const person = {
name: 'Valentina',
age: 18,
};
for (const key in person) {
if (Object.hasOwnProperty.call(person, key)) {
const element = person[key];
}
console.log(`key: ${key}; value: ${person[key]}`);
}
for...of
statement
Syntax:
for (variable of object) {
statement;
}
Example1:
const arr = [3, 5, 7];
arr.foo = 'hello';
for (const i in arr) {
console.log(i);
}
// "0" "1" "2" "foo"
for (const i of arr) {
console.log(i);
}
// Logs: 3 5 7
Example2:
const obj = { foo: 1, bar: 2 };
for (const [key, val] of Object.entries(obj)) {
console.log(key, val);
}
// "foo" 1
// "bar" 2
Math:
示例:
let num = 100;
console.log(num + 25);
console.log(num - 100);
console.log(num * 100);
console.log(num / 1500);
console.log(num % 1500);
console.log(++num);
console.log(--num);
num = 100;
console.log(Math.PI);
console.log(Math.sqrt(num));
Converting 数字和字符
示例:
console.log('-- parseInt() --');
let num = '150';
console.log(parseInt('100'));
console.log(parseInt(num));
console.log(parseInt('ABC'));
console.log(parseInt('0xf')); // 15
console.log('-- parseFloat() --');
let flo1 = '1.50';
console.log(parseFloat('1.5'));
console.log(parseFloat('1 + 1'));
console.log(parseFloat('ABC'));
console.log('-- parseInt() --');
console.log(parseInt('1.5'));
console.log(parseInt('1 + 1'));
console.log(parseInt(`${1 + 1}`));
console.log('-- toString() --');
let number = 150;
let float = 1.5;
console.log(number.toString());
console.log(float.toString());
console.log((100).toString());
Date 日期
示例:
console.log('-- creating a date object --');
// get right now
const now = new Date();
const randomDate = new Date(2015, 3, 12, 6, 25, 58);
const win95Launch = new Date(1995, 7, 24);
console.log(now);
console.log(randomDate);
console.log(win95Launch);
console.log('-- setting values --');
// get right now
const now1 = new Date();
now1.setFullYear(2014);
now1.setMonth(3); // April (counting starts at zero)
now1.setDate(4); // set
now1.setHours(4); // 24 hour clock
now1.setMinutes(24);
now1.setSeconds(46);
console.log(now1);
console.log('-- getting values --');
const now2 = new Date();
console.log(now2.getMonth()); // Month of the year
console.log(now2.getTime()); // milliseconds since 1 Jan 1970
console.log(now2.getDay()); // day of the week
数字、日期、数学库
Number
不分 interger 和 float,IEEE 754 的双精度的 64 位浮点数;分为下面三个部分
- 1 bit for the sign (positive or negative)
- 11 bits for the exponent (-1022 to 1023)
- 52 bits for the mantissa (representing a number between 0 and 1)
范围:-2^53 + 1 to 2^53 - 1
,值在Number.MIN_SAFE_INTEGER
和Number.MAX_SAFE_INTEGER
之间
Static properties
Number.MAX_SAFE_INTEGER
:Number.MIN_SAFE_INTEGER
:Number.MAX_VALUE
:Number.MIN_VALUE
:
console.log(Number.MAX_SAFE_INTEGER); // (2**53 - 1) => 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -(2**53 - 1) => -9007199254740991
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
Static methods
Number.isFinite()
:Determine whether the passed value is a finite number.Number.isInteger()
:Determine whether the passed value is an integer.Number.isNaN()
:Determine whether the passed value is NaN.Number.isSafeInteger()
:Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1).Number.parseFloat()
:This is the same as the global parseFloat() function.Number.parseInt()
:This is the same as the global parseInt() function.
Instance methods
toFixed
:转成固定(小数)toPrecision
:精准度(小数)
toFixed()
function financial(x) {
return Number.parseFloat(x).toFixed(2);
}
console.log(financial(123.456));
// Expected output: "123.46"
console.log(financial(0.004));
// Expected output: "0.00"
console.log(financial('1.23e+5'));
// Expected output: "123000.00"
toPrecision()
function precise(x) {
return x.toPrecision(4);
}
console.log(precise(123.456));
// Expected output: "123.5"
console.log(precise(0.004));
// Expected output: "0.004000"
console.log(precise(1.23e5));
// Expected output: "1.230e+5"
BigInt
Math 库
Math.PI
: Ratio of a circle's circumference to its diameter; approximately 3.14159.Math.abs()
: Returns the absolute value of x.Math.max()
: Returns the largest of zero or more numbers.Math.min()
: Returns the smallest of zero or more numbers.Math.random()
: Returns a pseudo-random number between 0 and 1.Math.round()
: Returns the value of the number x rounded to the nearest integer.Math.ceil()
: Returns the smallest integer greater than or equal to x.Math.floor()
: Returns the largest integer less than or equal to x.
Math.random()
function getRandomInt(max: number) {
return Math.floor(Math.random() * max);
}
console.log(getRandomInt(3));
// Expected output: 0, 1 or 2
console.log(getRandomInt(1));
// Expected output: 0
console.log(Math.random());
// Expected output: a number from 0 to <1
Math.round()
console.log(Math.round(0.9));
// Expected output: 1
console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// Expected output: 6 6 5
console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// Expected output: -5 -5 -6
Math.ceil()
console.log(Math.ceil(0.95));
// Expected output: 1
console.log(Math.ceil(4));
// Expected output: 4
console.log(Math.ceil(7.004));
// Expected output: 8
console.log(Math.ceil(-7.004));
// Expected output: -7
Text processing
String
- 创建
- 属性
lenght
:长度
- 常用方法
- 检索:
at
:返回指定位置的字符indexOf
:搜索第一次出现的位置lastIndexOf
:搜索最后一次出现的位置match
:正则搜索一个匹配matchAll
:正则搜索所有匹配的,返回一个迭代器search
:搜索,返回第一次匹配的位置索引
- 检查
includes
:是否包含指定的字符串startWith
:判断字符是不是以指定字符串开始endWith
:判断字符是不是以指定字符串结束
- 修改
concat
:合并两个字符形成一个新padStart
:头部填充指定字符padEnd
:尾部填充指定字符replace
:替换replaceAll
:替换所有splite
:切割,返回数组slice
:返回字符串的一部分substring
:返回字符串的一部分toLowerCase
:转小写toUpperCase
:转大写trim
:删除头部和尾部的空格trimStart
:删除头部的空格trimEnd
:删除尾部的空格
- Other
repeat
:返回一个重复了指定次数的新字符串
- 检索:
创建
// basic
const string1 = 'A string primitive';
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;
const string4 = new String('A String object');
// Multi-lines
const string5 = "string text line 1\n\
string text line 2";
const string6 = `string text line 1
string text line 2`;
// "string text line 1
// string text line 2"
// Embedded expressions
const five = 5;
const ten = 10;
const string7 = "Fifteen is " + (five + ten) + " and not " + (2 * five + ten) + ".";
const string8 = `Fifteen is ${five + ten} and not ${2 * five + ten}.`;
属性
const str = 'Life, the universe and everything. Answer:';
console.log(`${str} ${str.length}`);
// Expected output: "Life, the universe and everything. Answer: 42"
Indexed collections
Array
Int8Array
Uint8Array
Uint8ClampedArray
Int16Array
Uint16Array
Int32Array
Uint32Array
BigInt64Array
BigUint64Array
Float32Array
Float64Array
Array
- 数组大小是动态的,可以存放不同的类型
- JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
- 数组索引是从 0 开始
- JavaScript array-copy operations create shallow copies. (All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies).
Creating an array
const arr1 = new Array(element0, element1, /* …, */ elementN);
const arr2 = Array(element0, element1, /* …, */ elementN);
const arr3 = [element0, element1, /* …, */ elementN];
const arr1 = new Array(arrayLength);
const arr2 = Array(arrayLength);
const arr3 = [];
arr3.length = arrayLength;
Referring to array elements
const arr = ['one', 'two', 'three'];
arr[2]; // three
arr['length']; // 3
Understanding length
const cats = ['Dusty', 'Misty', 'Twiggy'];
console.log(cats.length); // 3
cats.length = 2;
console.log(cats); // [ 'Dusty', 'Misty' ] - Twiggy has been removed
cats.length = 0;
console.log(cats); // []; the cats array is empty
cats.length = 3;
console.log(cats); // [ <3 empty items> ]
Iterating over arrays
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// forEach
colors.forEach((color) => console.log(color));
Array methods
concat
:合并两个或多个 Array 成一新的 Arrayjoin
:合并元素成一个字符串push
:添加一个或多个元素到 Array 数组的尾部,并返回数组长度pop
:从数组中移除最后一个元素,并返回这个元素shift
:从数组中移除最前面的元素,并返回这个元素unshift
:在数组的前面添加一个或多个元素,并返回新数组的长度slice
:提取数组切片,返回一个新的数组at
:获取指定位置的元素splice
:移除元素并替换reverce
:数组反转flat
:返回递归子元素数组中所有元素组成的新数组,可指定递归的深度sort
:排序indexOf
:搜索元素,返回找到的第一个lastIndexOf
:搜索元素,返回找到的最后一个forEach
:迭代map
:转换flatMap
:flat 转换filter
:过滤find
:搜索第一个,并返回元素findLast
:搜索最后一个,并返回元素findIndex
:搜索第一个,并返回索引findLastIndex
:搜索最后一个,并返回索引every
:判断所有的都符合闭包的条件some
:判断是不是有一个符合闭包的条件reduce
:统计计算reduceRight
:统计计算(从右往左迭代)
concat
Syntax:
concat()
concat(value1)
concat(value1, value2)
concat(value1, value2, /_ …, _/ valueN)
let myArray = ['1', '2', '3'];
myArray = myArray.concat('a', 'b', 'c');
// myArray is now ["1", "2", "3", "a", "b", "c"]
join
const myArray = ['Wind', 'Rain', 'Fire'];
const list = myArray.join(' - '); // list is "Wind - Rain - Fire"
push
Syntax:
push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)
const myArray = ['1', '2'];
myArray.push('3'); // myArray is now ["1", "2", "3"]
pop
const myArray = ['1', '2', '3'];
const last = myArray.pop();
// myArray is now ["1", "2"], last = "3"
shift
const myArray = ['1', '2', '3'];
const first = myArray.shift();
// myArray is now ["2", "3"], first is "1"
unshift
Syntax:
unshift()
unshift(element1)
unshift(element1, element2)
unshift(element1, element2, /* …, */ elementN)
const myArray = ['1', '2', '3'];
myArray.unshift('4', '5');
// myArray becomes ["4", "5", "1", "2", "3"]
slice
Syntax:
slice()
slice(start)
slice(start, end)
let myArray = ['a', 'b', 'c', 'd', 'e'];
myArray = myArray.slice(1, 4); // [ "b", "c", "d"]
// starts at index 1 and extracts all elements
// until index 3
at
const myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.at(-2); // "d", the second-last element of myArray
splice
Syntax:
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)
const myArray = ['1', '2', '3', '4', '5'];
myArray.splice(1, 3, 'a', 'b', 'c', 'd');
// myArray is now ["1", "a", "b", "c", "d", "5"]
// 从index为1开始删除三个,并用后面的元素捏的
reverce
const myArray = ['1', '2', '3'];
myArray.reverse();
// transposes the array so that myArray = ["3", "2", "1"]
flat
Syntax:
flat()
flat(depth)
let myArray = [1, 2, [3, 4]];
myArray = myArray.flat();
// myArray is now [1, 2, 3, 4], since the [3, 4] subarray is flattened
sort
Syntax:
sort()
sort(compareFn)
const myArray = ['Wind', 'Rain', 'Fire'];
myArray.sort();
// sorts the array so that myArray = ["Fire", "Rain", "Wind"]
指定比较函数:
const sortFn = (a, b) => {
if (a[a.length - 1] < b[b.length - 1]) {
return -1; // Negative number => a < b, a comes before b
} else if (a[a.length - 1] > b[b.length - 1]) {
return 1; // Positive number => a > b, a comes after b
}
return 0; // Zero => a = b, a and b keep their original order
};
myArray.sort(sortFn);
// sorts the array so that myArray = ["Wind","Fire","Rain"]
indexOf
Syntax:
indexOf(searchElement)
indexOf(searchElement, fromIndex)
const a = ['a', 'b', 'a', 'b', 'a'];
console.log(a.indexOf('b')); // 1
// Now try again, starting from after the last match
console.log(a.indexOf('b', 2)); // 3
console.log(a.indexOf('z')); // -1, because 'z' was not found
lastIndexOf
Syntax:
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
const a = ['a', 'b', 'c', 'd', 'a', 'b'];
console.log(a.lastIndexOf('b')); // 5
// Now try again, starting from before the last match
console.log(a.lastIndexOf('b', 4)); // 1
console.log(a.lastIndexOf('z')); // -1
forEach
Syntax:
forEach(callbackFn)
forEach(callbackFn, thisArg)
callbackFn(element, index, array)
const a = ['a', 'b', 'c'];
a.forEach((element) => {
console.log(element);
});
// Logs:
// a
// b
// c
map
Syntax:
map(callbackFn)
map(callbackFn, thisArg)
const a1 = ['a', 'b', 'c'];
const a2 = a1.map((item) => item.toUpperCase());
console.log(a2); // ['A', 'B', 'C']
flatMap
Syntax:
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
const a1 = ['a', 'b', 'c'];
const a2 = a1.flatMap((item) => [item.toUpperCase(), item.toLowerCase()]);
console.log(a2); // ['A', 'a', 'B', 'b', 'C', 'c']
filter
Syntax:
filter(callbackFn)
filter(callbackFn, thisArg)
const a1 = ['a', 10, 'b', 20, 'c', 30];
const a2 = a1.filter((item) => typeof item === 'number');
console.log(a2); // [10, 20, 30]
find
const a1 = ['a', 10, 'b', 20, 'c', 30];
const i = a1.find((item) => typeof item === 'number');
console.log(i); // 10
findLast
const a1 = ['a', 10, 'b', 20, 'c', 30];
const i = a1.findLast((item) => typeof item === 'number');
console.log(i); // 30
findIndex
const a1 = ['a', 10, 'b', 20, 'c', 30];
const i = a1.findIndex((item) => typeof item === 'number');
console.log(i); // 1
findLastIndex
const a1 = ['a', 10, 'b', 20, 'c', 30];
const i = a1.findLastIndex((item) => typeof item === 'number');
console.log(i); // 5
every
function isNumber(value) {
return typeof value === 'number';
}
const a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // true
const a2 = [1, '2', 3];
console.log(a2.every(isNumber)); // false
some
function isNumber(value) {
return typeof value === 'number';
}
const a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // true
const a2 = [1, '2', 3];
console.log(a2.some(isNumber)); // true
const a3 = ['1', '2', '3'];
console.log(a3.some(isNumber)); // false
reduce
const a = [10, 20, 30];
const total = a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(total); // 60
reduceRight
const array1 = [
[0, 1],
[2, 3],
[4, 5],
];
const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));
// [4, 5] concat [2. 3], concat [0, 1] 成一维数组
console.log(result);
// Expected output: Array [4, 5, 2, 3, 0, 1]
Array transformations
Keyed collections
- Map
- Set
- WeakMap
- WeakSet
Structured data
- ArrayBuffer
- SharedArrayBuffer
- DataView
- Atomics
- JSON
JSON
Static methods
JSON.parse()
:解析成值/对象JSON.stringify()
:值/对象转成 Json 字符串
JSON.parse()
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// Expected output: 42
console.log(obj.result);
// Expected output: true
JSON.stringify()
console.log(JSON.stringify({ x: 5, y: 6 }));
// Expected output: '{"x":5,"y":6}'
console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// Expected output: '[3,"false",false]'
console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol('')] }));
// Expected output: '{"x":[10,null,null,null]}'
console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// Expected output: '"2006-01-02T15:04:05.000Z"'
Promises
Overview: Promises
- Guarantees
- Chaining
- Error handling
- Composition
- Timing
catch(failureCallback)
is short for then(null, failureCallback)
;
() => x
is short for () => { return x; }
)