As Javascript becomes more popular, it can be used in more and more scenarios, not just front ends, but back ends, hybrid applications, embedded devices, etc., hence the term big front ends. Modern front-end development has a large number of frameworks and code bases to help implement a variety of complex requirements, leading many people to think that front-end development is simple, such as cutting pages, organizing frames, making web pages, and so on. A front-end engineer who needs to improve his or her skills will have to go through native code writing, and snippets of code will increase your understanding of the basic syntax of Javascript as well as your coding level.

1. localStorage

LocalStorage is one of the local persistent storage methods in HTML5, and also one of the commonly used localStorage solutions in front-end projects. As long as the user does not delete the data stored in localStorage, it is permanently stored. The stored value can only be of string type and cannot be accessed across browsers or domain names. The storage size is generally about 5M. The following code snippet is to store, get, and clear localStorage data.

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; }}; / * * * remove localStorage * / const clear () = = > {window. LocalStorage. SetItem (localKey, ""); }; return { save, get, clear, }; }; const storageAuth = useStorage(); const loginInfo = { username: "hballard", age: 30, }; storageAuth.save(loginInfo); console.log(storageAuth.get());Copy the code

When executed in the browser, the result is as follows:

2. average

This code snippet returns the average of two or more values. This code also shows how to define mutable parameters.

const average = (... nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; const ages = [30, 24, 28, 32]; console.log(average(... ages)); // 28.5 console.log(average(30, 24, 28, 32)); / / 28.5Copy the code

3. averageBy

This code snippet computes the average value of the Map array according to the specified key, or it can be given an iteration function.

const averageBy = (array, fn) => array .map(typeof fn === "function" ? fn : (val) => val[fn]) .reduce((acc, val) => acc + val, 0) / array.length; const users = [ { name: "hballard", age: 30 }, { name: "sguzman", age: 24 }, { name: "jrowe", age: 28 }, { name: "plowe", age: 32 }, ]; const average1 = averageBy(users, (item) => item.age); const average2 = averageBy(users, "age"); console.log(average1); / / 28.5 console. The log (average2); / / 28.5Copy the code

4. all

This code snippet validates the elements of a collection, returning true if all elements are validated, false otherwise.

const all = (array, fn) => array.every(fn);

const ages = [30, 24, 28, 32];
const result1 = all(ages, (item) => item < 40);
const result2 = all(ages, (item) => item > 30);

console.log(result1); // true
console.log(result2); // false
Copy the code

5. arrayToCSV

This code snippet converts an element without commas or double quotes to a comma-delimited string in CSV file format.

const arrayToCSV = (array, delimiter = ",") => array .map((item) => item.map((value) => `"${value}"`).join(delimiter)) .join("\n"); const users = [ { name: "hballard", age: 30 }, { name: "sguzman", age: 24 }, { name: "jrowe", age: 28 }, { name: "plowe", age: 32 }, ]; const arrayUsers = users.map((item) => Object.values(item)); console.log(arrayUsers); // [ // [ 'hballard', 30 ], // [ 'sguzman', 24 ], // [ 'jrowe', 28 ], // [ 'plowe', 32 ] // ] const strCsv1 = arrayToCSV(arrayUsers); const strCsv2 = arrayToCSV(arrayUsers, ";" ); console.log(strCsv1); // "hballard","30" // "sguzman","24" // "jrowe","28" // "plowe","32" console.log(strCsv2); // "hballard";" 30" // "sguzman";" 24" // "jrowe";" 28" // "plowe";" 32"Copy the code

6. arrayToHtmlList

This code snippet converts array elements to

  • tags or specified HTML tags, primarily used to convert data to interface HTML format.
  • const arrayToHtmlList = (array, tag = "li") => array.map((item) => `<${tag}>${item}</${tag}>`).join(""); Console. log(arrayToHtmlList([" # 1 ", "# 2 "])); The first in the / / < li > < / li > < li > the second < / li > console. The log (arrayToHtmlList ([" first ", "the second"], "p")); // <p> </p><p> </p>Copy the code

    7. allEqual

    This code snippet determines whether all elements of a one-dimensional array are all equal.

    const allEqual = (array) => array.every((val) => val === array[0]);
    
    console.log(allEqual([1, 1, 1, "1"])); // false
    console.log(allEqual([1, 1, 1, 2])); // false
    console.log(allEqual([1, 1, 1, 1])); // true
    console.log(allEqual(["a", "a", "a"])); // true
    Copy the code

    8. countOccurrences

    This code snippet calculates the number of repetitions of a value in an array.

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

    9. capitalizeWord

    This code snippet capitalizes the first letter of each word in a given string.

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

    10. byteSize

    This code snippet calculates the length of a given string in bytes. This code snippet is valid in advanced browsers only.

    const byteSize = (string) => new Blob([string]).size; console.log(byteSize("hello")); // 5 console.log(byteSize(" China ")); / / 6Copy the code