前端技术

JavaScript 常用方法与属性

数据转换

parseInt()

解析一个字符串并返回指定基数的十进制整数

parseInt(string, radix)

parseFloat()

Boolean()

JSON.parse()

将文本字符串转换为 JSON 数据

字符串

split()

将字符串按照制定的符号进行分割

str.split([separator[, limit]])

// 以空格进行分割
let str = 'PUJI Design'
str.split(' ') // ['PUJI', 'Design']

trim()

从一个字符串的两端删除空白字符,不影响原先的字符串本身,将返回一个新的字符串。

includes()

是否包含其中的字符串

${}

可以直接在模版字符串(反引号)中调用变量

let name = 'PUJI'
console.log(`${name} Design`)

toUpperCase() / toLowerCase()

将字符串转换为全大写 / 小写形式

JSON.parse()

将字符串转换为 JSON 对象

JSON.stringify()

将 JSON 对象转换为字符串

获取外观

getComputedStyle()

获取指定元素中的样式属性

window.getComputedStyle(element, [pseudoElt])

// 获取样式表中的宽度属性
window.getComputedStyle(div).width

getBoundingClientRect()

返回元素的大小及其相对于视口的位置。如果是标准盒子模型,元素的尺寸等于 width/height + padding + border-width 的总和。如果 box-sizing: border-box,元素的的尺寸等于 width/height。

节点操作

createElement()

insertAdjacentHTML

firstElementChild / lastElementChild

元素操作

检测属性

arr = {name: 'PUJI', work: 'Design'};
console.log(arr.hasOwnProperty('url')); // 检测自身是否有此属性
console.log('url' in arr); // 检测自身以及父级对象(原型)是否有此属性

属性操作

style

style.cssText

classList

计算

Math.PI

表示一个圆的周长与直径的比例,约为 3.14159

Math.max() / Math.min()

返回给定数值中最大/小的数。如果任一参数不能转换为数值,则返回NaN。

Math.min([value1[,value2, ...]]) 

// 示例
console.log(Math.max(1, 3, 2)) // 3
console.log(Math.max(-1, -3, -2)) // -1
const array1 = [1, 3, 2]
console.log(Math.max(...array1)) // 3

Math.round()

返回数字四舍五入的整数。

Math.round(x)

x = Math.round(20.49);   //20
x = Math.round(20.5);    //21
x = Math.round(-20.5);   //-20
x = Math.round(-20.51); //-21

Math.ceil()

向上取整

Math.ceil(x)

Math.floor()

向下取整

Math.floor(x) 

Math.abs()

返回指定数字 “x“ 的绝对值。

Math.abs(x)

// 示例
Math.abs('-1') // 1
Math.abs(-2) // 2
Math.abs(null) // 0
Math.abs("string") // NaN
Math.abs() // NaN

Math.random()

返回一个浮点数,  从0 (包括0) 往上,但是不包括1 (排除1) ,不能被选择或重置。

Math.random()

toFixed()

使用定点表示法来格式化一个数值。

numObj.toFixed(digits)

监听

IntersectionObserver

监听元素是否与视窗可视区域交叉,及指是否显示在视窗的可视区域。

https://www.jb51.net/article/171944.htm

判断元素是否显示案例:

https://www.youtube.com/watch?v=wDnUtY5KcOc

数组操作

map()

filter()

concat()

用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

动画

setInterval()

其他

hasOwnProperty()

defineProperty()

setPrototypeOf()

createDocumentFragment()

cloneNode()

appendChild()

insertBefore()

call()

apply()

bind()

push() / pop()

sort()

indexOf() / lastIndexOf()

事件

其他

assign()

PUJI Design 朴及设计 (c) 2024. 沪ICP备17052229号