Post's cover

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

Web 前端有三层:

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

H1Date

H2Date() constructor

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

const date1 = new Date()

H2getFullYear()

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

jsconst birthday = new Date("August 9, 2000 00:00:00"); console.log(birthday.getFullYear()); // Expected output: 2000

H2getMonth()

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).

jsconst birthday = new Date("August 9, 2000 00:00:00"); console.log(birthday.getMonth()); // Expected output: 6 // January - December : 0 - 11

H2getDate()

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

jsconst birthday = new Date("August 9, 2000 00:00:00"); console.log(birthday.getDate()); // Expected output: 9

H2getDay()

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

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

H2getHours()

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

jsconst birthday = new Date("August 9, 2000 00:00:00"); console.log(birthday.getHours()); // Expected output: 0

H2getMinutes()

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

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

H2getSeconds()

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

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

H2getTime()

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.

jsconst 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

H1Math

H2Methods

H3abs()

The Math.abs() static method returns the absolute value of a number.

jsfunction difference(a, b) { return Math.abs(a - b); } console.log(difference(3, 5)); // Expected output: 2 console.log(difference(5, 3)); // Expected output: 2

H3ceil()

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

jsconsole.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

H3floor()

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

jsconsole.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

H3max() & min()

jsconsole.log(Math.max(1, 3, 2)); // Expected output: 3 console.log(Math.max(-1, -3, -2)); // Expected output: -1 const array1 = [1, 3, 2]; console.log(Math.max(...array1)); // Expected output: 3

Note: Math.max(...aaray1). We should use spread syntax.

H3pow()

jsconsole.log(Math.pow(3, 2)); // Expected output: 9 console.log(Math.pow(4, 0.5)); // Expected output: 2

Recommend: 2 ** 3 = 8

H3random()

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

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

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

H3round()

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

jsconsole.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

H1Array

H2Properties

H3length

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:

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

H2Methods

H3at()

The at() method of Array instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

jsconst array1 = [5, 12, 8, 130, 44]; let index = 2; console.log(`An index of ${index} returns ${array1.at(index)}`); // Expected output: "An index of 2 returns 8" index = -2; console.log(`An index of ${index} returns ${array1.at(index)}`); // Expected output: "An index of -2 returns 130"

H3concat()

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

jsconst 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)**更好:

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

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

H3every()

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

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

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

H3map()

The map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.

jsconst array1 = [1, 4, 9, 16]; // Pass a function to map const map1 = array1.map((x) => x * 2); console.log(map1); // Expected output: Array [2, 8, 18, 32]

H3includes()

includes() 方法用来判断一个数组是否包含某特定值,返回 boolean 值。

jsconst 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

H3indexOf()

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.

jsconst 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

H3isArray()

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

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

H3⭐️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.

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

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

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

H3find()

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.

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

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

H3findIndex()

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.

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

H3flat()

The flat() method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

jsconst arr1 = [0, 1, 2, [3, 4]]; console.log(arr1.flat()); // expected output: Array [0, 1, 2, 3, 4] const arr2 = [0, 1, [2, [3, [4, 5]]]]; console.log(arr2.flat()); // expected output: Array [0, 1, 2, Array [3, Array [4, 5]]] console.log(arr2.flat(2)); // expected output: Array [0, 1, 2, 3, Array [4, 5]] console.log(arr2.flat(Infinity)); // expected output: Array [0, 1, 2, 3, 4, 5]

H3forEach()

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

jsconst array1 = ["a", "b", "c"]; array1.forEach((element) => console.log(element)); // Expected output: "a" // Expected output: "b" // Expected output: "c"

H3join()

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.

jsconst 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"

H3push()

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

jsconst 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"]

H3⭐️reduce()

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

Syntax:

jsreduce(callbackFn); reduce(callbackFn, initialValue); callbackFn: accumulator, currentValue, currentIndex, array;

Example:

jsconst 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)。

H3reduceRight()

From right-to-left.

H3reverse()

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

jsconst 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"]

H3shift()

The shift() method of Array instances removes the first element from an array and returns that removed element. This method changes the length of the array.

jsconst array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(array1); // Expected output: Array [2, 3] console.log(firstElement); // Expected output: 1

H3slice()

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

jsconst 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"]

