javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > 前端js内置函数

前端开发常用的js内置函数总结大全(查漏补缺)

作者:~欲买桂花同载酒~

javascript是前端必要掌握的真正算得上是编程语言的语言,学会灵活运用javascript,将对以后学习工作有非常大的帮助,这篇文章主要介绍了前端开发常用的js内置函数总结大全的相关资料,需要的朋友可以参考下

一、数组 (Array) 相关内置函数

数组是前端处理数据最常用的结构,这些函数几乎每天都会用到:

1. forEach () - 遍历数组

const fruits = ['苹果', '香蕉', '橙子'];
// 遍历并打印每个水果
fruits.forEach((fruit, index) => {
  console.log(`第${index+1}个水果:${fruit}`);
});
// 输出:
// 第1个水果:苹果
// 第2个水果:香蕉
// 第3个水果:橙子

2. map () - 数组映射(返回新数组)

const nums = [1, 2, 3];
// 将每个数字翻倍,返回新数组
const doubleNums = nums.map(num => num * 2);
console.log(doubleNums); // [2,4,6]
console.log(nums); // [1,2,3](原数组不变)

3. filter () - 数组过滤(返回新数组)

const scores = [85, 60, 90, 55];
// 筛选出及格(≥60)的分数
const passScores = scores.filter(score => score >= 60);
console.log(passScores); // [85,90,60]

4. find () /findIndex () - 查找数组元素

const targetItem = array.find((item, index, arr) => { return 条件 });
const targetIndex = array.findIndex((item, index, arr) => { return 条件 });
const users = [
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' }
];
// 查找id为2的用户
const targetUser = users.find(user => user.id === 2);
console.log(targetUser); // { id: 2, name: '李四' }
// 查找id为3的用户的索引
const targetIdx = users.findIndex(user => user.id === 3);
console.log(targetIdx); // 2

5. reduce () - 数组归并(聚合计算)

// 1. 数组求和
const nums = [1, 2, 3, 4];
const sum = nums.reduce((prev, curr) => prev + curr, 0);
console.log(sum); // 10
// 2. 统计数组中元素出现次数
const fruits = ['苹果', '香蕉', '苹果', '橙子', '香蕉', '苹果'];
const countObj = fruits.reduce((prev, curr) => {
  prev[curr] = (prev[curr] || 0) + 1;
  return prev;
}, {});
console.log(countObj); // { 苹果: 3, 香蕉: 2, 橙子: 1 }

6. includes () - 判断数组是否包含某元素

const colors = ['red', 'green', 'blue'];
console.log(colors.includes('green')); // true
console.log(colors.includes('yellow')); // false

二、字符串 (String) 相关内置函数

前端处理文本(如用户输入、接口返回字符串)时必备:

1. trim () /trimStart () /trimEnd () - 去除空格

const inputStr = '  用户名  ';
const cleanStr = inputStr.trim();
console.log(cleanStr); // '用户名'(首尾空格被去除)

2. split () - 字符串分割为数组

const str = '苹果,香蕉,橙子';
const fruitArr = str.split(',');
console.log(fruitArr); // ['苹果','香蕉','橙子']
// 分割为单个字符
const charArr = 'hello'.split('');
console.log(charArr); // ['h','e','l','l','o']

3. indexOf () /lastIndexOf () - 查找字符串位置

const str = 'hello world';
console.log(str.indexOf('o')); // 4(第一个o的位置)
console.log(str.lastIndexOf('o')); // 7(最后一个o的位置)
console.log(str.indexOf('x')); // -1(不存在)

4. slice () - 截取字符串(不改变原字符串)

const str = '2026-03-01';
// 截取年份(前4位)
const year = str.slice(0, 4);
console.log(year); // '2026'
// 截取最后两位(日期)
const day = str.slice(-2);
console.log(day); // '01'

5. replace () /replaceAll () - 替换字符串

str.replace(searchValue, replaceValue);
str.replaceAll(searchValue, replaceValue);
const str = 'hello world, hello js';
// 替换第一个hello为hi
const newStr1 = str.replace('hello', 'hi');
console.log(newStr1); // 'hi world, hello js'
// 替换所有hello为hi
const newStr2 = str.replaceAll('hello', 'hi');
console.log(newStr2); // 'hi world, hi js'

三、对象 (Object) 相关内置函数

1. Object.keys() / Object.values() / Object.entries()

const keys = Object.keys(obj);
const values = Object.values(obj);
const entries = Object.entries(obj);
const user = { name: '张三', age: 20, gender: '男' };
console.log(Object.keys(user)); // ['name','age','gender']
console.log(Object.values(user)); // ['张三',20,'男']
console.log(Object.entries(user)); // [['name','张三'], ['age',20], ['gender','男']]

2. Object.assign () - 对象合并 / 拷贝

// 1. 合并对象
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const mergeObj = Object.assign({}, obj1, obj2);
console.log(mergeObj); // { a:1, b:2 }
// 2. 浅拷贝对象
const original = { name: '张三' };
const copy = Object.assign({}, original);
copy.name = '李四';
console.log(original.name); // '张三'(原对象不受影响)

四、其他高频内置函数

1. parseInt () /parseFloat () - 字符串转数字

parseInt(str, radix); // radix为进制(如10表示十进制)
parseFloat(str);
console.log(parseInt('123.45')); // 123
console.log(parseInt('10px')); // 10(自动忽略非数字部分)
console.log(parseFloat('123.45px')); // 123.45

2. JSON.parse () / JSON.stringify () - JSON 处理

const obj = JSON.parse(jsonStr);
const jsonStr = JSON.stringify(obj);
// 1. JSON字符串转对象
const jsonStr = '{"name":"张三","age":20}';
const user = JSON.parse(jsonStr);
console.log(user.name); // '张三'
// 2. 对象转JSON字符串(用于本地存储/接口传参)
const userObj = { name: '李四', age: 25 };
const str = JSON.stringify(userObj);
localStorage.setItem('user', str); // 存入本地存储

3. setTimeout () /setInterval () - 定时器

// 延迟1秒执行
const timer1 = setTimeout(() => {
  console.log('1秒后执行');
}, 1000);
// 每隔1秒执行一次
const timer2 = setInterval(() => {
  console.log('每隔1秒执行');
}, 1000);
// 清除定时器
clearTimeout(timer1);
clearInterval(timer2);

总结

  1. 数组函数forEach(遍历)、map(映射)、filter(筛选)、reduce(聚合)是处理列表数据的核心,几乎覆盖 80% 的数组操作场景;
  2. 字符串函数trim(去空格)、split(分割)、slice(截取)、replace(替换)是处理文本输入 / 输出的高频函数;
  3. 对象 / 通用函数Object.keys/values(遍历对象)、JSON.parse/stringify(JSON 处理)、parseInt(类型转换)是前端数据处理的基础,必须掌握。

到此这篇关于前端开发常用的js内置函数总结大全的文章就介绍到这了,更多相关前端js内置函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文