我很早学过,只是当时没有系统记录笔记,导致过一段时就容易忘记很多东西。本笔记主要参考JavaScript 基础-千古前端图文教程mdn web docs - JavaScript

Web 前端有三层:

  • HTML:从语义的角度,描述页面结构
  • CSS:从审美的角度,描述样式(美化页面)
  • JavaScript(简称 JS):从交互的角度,描述行为(实现业务逻辑和页面控制)

Date

Date() constructor

The Date() constructor can create a Date instance or return a string representing the current time.

const date1 = new Date()

getFullYear()

The getFullYear() method returns the year of the specified date according to local time.

1
2
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getFullYear()); // Expected output: 2000

getMonth()

The getMonth() method returns the month on the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

1
2
3
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getMonth()); // Expected output: 6
// January - December : 0 - 11

getDate()

The getDate() method returns the day of the month for the specified date according to local time.(几号)

1
2
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getDate()); // Expected output: 9

getDay()

The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday. (周几)

1
2
3
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getDay()); // Expected output: 3
// Sunday - Saturday : 0 - 6

getHours()

The getHours() method returns the hour for the specified date, according to local time.

1
2
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getHours()); // Expected output: 0

getMinutes()

The getMinutes() method returns the minutes on the specified date according to local time.

1
2
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getMinutes(); // Expected output: 0

getSeconds()

The getSeconds() method returns the seconds in the specified date according to local time.

1
2
const birthday = new Date('August 9, 2000 00:00:00');
console.log(birthday.getSeconds(); // Expected output: 0

getTime()

The getTime() method returns the number of milliseconds since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

1
2
3
const DOB = new Date('2000/08/09 00:00:00');
// Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
console.log(moonLanding.getTime()); // Expected output: 965775600000

Math

Methods

floor()

The Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.

1
2
3
4
console.log(Math.floor(5.95)); // Expected output: 5
console.log(Math.floor(5.05)); // Expected output: 5
console.log(Math.floor(5)); // Expected output: 5
console.log(Math.floor(-5.05)); // Expected output: -6

ceil()

The Math.ceil() static method always rounds up and returns the smaller integer greater than or equal to a given number.

1
2
3
4
console.log(Math.ceil(.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

round()

The Math.round() static method returns the value of a number rounded to the nearest integer.

1
2
3
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

random()

Math.floor(Math.random() * y + x) 👉 [x, y) 区间的随机整数

Math.ceil(Math.random() * y + x) 👉 (x, y] 区间的随机整数

Math.round(Math.random() * y + x) 👉 [x, y] 区间的随机整数

Array

Properties

length

The length property of an Array object represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Try it:

1
2
const clothing = ["shoes", "shirts", "socks", "sweaters"];
console.log(clothing.length); // 4

Methods

concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays but returns a new array.

1
2
3
4
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // Expected output: Array ["a", "b", "c", "d", "e", "f"]

其实扩展语法(spread syntax)更好:

1
2
3
4
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArr = [...arr1, ...arr2];
console.log(combinedArr); // [1, 2, 3, 4, 5, 6]

使用扩展语法可以使代码更简洁易读,而且性能也比使用 concat() 方法更好

forEach()

The forEach() method executes a provided function once for each array element.

例如:

1
2
3
4
5
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

人话说就是如果所有元素满足条件,就返回 true,反之。

1
2
3
const array1 = [1, 30, 39, 29, 10, 13];
const isBelowThreshold = (currentValue) => currentValue < 40;
console.log(array1.every(isBelowThreshold)); // true

some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

人话说就是如果至少有一个元素满足条件,就返回 true,反之。

1
2
3
4
const array = [1, 2, 3, 4, 5];
// Checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even)); // Expected output: true

includes()

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

1
2
3
4
5
6
const array1 = [1, 2, 3];
console.log(array1.includes(2)); // Expected output: true

const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat')); // Expected output: true
console.log(pets.includes('at')); // Expected output: false

indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

1
2
3
4
5
6
7
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison')); // Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2)); // Expected output: 4

console.log(beasts.indexOf('giraffe')); // Expected output: -1

isArray()

The Array.isArray() static method determines whether the passed value is an Array.

1
2
console.log(Array.isArray([1, 3, 5])); // Expected output: true
console.log(Array.isArray('Harris')); // Expected output: false

filter()

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

人话说就是返回满足条件的元素新数组。

1
2
3
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
const result = words.filter((word) => word.length > 6);
console.log(result); // Array ["exuberant", "destruction", "present"]

filter() 可以用来移除数组里对应值的元素。返回一个新数组,条件设为不等于某个值即可。

find()

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

人话说就是返回第一个满足条件的元素。

1
2
3
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // Expected output: 12

findIndex()

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

1
2
3
4
const array1 = [8, 9, 666, 666, 999];
const myNumber = (element) => element = 666;
console.log(array1.findIndex(myNumber));
// Expected output: 2

join()

The join() method creates and returns a new string by concatenating(连接) all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

1
2
3
4
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join()); // Expected output: "Fire,Air,Water"
console.log(elements.join('')); // Expected output: "FireAirWater"
console.log(elements.join('-')); // Expected output: "Fire-Air-Water"

push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

1
2
3
4
5
6
7
8
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // Expected output: 4
console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

reduce()

reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

1
2
3
4
5
6
7
8
9
10
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);

console.log(sumWithInitial); // Expected output: 10

第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。

reverse()

reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组

1
2
3
4
5
6
7
8
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1); // Expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed); // Expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1); // Expected output: "array1:" Array ["three", "two", "one"]

