javascript 备忘单

包含最重要的概念、函数、方法等的 JavaScript 备忘单。初学者的完整快速参考。

开始

介绍

JavaScript 是一种轻量级的解释型编程语言。

console.log()

alert('Hello world!');
console.log('Hello world!');
// => Hello world!

数值

let amount = 6;
let price = 4.99;

变量

let x = null;
let name = "Tammy";
const found = false;// => Tammy, false, nullconsole.log(name, found, x);var a;
console.log(a); // => undefined

字符串

let single = 'Wheres my bandit hat?';
let double = "Wheres my bandit hat?";// => 21console.log(single.length);

算术运算符

5 + 5 = 10// Addition10 - 5 = 5// Subtraction5 * 10 = 50// Multiplication10 / 5 = 2// Division10 % 5 = 0// Modulo

注释

// This line will denote a comment/*  
The below configuration must be 
changed before deployment. 
*/

赋值运算符

let number = 100;// Both statements will add 10
number = number + 10;
number += 10;console.log(number); 
// => 120

字符串插值

let age = 7;// String concatenation'Tommy is ' + age + ' years old.';// String interpolation`Tommy is ${age} years old.`;

let 关键字

let count; 
console.log(count); // => undefined
count = 10;
console.log(count); // => 10

const 关键字

const numberOfColumns = 4;// TypeError: Assignment to constant...
numberOfColumns = 8;

JavaScript 条件

if 语句

const isMailSent = true;if (isMailSent) {
  console.log('Mail sent to recipient');
}

三元运算符

var x=1;// => true
result = (x == 1) ? true : false;

运算符

true || false;       // true10 > 5 || 10 > 20;   // truefalse || false;      // false10 > 100 || 10 > 20; // false
逻辑运算符 &&
true && true;        // true1 > 2 && 2 > 1;      // falsetrue && false;       // false4 === 4 && 3 > 1;    // true
比较运算符
1 > 3// false3 > 1// true250 >= 250// true1 === 1// true1 === 2// false1 === '1'// false
逻辑运算符!
let lateToWork = true;
let oppositeValue = !lateToWork;// => falseconsole.log(oppositeValue); 

否则如果

const size = 10;if (size > 100) {
  console.log('Big');
} elseif (size > 20) {
  console.log('Medium');
} elseif (size > 4) {
  console.log('Small');
} else {
  console.log('Tiny');
}// Print: Small

switch 语句

const food = 'salad';switch (food) {
  case'oyster':
    console.log('The taste of the sea');
    break;
  case'pizza':
    console.log('A delicious pie');
    break;
  default:
    console.log('Enjoy your meal');
}

JavaScript 函数

函数

// Defining the function:
function sum(num1, num2) {
  return num1 + num2;
}

// Calling the function:
sum(3, 6); // 9

匿名函数

// Named functionfunctionrocketToMars() {
  return'BOOM!';
}// Anonymous functionconst rocketToMars = function() {
  return'BOOM!';
}

箭头函数 (ES6)

两个参数
const sum = (param1, param2) => { 
  return param1 + param2; 
}; console.log(sum(2,5)); // => 7 
没有参数
const printHello = () => { 
  console.log('hello'); 
}; 
printHello(); // => hello
一个参数
const checkWeight = weight => { 
  console.log(`Weight : ${weight}`); 
}; 
checkWeight(25); // => Weight : 25 
简洁的箭头函数
const multiply = (a, b) => a * b; 
// => 60 console.log(multiply(2, 30)); 

返回关键字

// With returnfunctionsum(num1, num2) {
  return num1 + num2;
}// The function doesn't output the sumfunctionsum(num1, num2) {
  num1 + num2;
}

调用函数

// Defining the functionfunctionsum(num1, num2) {
  return num1 + num2;
}// Calling the function
sum(2, 4); // 6

函数表达式

const dog = function() {
  return'Woof!';
}

功能参数

// The parameter is namefunctionsayHello(name) {
  return`Hello, ${name}!`;
}

函数声明

functionadd(num1, num2) {
  return num1 + num2;
}

JavaScript 范围

范围

functionmyFunction() {var pizzaName = "Volvo";
  // Code here can use pizzaName
}// Code here can't use pizzaName

块作用域变量

const isLoggedIn = true;if (isLoggedIn == true) {
  const statusMessage = 'Logged in.';
}// Uncaught ReferenceError...console.log(statusMessage);

