JavaScript基础笔记
我很早学过,只是当时没有系统记录笔记,导致过一段时就容易忘记很多东西。本笔记主要参考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 | const birthday = new Date('August 9, 2000 00:00:00'); |
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 | const birthday = new Date('August 9, 2000 00:00:00'); |
getDate()
The getDate()
method returns the day of the month for the specified date according to local time.(几号)
1 | const birthday = new Date('August 9, 2000 00:00:00'); |
getDay()
The getDay()
method returns the day of the week for the specified date according to local time, where 0 represents Sunday. (周几)
1 | const birthday = new Date('August 9, 2000 00:00:00'); |
getHours()
The getHours()
method returns the hour for the specified date, according to local time.
1 | const birthday = new Date('August 9, 2000 00:00:00'); |
getMinutes()
The getMinutes()
method returns the minutes on the specified date according to local time.
1 | const birthday = new Date('August 9, 2000 00:00:00'); |
getSeconds()
The getSeconds()
method returns the seconds in the specified date according to local time.
1 | const birthday = new Date('August 9, 2000 00:00:00'); |
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 | const DOB = new Date('2000/08/09 00:00:00'); |
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 | console.log(Math.floor(5.95)); // Expected output: 5 |
ceil()
The Math.ceil()
static method always rounds up and returns the smaller integer greater than or equal to a given number.
1 | console.log(Math.ceil(.95)); // Expected output: 1 |
round()
The Math.round()
static method returns the value of a number rounded to the nearest integer.
1 | console.log(Math.round(0.9)); // Expected output: 1 |
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 | const clothing = ["shoes", "shirts", "socks", "sweaters"]; |
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 | const array1 = ['a', 'b', 'c']; |
其实扩展语法(spread syntax)更好:
1 | const arr1 = [1, 2, 3]; |
使用扩展语法可以使代码更简洁易读,而且性能也比使用
concat()
方法更好
forEach()
The forEach()
method executes a provided function once for each array element.
例如:
1 | const array1 = ['a', 'b', '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 | const array1 = [1, 30, 39, 29, 10, 13]; |
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 | const array = [1, 2, 3, 4, 5]; |
includes()
includes()
方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true
,否则返回 false
。
1 | const array1 = [1, 2, 3]; |
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 | const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; |
isArray()
The Array.isArray()
static method determines whether the passed value is an Array
.
1 | console.log(Array.isArray([1, 3, 5])); // Expected output: true |
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 | const words = ["spray", "limit", "elite", "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 | const array1 = [5, 12, 8, 130, 44]; |
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 | const array1 = [8, 9, 666, 666, 999]; |
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 | const elements = ['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 | const animals = ['pigs', 'goats', 'sheep']; |
reduce()
reduce()
方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
1 | const array1 = [1, 2, 3, 4]; |
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
reverse()
reverse()
方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
1 | const array1 = ['one', 'two', 'three']; |
slice()
slice()
方法返回一个新的数组对象,这一对象是一个由 begin
和 end
决定的原数组的浅拷贝(包括 begin
,不包括end
)。原始数组不会被改变。(左闭右开)
1 | const animals = ['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 | const months = ['Jan', 'March', 'April', 'June']; |
Syntax
1 | splice(start) |
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 | const array1 = [1, 2, 3]; |
Object
Methods
keys()
Object.keys()
方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和正常循环遍历该对象时返回的顺序一致。
1 | const object1 = { |
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 | String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
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 | const str = "The quick brown fox jumps over the lazy dog."; |
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 | const anyString = "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 | const str = "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 | startsWith(searchString); |
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 | const str = "To be, or not to be, that is the question."; |
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 | const str1 = "Cats are the best!"; |
toLowerCase()
The toLowerCase()
method returns the calling string value converted to lower case.
1 | const sentence = '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 | const greeting = ' 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 | const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; |
replace()
replace()
根据规则将字符串中某部分替换成新内容,并返回新字符串。
语法:replace(substr|regexp, newSubStr|function)
第一个参数是要被替换的老字符串,或者正则表达式,记得用斜线 / 围上,后面可以加 g 或者 i 或者 gi,代表全局匹配、忽略大小写。
第二个参数是新字符串,或者函数,该函数返回着将替换掉第一个参数匹配到对结果。
1 | const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; |
Number
Methods
toLocaleString()
toLocaleString()
方法返回这个数字在特定语言环境下的表示字符串
Syntax: toLocaleString([locales, options])
locales
和 options
参数让应用程序可以指定要进行格式转换的语言,并且定制函数的行为。
1 | const number = 8090; |
常用的就是将数字每三个数位用逗号分隔开
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 | const matches1 = document.querySelectorAll("p"); |
后者是返回所有满足 .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
但 textContent
和 innerText
区别是:
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 | const catStr = JSON.stringify(cat); |
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 | const myInterval = setInterval(() => { |
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 | const myTimeout = setTimeout(myGreeting, 5000); |
scrollTo()
The scrollTo()
method scrolls the document to specified coordinates(坐标).
Syntax: scrollTo(x-coord, y-coord)
x-coord
是文档中的横轴坐标。y-coord
是文档中的纵轴坐标。
Syntax: scrollTo(options)
options
是一个包含三个属性的对象:
top
等同于y-coord
left
等同于x-coord
behavior
类型 String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值 auto
例如:
1 | element.scrollTo(0, 1000); |
☕欲知后事如何,
且听下回分解🍵