slice()

slice() 方法返回一个新的数组对象,这一对象是一个由 beginend 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。(左闭右开)

1
2
3
4
5
6
7
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); // Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)); // Expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 10)); // Expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2)); // Expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1)); // Expected output: Array ["camel", "duck"]
console.log(animals.slice()); // Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

1
2
3
4
5
6
7
8
9
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb'); // Inserts at index 1
console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May'); // Replaces 1 element at index 4
console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April", "May"]

months.splice(4, 1); // Delete 1 element at index 4
console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April"]

Syntax

1
2
3
4
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item0)
splice(start, deleteCount, item0, item1, /* … ,*/ itemN)

start: Zero-based index at which to start changing the array.

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

1
2
3
4
5
6
7
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

Object

Methods

keys()

Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和正常循环遍历该对象时返回的顺序一致。

1
2
3
4
5
6
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1)); // Expected output: Array ["a", "b", "c"]

values()

DITTO

entries()

TODO

String

Properties

length

The length method returns the length of a specified string.

Note: The length of an empty string is 0.

Try it:

1
2
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length); //26

Methods

lastIndexOf()

lastIndexOf() 方法返回调用 String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex 处从后向前搜索。如果没找到这个特定值则返回 -1。

Syntax: str.lastIndexOf(searchValue[, fromIndex])

searchValue: 一个字符串,表示被查找的值。

fromIndex(可选): 待匹配字符串 searchValue 的开头一位字符从 str 的第 fromIndex 位开始向左回向查找。fromIndex默认值是 +Infinity。如果 fromIndex >= str.length ,则会搜索整个字符串。如果 fromIndex < 0 ,则等同于 fromIndex == 0

slice()

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

左闭右开

Try it:

1
2
3
4
5
6
7
8
9
10
11
12
13
const str = "The quick brown fox jumps over the lazy dog.";

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

console.log(str.slice(-4));
// expected output: "dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"

substring()

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.(用法和slice()相似,看例子知用法)

左闭右开

Try it:

1
2
3
4
5
6
7
8
9
10
11
12
13
const anyString = "Mozilla";

console.log(anyString.substring(0, 1)); // 'M'
console.log(anyString.substring(1, 0)); // 'M'

console.log(anyString.substring(0, 6)); // 'Mozill'

console.log(anyString.substring(4)); // 'lla'
console.log(anyString.substring(4, 7)); // 'lla'
console.log(anyString.substring(7, 4)); // 'lla'

console.log(anyString.substring(0, 7)); // 'Mozilla'
console.log(anyString.substring(0, 10)); // 'Mozilla'

split()

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Try it:

1
2
3
4
5
6
7
8
9
10
11
12
13
const str = "The quick brown fox jumps over the lazy dog.";

const words = str.split(" ");
console.log(words[3]);
// expected output: "fox"

const chars = str.split("");
console.log(chars[8]);
// expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

startsWith()

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

Syntax:

1
2
startsWith(searchString);
startsWith(searchString, position);

searchString: The characters to be searched for at the start of this string. Cannot be a regex(正则表达式).

