好用的JavaScript技巧(持续更新)

60 阅读1分钟

超大数相加

function addBig(a, b) {
  let temp = 0;
  let res = "";
  a = a.split("");
  b = b.split("");
  while (a.length || b.length || temp) {
    temp += ~~a.pop() + ~~b.pop();
    res = (temp % 10) + res;
    temp = temp > 9;
  }
  console.log(res);
  return res.replace(/^0+/g, "");
}

注:ab均需要为字符串

校验数据类型

export const typeOf = function(obj) {  
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()  
}

reduce

使用说明:

arr.reduce((accumulator, currentValue, index, array)=>{},initialValue)
  • accumulator:累积器,即上一次回调函数执行的返回值。
  • currentValue:当前元素的值。
  • index:当前元素的下标。
  • array:原始数组。
  • initialValue:是可选的,表示累积器的初始值。若不设置,则默认值为arr第一项
  • 从数组的第二个元素开始,依次对数组中的每个元素执行回调函数。
  • 回调函数的返回值作为下一次回调函数执行时的累积器的值。
  • 对数组中的每个元素执行完回调函数后,reduce 函数返回最后一次回调函数的返回值,即最终的累积值。

1、reduce去重

let obj = [1, 2, 3, 123, 123, 23, 12, 3, 12, 34, 5, 2, 1, 2];
let newArr = obj.reduce((cur, pre, index, i) => {
  if (cur.indexOf(pre) === -1) {
    cur.push(pre);
  }
  return cur;
}, []);
console.log(newArr); // [1, 2, 3, 123, 23, 12, 34, 5]

2、reduce 计算数组中每个元素出现的次数

const fruits = ['apple''banana''apple''orange''banana''apple'];  
const count = fruits.reduce((accumulator, currentValue) => {  
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;  
  return accumulator;  
}, {});  
console.log(count); // Output: { apple: 3, banana: 2, orange: 1 }

key-value 键值对转换

简单的转换

const getStat = (key) => {
  let obj = {
    a: "我是a",
    b: "我是b",
    c: "我是c",
  };
  return obj[key];
};
console.log(getStat("a")); // "我是a"

相对复杂转换

let arr = [
  { id: 1, value: "值1" },
  { id: 2, value: "值2" },
  { id: 3, value: "值3" },
];
const getStat = (arr, key) => {
  let index = arr.findIndex((item) => item.id === key);
  if (index === -1) {
    return "";
  } else {
    return arr[index].value;
  }
};
console.log(getStat(arr, 1)); // "值1"
console.log(getStat(arr, 4)); // ""