全局变量

// Variable declared globallyconst color = 'blue';functionprintColor() {
  console.log(color);
}
printColor(); // => blue

JavaScript 数组

数组

const a1 = [0, 1, 2, 3];// Different data typesconst a2 = [1, 'chicken', false];

属性 .length

const numbers = [1, 2, 3, 4];
numbers.length // 4

指数

// Accessing an array elementconst myArray = [100, 200, 300];console.log(myArray[0]); // 100console.log(myArray[1]); // 200

方法 .push()

// Adding a single element:const cart = ['apple', 'orange'];
cart.push('pear'); // Adding multiple elements:const numbers = [1, 2];
numbers.push(3, 4, 5);

方法 .pop()

const a= ['eggs', 'flour', 'chocolate'];const p = a.pop(); // 'chocolate'console.log(a); // ['eggs', 'flour']

可变的

const names = ['Alice', 'Bob'];
names.push('Carl');
// ['Alice', 'Bob', 'Carl']

JavaScript 循环

While 循环

while (condition) {
  // code block to be executed
}let i = 0;
while (i < 5) {        
  console.log(i);
  i++;
}

反向循环

const a = ['banana', 'cherry'];for (let i = a.length - 1; i >= 0; i--){
  console.log(`${i}. ${items[i]}`);
}// => 2. cherry// => 1. banana

Do...while 语句

x = 0
i = 0do {
  x = x + i;console.log(x)
  i++;
} while (i < 5);
// => 0 1 3 6 10

For循环

for (let i = 0; i < 4; i += 1) {
  console.log(i);
};// => 0, 1, 2, 3

循环遍历数组

for (let i = 0; i < array.length; i++){
  console.log(array[i]);
}// => Every item in the array

Break

for (let i = 0; i < 99; i += 1) {
  if (i > 5) {
     break;
  }console.log(i)
}// => 0 1 2 3 4 5

Continue

for (i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}

嵌套循环

for (let i = 0; i < 2; i += 1) {
  for (let j = 0; j < 3; j += 1) {
    console.log(`${i}-${j}`);
  }
}

for...in 循环

let dic = {brand: 'Apple', model: ''};for (let key in mobile) {
  console.log(`${key}: ${mobile[key]}`);
}

JavaScript 迭代器

分配给变量的函数

let plusFive = (number) => {
  return number + 5;  
};// f is assigned the value of plusFivelet f = plusFive;
plusFive(3); // 8// Since f has a function value, it can be invoked. 
f(9); // 14

回调函数

const isEven = (n) => {
  return n % 2 == 0;
}let printMsg = (evenFunc, num) => {
  const isNumEven = evenFunc(num);
  console.log(`${num} is an even number: ${isNumEven}.`)
}// Pass in isEven as the callback function
printMsg(isEven, 4); 
// => The number 4 is an even number: True.

数组方法 .reduce()

const arrayOfNumbers = [1, 2, 3, 4];const sum = arrayOfNumbers.reduce((accumulator, curVal) => {  
  return accumulator + curVal;
});console.log(sum); // 10

数组方法 .map()

const a = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];const announcements = a.map(member => {
  return member + ' joined the contest.';
})console.log(announcements);

数组方法 .forEach()

const numbers = [28, 77, 45, 99, 27];
numbers.forEach(number => {  
  console.log(number);
}); 

数组方法 .filter()

const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {  
  return n > 5;
});

JavaScript 对象

访问属性

const apple = { 
  color: 'Green',
  price: { bulk: '$3/kg', smallQty: '$4/kg' }
};console.log(apple.color); // => Greenconsole.log(apple.price.bulk); // => $3/kg

命名属性

// Example of invalid key namesconst trainSchedule = {
  // Invalid because of the space between words.
  platform num: 10, 
  // Expressions cannot be keys.40 - 10 + 2: 30,
  // A + sign is invalid unless it is enclosed in quotations.
  +compartment: 'C'
}

不存在的属性

const classElection = {
  date: 'January 12'
};console.log(classElection.place); // undefined

可变的

const student = {
  name: 'Sheldon',
  score: 100,
  grade: 'A',
}console.log(student)
// { name: 'Sheldon', score: 100, grade: 'A' }delete student.score
student.grade = 'F'console.log(student)
// { name: 'Sheldon', grade: 'F' }
student = {}// TypeError: Assignment to constant variable.

