一、对象键值对数组转换
在数据处理场景中,将对象转换为键值对数组是常见需求。传统方法需手动遍历对象属性,而现代JavaScript提供了更优雅的解决方案:
const obj = { name: 'Alice', age: 25, city: 'Beijing' };const keyValuePairs = Object.keys(obj).map(key => [key, obj[key]]);// 输出: [['name', 'Alice'], ['age', 25], ['city', 'Beijing']]
优化点:
- 使用
Object.entries()可进一步简化代码:const entries = Object.entries(obj); // 直接生成键值对数组
- 若需特定格式转换,可在
map回调中自定义逻辑,如将数值转为字符串:const formattedPairs = Object.keys(obj).map(key => ({key,value: typeof obj[key] === 'number' ? String(obj[key]) : obj[key]}));
二、数组虚假值过滤
虚假值(falsy values)包括false、0、""、null、undefined和NaN。过滤时需注意:
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN, 4];const truthyValues = mixedArray.filter(Boolean); // [1, 2, 3, 4]
特殊场景处理:
若需保留0或空字符串,需自定义过滤函数:
const customFilter = arr => arr.filter(item =>item !== null && item !== undefined && !isNaN(item));
三、日期差值计算
计算两个日期的天数差需考虑时区问题,推荐使用时间戳:
function getDayDifference(startDate, endDate) {const msPerDay = 24 * 60 * 60 * 1000;return Math.round((endDate - startDate) / msPerDay);}// 使用示例const start = new Date('2023-01-01');const end = new Date('2023-01-10');console.log(getDayDifference(start, end)); // 9
进阶技巧:
使用Date.UTC()可避免本地时区影响:
function getUTCDateDiff(d1, d2) {return Math.floor((Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate()) -Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate())) /(1000 * 60 * 60 * 24));}
四、数组差异比较
对于大型数组,使用Set可显著提升性能:
function findDifference(arr1, arr2) {const set2 = new Set(arr2);return arr1.filter(item => !set2.has(item));}// 双向差异比较function getArrayDiff(a, b) {return {onlyInA: a.filter(x => !new Set(b).has(x)),onlyInB: b.filter(x => !new Set(a).has(x))};}
性能对比:
- 传统
includes()方法时间复杂度为O(n²) Set方案时间复杂度降至O(n)
五、数组转CSV格式
处理包含特殊字符的数据时需注意转义:
function arrayToCSV(data, delimiter = ',') {return data.map(row =>row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(delimiter)).join('\n');}// 使用示例const data = [['Name', 'Age'], ['John, Doe', 30], ['Jane "Smith"', 25]];console.log(arrayToCSV(data));
输出结果:
"Name","Age""John, Doe","30""Jane ""Smith""","25"
六、数组元素计数
使用reduce实现多功能计数器:
function countItems(arr, target) {return arr.reduce((acc, curr) =>curr === target ? acc + 1 : acc, 0);}// 扩展:统计所有元素出现次数function countAllItems(arr) {return arr.reduce((acc, curr) => {acc[curr] = (acc[curr] || 0) + 1;return acc;}, {});}
七、字符串首字母大写
处理多单词字符串时的优化方案:
function capitalizeFirstLetter(str) {return str.toLowerCase().replace(/^[a-z]|\s[a-z]/g,match => match.toUpperCase());}// 使用示例console.log(capitalizeFirstLetter('hello world')); // "Hello World"
八、数组最大值查找
多维度最大值查找方案:
// 一维数组const maxNum = Math.max(...[1, 5, 3]); // 5// 二维数组const matrix = [[1, 2], [3, 4]];const maxInMatrix = Math.max(...matrix.flat()); // 4// 对象数组const users = [{age: 25}, {age: 30}];const maxAge = Math.max(...users.map(u => u.age)); // 30
九、数组平均值计算
处理空数组时的安全方案:
function safeAverage(arr) {if (arr.length === 0) return 0;return arr.reduce((sum, curr) => sum + curr, 0) / arr.length;}// 加权平均值计算function weightedAverage(values, weights) {const sum = values.reduce((acc, val, i) => acc + val * weights[i], 0);return sum / weights.reduce((acc, w) => acc + w, 0);}
十、JSON字符串验证
增强版验证函数,支持额外检查:
function isValidJSON(str, allowEmpty = false) {if (allowEmpty && str.trim() === '') return true;try {const obj = JSON.parse(str);// 可添加额外验证逻辑,如检查特定字段return typeof obj === 'object' && obj !== null;} catch (e) {return false;}}// 使用示例console.log(isValidJSON('{"name": "Alice"}')); // trueconsole.log(isValidJSON('invalid json')); // false
总结:
本文提供的10个解决方案覆盖了JavaScript开发中的核心场景,每个方案都包含基础实现和进阶优化。开发者可根据实际需求选择合适的方法,特别注意边界条件处理和性能优化。对于企业级应用,建议将常用功能封装为工具库,配合单元测试确保代码质量。在云开发环境中,这些技巧同样适用于前后端数据处理的各个环节,能有效提升开发效率和系统稳定性。