ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

JavaScript 常用 API 语法速查

2026/8/9 3:44:44 拓冰建站 浏览量
JavaScript 常用 API 语法速查 1. 数组操作1.1 创建与初始化// 字面量创建constarr1[1,2,3]constarr2newArray(5)// 创建长度为5的空数组constarr3Array.from(hello)// [h, e, l, l, o]1.2 常用方法方法功能示例push()末尾添加元素arr.push(4)pop()删除末尾元素arr.pop()unshift()开头添加元素arr.unshift(0)shift()删除开头元素arr.shift()forEach()遍历数组arr.forEach(item console.log(item))map()映射新数组arr.map(item item * 2)filter()过滤数组arr.filter(item item 2)find()查找元素arr.find(item item 3)indexOf()查找索引arr.indexOf(3)sort()排序arr.sort((a, b) a - b)reverse()反转arr.reverse()2. 字符串操作类别方法功能示例获取与查找charAt()获取指定位置字符str.charAt(1)→eindexOf()查找子串位置str.indexOf(World)→6includes()是否包含子串str.includes(Hello)→true截取与分割split()分割为数组str.split( )→[Hello, World]修改toUpperCase()转为大写str.toUpperCase()→HELLO WORLDtoLowerCase()转为小写str.toLowerCase()→hello worldreplace()替换子串str.replace(World, JavaScript)trim()去除首尾空格str.trim()3. 对象操作constobj{name:John,age:25}// 访问与修改obj.name// Johnobj[age]26;// 遍历Object.keys(obj)// [name, age]Object.values(obj)// [John, 26]Object.entries(obj)// [[name, John], [age, 26]]// 合并与复制constnewObjObject.assign({},obj,{city:NYC})constspreadObj{...obj,city:NYC}4. 日期处理4.1 创建与获取constnownewDate()// 获取时间now.getFullYear()// 2026now.getMonth()// 0-11now.getDate()// 1-31now.getHours()// 0-23now.getMinutes()// 0-59now.getSeconds()// 0-59// 格式化now.toLocaleDateString()// 2026/8/84.2 常用日期方法方法说明返回值范围getFullYear()年份4位数字getMonth()月份0-1101月getDate()日期1-31getDay()星期0-60周日getHours()小时0-23getMinutes()分钟0-59getSeconds()秒0-59getTime()时间戳毫秒数toLocaleDateString()本地日期本地格式字符串5. 数字与数学类别方法/属性功能示例转换parseInt()字符串转整数parseInt(123)→123parseFloat()字符串转浮点数parseFloat(3.14)→3.14Number()转为数字Number(42)→42数学运算Math.abs()绝对值Math.abs(-5)→5Math.round()四舍五入Math.round(3.7)→4Math.floor()向下取整Math.floor(3.7)→3Math.ceil()向上取整Math.ceil(3.2)→4Math.max()最大值Math.max(1, 5, 3)→5Math.min()最小值Math.min(1, 5, 3)→1Math.random()随机数0-1之间的随机数6. 浏览器 APIWeb API6.1 本地存储// localStoragelocalStorage.setItem(key,value)constvaluelocalStorage.getItem(key)localStorage.removeItem(key)localStorage.clear()6.2 定时器// 延时执行setTimeout((){console.log(1秒后执行)},1000)// 间隔执行consttimersetInterval((){console.log(每2秒执行一次)},2000)// 清除定时器clearTimeout(timerId)clearInterval(timer)6.3 获取DOM元素// 选择器document.getElementById(id)document.querySelector(.class)document.querySelectorAll(div)// 操作element.textContent新内容element.innerHTMLspanHTML内容/spanelement.style.colorredelement.classList.add(active)7. JSON 处理constobj{name:Alice,age:30}// 序列化constjsJSON.stringify(obj)// {name:Alice,age:30}// 反序列化constObjJSON.parse(js)// {name: Alice, age: 30}8. 实用技巧typeof42// numbertypeofhello// stringtypeoftrue// booleantypeofundefined// undefinedtypeofnull// object注意这个特例Array.isArray([])// trueisNaN(abc)// trueNumber.isFinite(42);// true9. 简写语法// 属性简写constnameJohnconstobj{name}// {name: John}// 方法简写constobj{sayHello(){console.log(Hello)}}// 模板字符串constgreetingHello,${name}!