赋值速记语法

const person = {
  name: 'Tom',
  age: '22',
};const {name, age} = person;
console.log(name); // 'Tom'console.log(age);  // '22'

删除运算符

const person = {
  firstName: "Matilda",
  age: 27,
  hobby: "knitting",
  goal: "learning JavaScript"
};delete person.hobby; // or delete person[hobby];console.log(person);
/*
{
  firstName: "Matilda"
  age: 27
  goal: "learning JavaScript"
}
*/
	

对象作为参数

const origNum = 8;
const origObj = {color: 'blue'};const changeItUp = (num, obj) => {
  num = 7;
  obj.color = 'red';
};
changeItUp(origNum, origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

速记对象创建

const activity = 'Surfing';
const beach = { activity };
console.log(beach); // { activity: 'Surfing' }

this 关键字

const cat = {
  name: 'Pipey',
  age: 8,
  whatName() {
    returnthis.name  
  }
};console.log(cat.whatName()); // => Pipey

工厂函数

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. const dogFactory = (name, age, breed) => {
  return {
    name: name,
    age: age,
    breed: breed,
    bark() {
      console.log('Woof!');  
    }
  };
};

方法

const engine = {
  // method shorthand, with one argument
  start(adverb) {
    console.log(`The engine starts up ${adverb}...`);
  },  // anonymous arrow function expression with no arguments
  sputter: () => {
    console.log('The engine sputters...');
  },
};
engine.start('noisily');
engine.sputter();

Getters and setters

const myCat = {
  _name: 'Dottie',
  get name() {
    returnthis._name;  
  },
  set name(newName) {
    this._name = newName;  
  }
};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the setter
myCat.name = 'Yankee';

JavaScript 类

静态方法

classDog{
  constructor(name) {
    this._name = name;  
  }
  introduce() { 
    console.log('This is ' + this._name + ' !');  
  }// A static methodstatic bark() {
    console.log('Woof!');  
  }
}const myDog = new Dog('Buster');
myDog.introduce();// Calling the static method
Dog.bark();

Class

classSong{
  constructor() {
    this.title;
    this.author;
  }
  play() {
    console.log('Song playing!');
  }
}const mySong = new Song();
mySong.play();

类构造函数

classSong{
  constructor(title, artist) {
    this.title = title;
    this.artist = artist;
  }
}const mySong = new Song('Bohemian Rhapsody', 'Queen');
console.log(mySong.title);

类方法

classSong{
  play() {
    console.log('Playing!');
  }
  stop() {
    console.log('Stopping!');
  }
}

延伸

// Parent classclassMedia{
  constructor(info) {
    this.publishDate = info.publishDate;
    this.name = info.name;
  }
}// Child classclassSongextendsMedia{
  constructor(songData) {
    super(songData);
    this.artist = songData.artist;
  }
}const mySong = new Song({ 
  artist: 'Queen', 
  name: 'Bohemian Rhapsody', 
  publishDate: 1975
});

JavaScript 模块

Require

var moduleA = require( "./module-a.js" );// The .js extension is optionalvar moduleA = require( "./module-a" );
// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x) {
  return x * x * x;
}// In main.jsimport cube from'./moduleA.js';
// Now the `cube` function can be used straightforwardly.console.log(cube(3)); // 27

导出模块

let Course = {};
Course.name = "Javascript Node.js"module.exports = Course;

导入关键字

// add.jsexportconst add = (x, y) => {
    return x + y
}// main.jsimport { add } from'./add';
console.log(add(2, 3)); // 5

JavaScript 承诺

承诺状态

const promise = newPromise((resolve, reject) => {
  const res = true;
  // An asynchronous operation.if (res) {
    resolve('Resolved!');
  }else {
    reject(Error('Error'));
  }
});
promise.then((res) => console.log(res), (err) => alert(err));

执行器函数

const executorFn = (resolve, reject) => {
  resolve('Resolved!');
};const promise = newPromise(executorFn);

setTimeout()

const loginAlert = () =>{
  alert('Login');
};
setTimeout(loginAlert, 6000); 

.then() 方法

const promise = newPromise((resolve, reject) => {    
  setTimeout(() => {
    resolve('Result');
  }, 200);
});
promise.then((res) => {
  console.log(res);
}, (err) => {
  alert(err);
}); 