position (optional): The start position at which searchString is expected to be found (the index of searchString's first character). Defaults to 0.

Try it:

1
2
3
4
5
const str = "To be, or not to be, that is the question.";

console.log(str.startsWith("To be")); // true
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be", 10)); // true

endsWith()

The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.(用法和starsWith()相似,不多说)

Try it:

1
2
3
4
5
6
7
8
9
10
11
12
const str1 = "Cats are the best!";

console.log(str1.endsWith("best!"));
// expected output: true

console.log(str1.endsWith("best", 17));
// expected output: true

const str2 = "Is this a question?";

console.log(str2.endsWith("question"));
// expected output: false

toLowerCase()

The toLowerCase() method returns the calling string value converted to lower case.

1
2
const sentence = 'HarrisWong';
console.log(sentence.toLowerCase()); // Expected output: "harriswong"

toUpperCase()

DITTO

trim()

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.

1
2
3
4
5
6
7
const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: " Hello world! ";

console.log(greeting.trim());
// Expected output: "Hello world!";

filter()

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

1
2
3
4
5
6
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

replace()

replace() 根据规则将字符串中某部分替换成新内容,并返回新字符串。

语法:replace(substr|regexp, newSubStr|function)

第一个参数是要被替换的老字符串,或者正则表达式,记得用斜线 / 围上,后面可以加 g 或者 i 或者 gi,代表全局匹配、忽略大小写。

第二个参数是新字符串,或者函数,该函数返回着将替换掉第一个参数匹配到对结果。

1
2
3
4
5
6
7
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/gi;
console.log(p.replace(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

Number

Methods

toLocaleString()

toLocaleString() 方法返回这个数字在特定语言环境下的表示字符串

Syntax: toLocaleString([locales, options])

localesoptions 参数让应用程序可以指定要进行格式转换的语言,并且定制函数的行为。

1
2
const number = 8090;
console.log(number.toLocaleString()); // Displays "8,090" if in U.S. English locale

常用的就是将数字每三个数位用逗号分隔开

Document

Methods

querySelector()

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

例如:

const el = document.querySelector(".myclass");

querySelectorAll()

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

例如:

1
2
const matches1 = document.querySelectorAll("p");
const matches2 = document.querySelectorAll("div.note, div.alert");

后者是返回所有满足 .note 或者 .alert 的元素列表

Element

Properties

innerHTML

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.

get HTML

Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.

let contents = element.innerHTML;

set HTML

element.innerHTML = contents;

innerText

innerText 属性表示一个节点及其后代的“渲染”文本内容。

get Text

let text = element.innerText;

set Text

element.innerText = text

textContent

DITTO

textContentinnerText 区别是:

innerText 属性是一个非标准属性,它返回元素及其子元素中的渲染文本内容,它不考虑样式的影响并忽略空白符号。由于这个属性是非标准的,因此不是所有浏览器都支持它,也可能在将来被废弃。

textContent 属性返回元素及其子元素中的所有文本内容,包括空白字符和隐藏元素中的文本,但不考虑样式的影响。这个属性在所有现代浏览器中都得到支持,并且是标准属性。

Window

Properties

scrollY

The read-only scrollY property of the Window interface returns the number of pixels that the document is currently scrolled vertically.

Syntax: window.scrollY

scrollX

DITTO

innerHeight

The read-only innerHeight property of the Window interface returns the interior height of the window in pixels, including the height of the horizontal scroll bar, if present.

innerwidth

DITTO

localStorage

The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is when the page is closed. (localStorage data for a document loaded in a "private browsing" or "incognito"(无痕浏览) session is cleared when the last "private" tab is closed.)

setItem()

The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().

1
2
const catStr = JSON.stringify(cat);
localStorage.setItem("cat", catStr);

Note:

value must be a string, so if you have a more complex value like an array or object to save, you'll need to use: JSON.stringify(value)

It can turn that array or object into a stringified version or rather a JSON version that can be saved in local storage.

On the contrary, we can use JSON.parse() to turn the stringified array back into a real JS array.

getItem()

The syntax for reading the localStorage item is as follows:

let cat = JSON.parse(localStorage.getItem('key'));

removeItem()

The syntax for removing the localStorage item is as follows:

localStorage.removeItem('key');

clear()

The syntax for removing all the localStorage items is as follows:

localStorage.clear();

Methods

setInterval()

The setInterval() method calls a function at specified intervals (in milliseconds).

The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

Syntax: setInterval(function, milliseconds, param1, param2, ...)

param is optional, which can be passed to the function.

The return value of setInterval() is the Id of the timer. We can use clearInterval(Id) to cancel the timer.

1
2
3
4
5
const myInterval = setInterval(() => {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}, 1000);
clearInterval(myInterval);

setTimeout()

The setTimeout() method calls a function after a number of milliseconds.

Syntax: setTimeout(function, milliseconds, [param1, param2, ...])

param is optional, which can be passed to the function.

The return value of setTimeout() is also the Id of the timer.

1
2
const myTimeout = setTimeout(myGreeting, 5000);
clearTimeout(myTimeout);

scrollTo()

The scrollTo() method scrolls the document to specified coordinates(坐标).

Syntax: scrollTo(x-coord, y-coord)

  • x-coord 是文档中的横轴坐标。
  • y-coord 是文档中的纵轴坐标。

Syntax: scrollTo(options)

options 是一个包含三个属性的对象:

  1. top 等同于 y-coord
  2. left 等同于 x-coord
  3. behavior 类型 String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值 auto

例如:

1
2
3
4
5
6
7
element.scrollTo(0, 1000);
// or
element.scrollTo({
top: 100,
left: 100,
behavior: 'smooth'
});

☕欲知后事如何,

且听下回分解🍵