This is the 25th day of my participation in the August Gwen Challenge. For details, see: August Gwen Challenge.

Every day to learn 10 practical JavaScript code snippets, deepen the understanding of JavaScript syntax, accumulation of code optimization experience, the sixth day, this code snippet includes random number generation, digital encryption, rounding, file extension, variable number conversion. If you find it helpful, check out the rest of the “Learning Javascript Code in Fragments” column, or leave a comment in the comments section.

1. Randoms

The code snippet below shows two ways to generate random numbers or get random elements from an array.

Generate a specified range of random numbers:

const getRandoms = (min, max) => {
    return Math.round(Math.random() * (max - min) + min);
};
console.log(getRandoms(10, 100));
Copy the code

Gets an element of the array randomly:

Const arrayCities = [" Beijing ", "Shanghai", "guangzhou", "shenzhen", "tianjin", "chongqing"]. const getRadmonItem = (array) => array[Math.floor(Math.random() * array.length)]; Console. log(" Random cities: ", getRadmonItem(arrayCities));Copy the code

2. Digital encryption

The following code snippet shows a simple encryption and decryption process using a number as a key, using XOR(^).

function Encrypt(secretNumber) { const _secretNumber = secretNumber; const encrypted = (encryptNumber) => encryptNumber ^ _secretNumber; const decrypted = (encryptedContent) => encryptedContent ^ _secretNumber; return { encrypted, decrypted, }; } const encryptHelper = new Encrypt(202108); const encryptNumber = 20210901; // encrypted const encrypted = encrypthelper.encrypted (encryptNumber); console.log(encrypted); // 20410793 // Const decrypted = encrypthelper.decrypted (encrypted); console.log(decrypted); / / 20210901Copy the code

3. Set mandatory parameters

When defining a function, you can use default values for expected arguments and friendly hints for required arguments. The following code snippet shows the definition of a required argument:

Const mandatory = (name) => {throw new Error(' call Error, must pass: ${name} '); }; Const printTitle = (title = mandatory(" title ")) => {console.log(' print article title: ${title} '); }; printTitle("JavaScript"); // Print the title of the article: JavaScript printTitle(); // Error: call Error, must pass argument: titleCopy the code

4. Create functions dynamically

A dynamically created function is a dynamic mechanism that dynamically generates functions based on strings. It is commonly used in rule validation of dynamic forms where the first parameter is a comma-separated list of arguments and the last parameter is the logical code of the function body:

const multiplyFn = new Function( "num1", "num2", "num3", "return num1*num2*num3" ); console.log(multiplyFn(1, 2, 3)); // 6 // ES6 const multiply = new Function( "... numbers", "return numbers.reduce((acc,current) => acc * current, 1)" ); console.log(multiply(1, 2, 3)); / / 6Copy the code

5. Empty the array

A simple way to empty an array is to change its length, as shown in the following code snippet:

Const arrayCities = [" Beijing ", "Shanghai", "guangzhou", "shenzhen", "tianjin", "chongqing"]. console.log(arrayCities); / / [' Beijing ', 'Shanghai', 'guangzhou', 'shenzhen', 'tianjin', 'chongqing'] / / empty arrayCities length = 0; console.log(arrayCities); / / []Copy the code

6. Round

The handling of the decimal point is a common operation with numbers. The main methods involved are toFixed and Math. The following code snippet shows the common methods.

The following code snippet shows common rounding methods and decimals added incorrectly due to JavaScript precision:

Const PI = 3.14159265359; console.log(pi.toFixed(3)); // 3.142 const sumFloat = 0.1 + 0.2; console.log(sumFloat); / / 0.30000000000000004 the console log (sumFloat toFixed (1)); / / 0.3Copy the code

Common rounding methods in Math include math.round () to the nearest integer, math.floor () to round down, and math.ceil () to round up. The closest approach to mathematical rounding is toFixed, as shown in the following code snippet:

Const PI = 3.14159265359; console.log(pi.toFixed(0)); // 3 console.log(Math.floor(pi)); // 3 console.log(Math.ceil(pi)); // 4 console.log(Math.round(pi)); // 3 const num2 = 3.5; console.log(num2.toFixed(0)); // 4 console.log(Math.floor(num2)); // 3 console.log(Math.ceil(num2)); // 4 console.log(Math.round(num2)); / / 4Copy the code

7. Object deconstruction of array items

Object deconstruction of array items is useful for parsing CSV data, as shown in the following code snippet:

Const csvAddressDetail = "Science park Building, North Of Science Park, Nanshan District, Shenzhen City, Guangdong Province "; const arrayAddress = csvAddressDetail.split(","); const { 0: province, 1: city, 2: district, 3: address } = arrayAddress; console.log(province, city, district, address); // Science Park Building, North Science Park, Nanshan District, Shenzhen city, Guangdong ProvinceCopy the code

Of course, you can skip some indexes as follows:

const arrayAddress = csvAddressDetail.split(","); const { 1: city, 3: address } = arrayAddress; console.log(city, address); // Science Park Building, North District, Science Park, Shenzhen cityCopy the code

8. Variable digital conversion

Converting a value to a number, especially a string to a number, is often used. There are many ways to do this. Here are some common ways:

console.log(+"15"); // 15 console.log(+true); // 1 console.log(+false); // 0 console.log(+null); // 0 console.log(Number("15")); // 15 console.log(parseInt("15", 10)); / / 15 console. The log (parseFloat (" 15.42 ")); / / 15.42Copy the code

9. Obtain the file name extension

The following code snippet shows how to get the extension name of a file from a full path or file name:

const arrayFiles = [
    "/attach/pics/logo.png",
    "logo.svg",
    "template.xlsx",
    "template.doc",
];
const getExtName = (fullpath) => {
    const root = fullpath.split(/[\\/]/).pop();
    const pos = root.lastIndexOf(".");
    return root === "" || pos < 1 ? "" : root.slice(pos + 1);
};

const arrayExtNames = arrayFiles.map((item) => getExtName(item));
console.log(arrayExtNames); // [ 'png', 'svg', 'xlsx', 'doc' ]
Copy the code

10. Common function definitions

Suppose you need to define a function, give some arguments and functions, and execute the function with those arguments. The code snippet shows the functionality of a calculator and the use of an extended operator, as follows:

const calculator = (operation, ... numbers) => { return operation(... numbers); }; function add(... numbers) { return numbers.reduce((acc, num) => acc + num, 0); } function subtract(... numbers) { return numbers.reduce((acc, num) => acc - num, 0); } function multiply(... numbers) { return numbers.reduce((acc, num) => acc * num, 1); } console.log(calculator(add, 1, 2, 3, 4, 5)); // 15 console.log(calculator(subtract, 20, 12, 1)); // -33 console.log(calculator(multiply, 1, 2, 3, 4)); Function printTitle({title}) {console.log(title); } const article = {title: "JavaScript function definition ", description: "function definition ",}; printTitle(article); // JavaScript function definitionCopy the code