H3some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

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

jsconst 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

H3sort()

The default sort order is ascending.

jsconst months = ["March", "Jan", "Feb", "Dec"]; months.sort(); console.log(months); // Expected output: Array ["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // Expected output: Array [1, 100000, 21, 30, 4]

Syntax:

jssort(); sort(compareFn);

The compareFn return value should be a number that indicates the relative order of the two elements. Let's say a & b. Descending if b - a, ascending if a - b.

H3⭐️splice()

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

jsconst 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:

jssplice(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.

H3toSorted()

The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.

H3unshift()

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

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

H1Object

H2Methods

H3keys() & values()

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

jsconst object1 = { a: "somestring", b: 42, c: false, }; console.log(Object.keys(object1)); // Expected output: Array ["a", "b", "c"]

H3entries()

js[ ["a", "somestring"], ["b", 42], ["c", false], ];

H1String

H2Properties

H3length

The length method returns the length of a specified string.

Note: The length of an empty string is 0.

Try it:

jsvar txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; console.log(txt.length); //26

H2Methods

H3charCodeAt()

The charCodeAt() method of String values returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

Try it:

jsconst name = "Harris"; console.log(name.charCodeAt(1)); // 97. Becuase "a" is 97

H3fromCharCode()

The String.fromCharCode() static method returns a string created from the specified sequence of UTF-16 code units.

Try it:

jsconsole.log(String.fromCharCode(97, 98, 99)); // 'abc'

H3lastIndexOf()

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

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

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

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

H3slice()

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

左闭右开

Try it:

jsconst 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"

H3substring()

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:

jsconst 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'

H3split()

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:

jsconst 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."]

H3startsWith()

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

Syntax:

jsstartsWith(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:

jsconst 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

H3endsWith()

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

Try it:

jsconst 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

H3padEnd()

Same as below

H3padStart()

The padStart() method of String values pads this string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of this string.

jsconst str1 = "5"; console.log(str1.padStart(2, "0")); // Expected output: "05"

H3toLowerCase() & toUpperCase()

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

jsconst sentence = "HarrisWong"; console.log(sentence.toLowerCase()); // Expected output: "harriswong"

H3trim()

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

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

H3repeat()

The repeat() method of String values constructs and returns a new string which contains the specified number of copies of this string, concatenated together.

js"abc".repeat(0); // '' "abc".repeat(1); // 'abc' "abc".repeat(2); // 'abcabc' "abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)

H3replace()

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

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

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

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

jsconst paragraph = "I think Ruth's dog is cuter than your dog!"; console.log(paragraph.replace("Ruth's", "my")); // Expected output: "I think my dog is cuter than your dog!" const regex = /Dog/i; console.log(paragraph.replace(regex, "ferret")); // Expected output: "I think Ruth's ferret is cuter than your dog!"

H1Number

H2Methods

H3toFixed()

jsfunction financial(x) { return 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.23e5)); // Expected output: "123000.00"

H3toLocaleString()

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

Syntax: toLocaleString([locales, options])

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

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

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

H3toString()

The toString() method of Number values returns a string representing this number value.

jsconsole.log(89.toStirng()); // "89" console.log(2.toStirng(2)); // "10"

H1Set

Set objects are collections of values. A value in the set may only occur once;

Note: you can put String and Array in Set() to turn into Set.

H2Properties

H3size

Like length.

H2Methods

H3add()

The add() method of Set instances inserts a new element with a specified value in to this set, if there isn't an element with the same value already in this set.

jsconst set1 = new Set(); set1.add(42); set1.add(42); set1.add(13); for (const item of set1) { console.log(item); // Expected output: 42 // Expected output: 13 }

H3delete()

The delete() method of Set instances removes a specified value from this set, if it is in the set.

jsconst set1 = new Set([1, 2]); set1.delete(1); for (const item of set1) { console.log(item); } // 2

H1Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

jsconst map1 = new Map(); map1.set('a', 1); map1.set('b', 2); map1.set('c', 3); console.log(map1.get('a')); // Expected output: 1 map1.set('a', 97); console.log(map1.get('a')); // Expected output: 97 console.log(map1.size); // Expected output: 3 map1.delete('b'); console.log(map1.size); // Expected output: 2

Differences between Map and Object:

  • Key type: The keys of Object can only be string or Symbol types, while the keys of Map can be of any type, including basic data types, objects, functions, etc.
  • Number of key-value pairs: The number of key-value pairs of Object is not easy to obtain directly and needs to be calculated manually, while the number of key-value pairs of Map can be obtained directly through the size attribute.
  • Iteration order: There is no order guarantee for the properties of Object, and the order of key-value pairs cannot be guaranteed when traversing, while Map will maintain the insertion order.
  • Performance: In scenarios where key-value pairs are frequently added or deleted, Map may perform better than Object.

H2Methods

H3has()

The has() method of Map instances returns a boolean indicating whether an element with the specified key exists in this map or not.

jsconst map1 = new Map(); map1.set('bar', 'foo'); console.log(map1.has('bar')); // Expected output: true console.log(map1.has('baz')); // Expected output: false

H3values()

jsconst map1 = new Map(); map1.set('0', 'foo'); map1.set(1, 'bar'); const iterator1 = map1.values(); console.log(iterator1.next().value); // Expected output: "foo" console.log(iterator1.next().value); // Expected output: "bar" console.log([...iterator1]); // Expected output: ["foo", "bar"]

H1Built-in Objects

H2parseInt()

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

jsconsole.log(parseInt("101", 2)); // 5 console.log(parseInt("123", 10)); // 123 (explicitly specify base-10) console.log(parseInt(" 123 ")); // 123 (whitespace is ignored) console.log(parseInt("077")); // 77 (leading zeros are ignored) console.log(parseInt("1.9")); // 1 (decimal part is truncated) console.log(parseInt("ff", 16)); // 255 (lower-case hexadecimal) console.log(parseInt("0xFF", 16)); // 255 (upper-case hexadecimal with "0x" prefix) console.log(parseInt("xyz")); // NaN (input can't be converted to an integer)

H1Document

H2Methods

H3querySelector()

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");

H3querySelectorAll()

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.

例如:

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

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

H1Element

H2Properties

H3innerHTML

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

H4get 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;

H4set HTML

element.innerHTML = contents;

H3innerText

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

H4get Text

let text = element.innerText;

H4set Text

element.innerText = text

H3textContent

DITTO

textContentinnerText 区别是:

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

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

H1Window

H2Properties

H3scrollY

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

Syntax: window.scrollY

H3scrollX

DITTO

H3innerHeight

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.

H3innerwidth

DITTO

H3localStorage

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.)

H4setItem()

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

jsconst catStr = JSON.stringify(cat); localStorage.setItem("cat", catStr);

Note:

value must be a string, so if you have a 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.

H4getItem()

The syntax for reading the localStorage item is as follows:

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

H4removeItem()

The syntax for removing the localStorage item is as follows:

localStorage.removeItem('key');

H4clear()

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

localStorage.clear();

H3sessionStorage

同上

H2Methods

H3setInterval()

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.

jsconst myInterval = setInterval(() => { const date = new Date(); document.getElementById("demo").innerHTML = date.toLocaleTimeString(); }, 1000); clearInterval(myInterval);

H3setTimeout()

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.

jsconst myTimeout = setTimeout(myGreeting, 5000); clearTimeout(myTimeout);

H3scrollTo()

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

例如:

jselement.scrollTo(0, 1000); // or element.scrollTo({ top: 100, left: 100, behavior: "smooth", });

H1Expressions & Operators

H2in & delete

jsconst car = { make: "Honda", model: "Accord", year: 1998 }; console.log("make" in car); // Expected output: true delete car.make; if ("make" in car === false) { car.make = "Suzuki"; } console.log(car.make); // Expected output: "Suzuki"

H1Web APIs

H2FormData

Note: formData is a type of Map.

Methods:

FormData.get()

FormData.forEach()

jsxexport default function App() { const onSubmit = (e) => { e.preventDefault(); const formData = new FormData(e.target); console.log(formData.get("a")); console.log(Object.fromEntries(formData.entries())); // {a:"", b:"", c:""} }; return ( <main> <form onSubmit={onSubmit}> <input type="text" name="a" /> <input type="text" name="b" /> <input type="text" name="c" /> <button>Button</button> </form> </main> ); }

Prev

Next

Related Posts