JavaScript开发必知:10个高频问题解决方案全解析

一、对象键值对数组转换

在数据处理场景中,将对象转换为键值对数组是常见需求。传统方法需手动遍历对象属性,而现代JavaScript提供了更优雅的解决方案:

  1. const obj = { name: 'Alice', age: 25, city: 'Beijing' };
  2. const keyValuePairs = Object.keys(obj).map(key => [key, obj[key]]);
  3. // 输出: [['name', 'Alice'], ['age', 25], ['city', 'Beijing']]

优化点

  1. 使用Object.entries()可进一步简化代码:
    1. const entries = Object.entries(obj); // 直接生成键值对数组
  2. 若需特定格式转换,可在map回调中自定义逻辑,如将数值转为字符串:
    1. const formattedPairs = Object.keys(obj).map(key => ({
    2. key,
    3. value: typeof obj[key] === 'number' ? String(obj[key]) : obj[key]
    4. }));

二、数组虚假值过滤

虚假值(falsy values)包括false0""nullundefinedNaN。过滤时需注意:

  1. const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN, 4];
  2. const truthyValues = mixedArray.filter(Boolean); // [1, 2, 3, 4]

特殊场景处理
若需保留0或空字符串,需自定义过滤函数:

  1. const customFilter = arr => arr.filter(item =>
  2. item !== null && item !== undefined && !isNaN(item)
  3. );

三、日期差值计算

计算两个日期的天数差需考虑时区问题,推荐使用时间戳:

  1. function getDayDifference(startDate, endDate) {
  2. const msPerDay = 24 * 60 * 60 * 1000;
  3. return Math.round((endDate - startDate) / msPerDay);
  4. }
  5. // 使用示例
  6. const start = new Date('2023-01-01');
  7. const end = new Date('2023-01-10');
  8. console.log(getDayDifference(start, end)); // 9

进阶技巧
使用Date.UTC()可避免本地时区影响:

  1. function getUTCDateDiff(d1, d2) {
  2. return Math.floor((Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate()) -
  3. Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate())) /
  4. (1000 * 60 * 60 * 24));
  5. }

四、数组差异比较

对于大型数组,使用Set可显著提升性能:

  1. function findDifference(arr1, arr2) {
  2. const set2 = new Set(arr2);
  3. return arr1.filter(item => !set2.has(item));
  4. }
  5. // 双向差异比较
  6. function getArrayDiff(a, b) {
  7. return {
  8. onlyInA: a.filter(x => !new Set(b).has(x)),
  9. onlyInB: b.filter(x => !new Set(a).has(x))
  10. };
  11. }

性能对比

  • 传统includes()方法时间复杂度为O(n²)
  • Set方案时间复杂度降至O(n)

五、数组转CSV格式

处理包含特殊字符的数据时需注意转义:

  1. function arrayToCSV(data, delimiter = ',') {
  2. return data.map(row =>
  3. row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(delimiter)
  4. ).join('\n');
  5. }
  6. // 使用示例
  7. const data = [['Name', 'Age'], ['John, Doe', 30], ['Jane "Smith"', 25]];
  8. console.log(arrayToCSV(data));

输出结果

  1. "Name","Age"
  2. "John, Doe","30"
  3. "Jane ""Smith""","25"

六、数组元素计数

使用reduce实现多功能计数器:

  1. function countItems(arr, target) {
  2. return arr.reduce((acc, curr) =>
  3. curr === target ? acc + 1 : acc, 0
  4. );
  5. }
  6. // 扩展:统计所有元素出现次数
  7. function countAllItems(arr) {
  8. return arr.reduce((acc, curr) => {
  9. acc[curr] = (acc[curr] || 0) + 1;
  10. return acc;
  11. }, {});
  12. }

七、字符串首字母大写

处理多单词字符串时的优化方案:

  1. function capitalizeFirstLetter(str) {
  2. return str.toLowerCase().replace(/^[a-z]|\s[a-z]/g,
  3. match => match.toUpperCase()
  4. );
  5. }
  6. // 使用示例
  7. console.log(capitalizeFirstLetter('hello world')); // "Hello World"

八、数组最大值查找

多维度最大值查找方案:

  1. // 一维数组
  2. const maxNum = Math.max(...[1, 5, 3]); // 5
  3. // 二维数组
  4. const matrix = [[1, 2], [3, 4]];
  5. const maxInMatrix = Math.max(...matrix.flat()); // 4
  6. // 对象数组
  7. const users = [{age: 25}, {age: 30}];
  8. const maxAge = Math.max(...users.map(u => u.age)); // 30

九、数组平均值计算

处理空数组时的安全方案:

  1. function safeAverage(arr) {
  2. if (arr.length === 0) return 0;
  3. return arr.reduce((sum, curr) => sum + curr, 0) / arr.length;
  4. }
  5. // 加权平均值计算
  6. function weightedAverage(values, weights) {
  7. const sum = values.reduce((acc, val, i) => acc + val * weights[i], 0);
  8. return sum / weights.reduce((acc, w) => acc + w, 0);
  9. }

十、JSON字符串验证

增强版验证函数,支持额外检查:

  1. function isValidJSON(str, allowEmpty = false) {
  2. if (allowEmpty && str.trim() === '') return true;
  3. try {
  4. const obj = JSON.parse(str);
  5. // 可添加额外验证逻辑,如检查特定字段
  6. return typeof obj === 'object' && obj !== null;
  7. } catch (e) {
  8. return false;
  9. }
  10. }
  11. // 使用示例
  12. console.log(isValidJSON('{"name": "Alice"}')); // true
  13. console.log(isValidJSON('invalid json')); // false

总结
本文提供的10个解决方案覆盖了JavaScript开发中的核心场景,每个方案都包含基础实现和进阶优化。开发者可根据实际需求选择合适的方法,特别注意边界条件处理和性能优化。对于企业级应用,建议将常用功能封装为工具库,配合单元测试确保代码质量。在云开发环境中,这些技巧同样适用于前后端数据处理的各个环节,能有效提升开发效率和系统稳定性。