.catch() 方法

const promise = newPromise((resolve, reject) => {  
  setTimeout(() => {
    reject(Error('Promise Rejected Unconditionally.'));
  }, 1000);
});
promise.then((res) => {
  console.log(value);
});
promise.catch((err) => {
  alert(err);
});

Promise.all()

const promise1 = newPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(3);
  }, 300);
});const promise2 = newPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(2);
  }, 200);
});Promise.all([promise1, promise2]).then((res) => {
  console.log(res[0]);
  console.log(res[1]);
});

避免嵌套 Promise 和 .then()

const promise = newPromise((resolve, reject) => {  
  setTimeout(() => {
    resolve('*');
  }, 1000);
});const twoStars = (star) => {  
  return (star + star);
};const oneDot = (star) => {  
  return (star + '.');
};const print = (val) => {
  console.log(val);
};// Chaining them all together
promise.then(twoStars).then(oneDot).then(print);

创建

const executorFn = (resolve, reject) => {
  console.log('The executor function of the promise!');
};const promise = newPromise(executorFn);

链接多个 .then()

const promise = newPromise(resolve => setTimeout(() => resolve('dAlan'), 100));
promise.then(res => {
  return res === 'Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')
}).then((res) => {
  console.log(res)
}, (err) => {
  alert(err)
});

JavaScript 异步等待

异步

functionhelloWorld() {
  returnnewPromise(resolve => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}const msg = asyncfunction() { //Async Function Expressionconst msg = await helloWorld();
  console.log('Message:', msg);
}const msg1 = async () => { //Async Arrow Functionconst msg = await helloWorld();
  console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
msg1(); // Message: Hello World! <-- after 2 seconds

解决承诺

let pro1 = Promise.resolve(5);
let pro2 = 44;
let pro3 = newPromise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});Promise.all([pro1, pro2, pro3]).then(function(values) {
  console.log(values);
});// expected => Array [5, 44, "foo"]

异步等待承诺

functionhelloWorld() {
  returnnewPromise(resolve => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}asyncfunctionmsg() {
  const msg = await helloWorld();
  console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds

错误处理

let json = '{ "age": 30 }'; // incomplete datatry {
  let user = JSON.parse(json); // <-- no errors
  alert( user.name ); // no name!
} catch (e) {
  alert( "Invalid JSON data!" );
}

Aysnc 等待运算符

functionhelloWorld() {
  returnnewPromise(resolve => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}asyncfunctionmsg() {
  const msg = await helloWorld();
  console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds

JavaScript 请求

JSON

const jsonObj = {
  "name": "Rick",
  "id": "11A",
  "level": 4
};

XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open('GET', 'mysite.com/getjson');

GET

const req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', '/getdata?id=65');
req.onload = () => {
  console.log(xhr.response);
};
req.send();

POST

const data = {
  fish: 'Salmon',
  weight: '1.5 KG',
  units: 5
};const xhr = new XMLHttpRequest();
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));
xhr.onload = () => {
  console.log(xhr.response);
};

获取 API

fetch(url, {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'apikey': apiKey
    },
    body: data
  }).then(response => {
    if (response.ok) {
      return response.json();
    }thrownewError('Request failed!');
  }, networkError => {
    console.log(networkError.message)
  })
}

JSON 格式

fetch('url-that-returns-JSON')
.then(response => response.json())
.then(jsonResponse => {
  console.log(jsonResponse);
});

承诺url参数获取api

fetch('url')
.then(
  response  => {
    console.log(response);
  },
 rejection => {
    console.error(rejection.message);
);

获取 API 函数

fetch('https://api-xxx.com/endpoint', {
  method: 'POST',
 body: JSON.stringify({id: "200"})
}).then(response => {
  if(response.ok){
	  return response.json();  
  }
	thrownewError('Request failed!');
}, networkError => {
  console.log(networkError.message);
}).then(jsonResponse => {
  console.log(jsonResponse);
})

异步等待语法

const getSuggestions = async () => {
  const wordQuery = inputField.value;
  const endpoint = `${url}${queryParams}${wordQuery}`;
  try{
const response = await fetch(endpoint, {cache: 'no-cache'});
    if(response.ok){
      const jsonResponse = await response.json()
    }
  }catch(error){
    console.log(error)
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值