JavaScript 常用语法
Hello, JS!
// 在控制台输出
console.log('AwesomeProgram!');
// 在网页输出
document.write('AwesomeProgram!');
// 在网页中创建元素进行输出
let hello = document.createElement('h1');
hello.innerText = 'AwesomeProgram!';
document.body.appendChild(hello);
// 使用浏览器弹窗输出
alert('AwesomeProgram!');
解构赋值
let [first, last] = ['Awesome', 'Program']
// or
let {first, last} = {
first: 'Awesome',
last: 'Program'
}
字符串操作
"AwesomeProgram".includes("some") // true
"AwesomeProgram".startsWith("Awesome") // true
"AwesomeProgram".endsWith("Program") // true
'Awe:some:Program'.split(':') // ["Awe", "some", "Program"]
parseFloat("123").toFixed(2) // "123.00"
箭头函数
const getName = user => user.name
const funcName = name => {
// do something
return name
}
数组遍历
const numbers = [1, 2, 3]
numbers.map(n => n * 2) // [2, 4, 6]
numbers.filter(n => n % 2 === 0) // [2]
numbers.reduce((prev, next) => prev + next, 0) // 6
numbers.find(n => n > 2) // 3
数组操作
// Delete at index
array.splice(index, 1)
// Insert at index
array.splice(index, 0, newItem)
// check exist
[1, 2, 3].includes(3) // true
// find index
[1, 2, 3].indexOf(3) // 2; return -1 if not found
// concat
let array3 = array1.concat(array2) // [1].concat([2]) is [1, 2]
// new array
let array4 = [1, 2, 3, 4, 5].slice(2, 4) // [3, 4]
展开操作符
const array1 = [1, 2]
const array2 = [...array1, 3, 4] // [1, 2, 3, 4]
const funcName = (x, ...params) => {
console.log(x)
console.log(params)
}
funcName(1, 2, 3, 4)
// 1
// [2, 3, 4]
对象展开
const options = {
...defaults,
show: true
}
数组展开
const array3 = [
...array1,
...array2,
'newItem'
]
遍历
for (const i of [1, 2, 3]) {
console.log(i)
}
// 1
// 2
// 3
for (const [index, value] of ['Awesome', 'Program', '@git'].entries()) {
console.log(index, value)
}
// 0 "Awesome"
// 1 "Program"
// 2 "@git"
const obj = {part1: 'Awesome', part2: 'Program', part3: '@git'};
for (const key in obj) {
console.log(key, obj[key])
}
// or
for (const [key, value] of Object.entries(obj)) {
console.log(key, value)
}
// part1 Awesome
// part2 Program
// part3 @git
创建 Promise
const funcName = params => {
return new Promise((resolve, reject) => {
// ....
// do something
// if success
resolve(result)
// if fail
reject(error)
})
}
funcName('test')
.then(result => {
// ...
})
.catch(error => {
// ...
})
.finally(() => {
// ...
})
收集所有 Promise 返回
let promises = []
// func1 and func2 returns a promise
promises.push(func1())
promises.push(func2())
Promise.all(promises).then(allResult => {
let [result1, resul2] = allResult
// ...
})
Async-await
const funcName = async () => {
const data = await fetchData()
return data
}
await funcName()
生成器
function * countdown(n) {
for (let i = n; i > 0; --i) {
yield i
}
}
[...countdown(3)] // [ 3, 2, 1 ]
let gen = countdown(3)
gen.next() // 3
gen.next() // 2
浏览器
encodeURIComponent() // Encodes a URI into UTF-8
decodeURIComponent() // Decodes
window
const formData = new window.FormData()
formData.append('file', data)
window.localStorage.getItem(key)
window.localStorage.setItem(key, data)
window.location.origin // "https://awesomeprogram.github.io/"
window.location.hostname // "awesomeprogram.github.io"
window.location.href // "https://awesomeprogram.github.io/js-ts/chapter_1_1.html"
window.open("https://awesomeprogram.github.io/")
window.addEventListener('resize', resizeHandler)
window.removeEventListener('resize', resizeHandler)
XMLHttpRequest
// Download excel file
const xhr = new window.XMLHttpRequest()
const applicationType = 'application/vnd.ms-excel; charset=UTF-8'
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.onload = function(e) {
if (this.status === 200) {
let blob = new window.Blob([this.response], { type: applicationType })
let downloadUrl = window.URL.createObjectURL(blob)
let a = document.createElement('a')
a.href = downloadUrl
a.download = fileName
a.click()
}
}
xhr.onreadystatechange = e => {
if (xhr.readyState === 4) {
//
} else if (xhr.readyState === 3) {
//
})
}
xhr.send()
Email Validation
// From https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
function validateEmail(email) {
if (email === '') {
return true
}
const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
TypeScript 常用语法
编译到 JavaScript
tsc --outFile sample.js Test.ts
基本
let name: string = 'name';
let isDone: boolean = false;
let count: number = 10;
let sentence: string = `Hello, ${ name }.`
let notSure: any = 1;
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
let tupleX: [string, number];
x = ['hello', 10]
enum Color {Red, Green, Blue};
let c: Color = Color.Green;
let [first, ...rest] = [1, 2, 3, 4];
// first: 1, rest: [2, 3, 4 ]
// type assert
let strLength: number = (<string>someValue).length;
let strLength: number = (someValue as string).length;
函数
const params = (value: string) => {
console.log(value);
}
const paramOr = (value: string | null) => {
console.log(value);
}
paramOr('1'); // OK
paramOr(null); // OK
paramOr(1); // Error
const paramArray = ([first, second]: [string, number]) => {
console.log(first);
console.log(second);
}
const returnValue = (): String => {
return 'return a stirng';
}
接口
interface Config {
color?: string;
width?: number;
readonly y?: number;
[propName: string]: any;
}
const funcName = (config: Config) => {
console.log(config.test);
}
funcName({test: 'test prop'}); // test prop
类
class Example {
name: string; // default public
private priaveName: string;
protected protectedName: string;
readonly readonlyName: string;
private _fullName: string;
static baseRoute = '/basePath';
constructor(name: string) {
this.name = name;
this.priaveName = name;
this.protectedName = name;
this.readonlyName = name;
this._fullName = name;
}
hello() {
return `Hello, ${this.name}`;
}
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
// do some check
// ...
this._fullName = newName;
}
}
let test = new Example("world");
console.log(test.hello()); // Hello, world
test.priaveName; // Error
class NewExample extends Example {
hi() {
return `Hi, ${super.hello()}`;
}
getProtectedName() {
return this.protectedName
}
}
let newTest = new NewExample("new world");
console.log(newTest.hi()); // Hi, Hello, new world
newTest.protectedName; // Error
newTest.getProtectedName(); // OK
// Abstract Class
abstract class AbstractExample {
abstract hi(): void;
say(): void {
console.log('say something');
}
}
class ActualExample extends AbstractExample {
hi() {
return 'hi'
}
}
命名空间
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
Validation.StringValidator;
泛型
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
声明
# File ends with `.d.ts`
declare var testNumber: number;
declare function hi(greeting: string): void;
declare namespace myNamespace {
function hello(s: string): string;
let count: number;
}