收集的一些常用的 JavaScript 代码片段

# 将给定字符串中每个单词的首字母转为大写

const capitalizeWord = (string) =>
  string.replace(/\b[a-z]/g, (char) => char.toUpperCase());
console.log(capitalizeWord("hello world in javascript")); // Hello World In Javascript

# 计算给定字符串的字节长度

const byteSize = (string) => new Blob([string]).size;
console.log(byteSize("vivy")); // 4
console.log(byteSize("潮鸣")); // 6

# 将数组元素转换为指定的 HTML 元素,主要用于将数据转换为界面 HTML 格式

const arrayToHtmlList = (array, tag = "li") =>
  array.map((item) => `<${tag}>${item}</${tag}>`).join("");
console.log(arrayToHtmlList(["第一条", "第二条"])); // <li > 第一条 & lt;/li><li > 第二条 & lt;/li>
console.log(arrayToHtmlList(["第一条", "第二条"], "p")); // <p > 第一条 & lt;/p><p > 第二条 & lt;/p>

# 多个数值求平均值

const average = (...nums) =>
  nums.reduce((acc, val) => acc + val, 0) / nums.length;
const ages = [23, 56, 15, 28];
// 此代码也展示了函数如何传递不定参数(使用 ES6 扩展运算符)
console.log(average(...ages)); // 30.5
console.log(average(23, 56, 15, 28)); // 30.5

# 计算 map 数组按照指定 key 的平均值,也可以给定一个迭代函数

const averageBy = (array, fn) =>
  array.map(typeof fn === "function" ? fn : (val) => val[fn]).reduce((acc, val) => acc + val, 0) / array.length;
const users = [
  { name: "saber", size: 23 },
  { name: "vivy", size: 56 },
  { name: "tico", size: 15 },
  { name: "k423", size: 28 },
];
const average1 = averageBy(users, (item) => item.size);
const average2 = averageBy(users, "size");
console.log(average1); // 30.5
console.log(average2); // 30.5

# 封装 localStorage

const useStorage = (storageKey = "authorization") => {
  const localKey = `devpoint.local.${storageKey}`;
  const save = (data) => {
    window.localStorage.setItem(localKey, JSON.stringify(data));
  };
  const get = () => {
    const localData = window.localStorage.getItem(localKey);
    if (localData && localData !== "") {
      return JSON.parse(localData);
    } else {
      return false;
    }
  };
  const clear = () => {
    window.localStorage.setItem(localKey, "");
  };
  return { save, get, clear };
};
const storageAuth = useStorage();
const loginInfo = {
  username: "vivy",
  age: 18,
};
storageAuth.save(loginInfo);
console.log(storageAuth.get());

# 计算数组中某个值的重复次数

const countOccurrences = (array, value) =>
  array.reduce(
    (accumulator, current) =>
      current === value ? accumulator + 1 : accumulator,
    0
  );
console.log(countOccurrences([..."vivy"], "v")); // 2
console.log(countOccurrences([1, 3, 3, 4, 3, 3, 2, 3], 3)); // 5

# 检查值是否属于某个数据类型

const isCheck = (type, val) =>
  ![undefined, null].includes(val) && val.constructor === type;
console.log(isCheck(Array, ["a"])); // true
console.log(isCheck(Object, {})); // true
console.log(isCheck(ArrayBuffer, new ArrayBuffer())); // true
console.log(isCheck(Boolean, new Boolean(true))); // true
console.log(isCheck(RegExp, /./g)); // true
console.log(isCheck(Number, 0)); // true

# 遍历对象的每个属性,并分别为每个属性迭代一个回调

const forObject = (obj, callback) =>
  Object.keys(obj).forEach((key) => callback(obj[key], key, obj));
const testObj = {
  word: "信じる心があなたの魔法〜",
  author: "篝敦子",
};
forObject(testObj, (val, key) => {
  console.log(`${key}:${val}`);
});
//word: 信じる心があなたの魔法〜
//author: 篝敦子

# 通过键值查找对象,返回满足给定函数的第一个 key

const findKey = (obj, fn) =>
  Object.keys(obj).find((key) => fn(obj[key], key, obj));
const testObj = {
  vivy: { age: 17 },
  k423: { age: 18 },
  saber: { age: 19 },
};
console.log(findKey(testObj, (item) => item.age > 18)); // saber

# 将一组数据按照指定的 key 的进行分组,并按照分组进行归类

const groupBy = (obj, key) => {
    const values =
        obj instanceof Map || obj instanceof Set
            ? Array.from(obj.values())
            : Object.values(obj);
    return values.reduce((acc, value) => {
        const groupKey = value[key];
        if (!Array.isArray(acc[groupKey])) {
            acc[groupKey] = [value];
        } else {
            acc[groupKey].push(value);
        }
        return acc;
    }, {});
};
const arrayRoles = [
    { title: "Mieruko-chan", category: "xxx" },
    { title: "Vladilena Mirizé", category: "xxx" },
    { title: "Nakano Azusa", category: "xxx" },
    { title: "Shirahane Suou", category: "yyy" },
    { title: "Mio Akiyama", category: "yyy" },
];
console.log(groupBy(arrayRoles, "category"));
/*
{
  'xxx': [
    { title: 'Mieruko-chan', category: 'xxx' },
    { title: 'Vladilena Mirizé', category: 'xxx' },
    { title: 'Nakano Azusa', category: 'xxx' }
  ],
  'yyy': [
    { title: 'Shirahane Suou', category: 'yyy' },
    { title: 'Mio Akiyama', category: 'yyy' }
  ]
}
*/

# Reference

碎片时间学习 Javascript 代码

更新于