JavaScript Handwritten Code Issue 4

1. Why write code by hand?

In the daily development process, we often take it out and use it directly, never thinking about the underlying implementation logic of the code, but when I started to study some underlying things, I began to understand the underlying implementation ideas of each method and function in JavaScript , I think this can improve our code level and logical thinking very well.

2. Handwritten implementation

2.1 Array flattening

Simply put, it is to convert a multidimensional array to a one-dimensional array

2.1.1 Recursive implementation of array flattening

See notes for specific ideas

            let arr = [1, 2, [3, 4], [5, [6, 7]]];
            function flat(arr) {
    
    
                let result = [];
                for (let i = 0; i < arr.length; i++) {
    
    
                    // 判断数组的元素是否为数组
                    if (Array.isArray(arr[i])) {
    
    
                        // 如果为数组,就进行递归
                        result = result.concat(flat(arr[i]));
                    } else {
    
    
                        // 如果不是数组,直接push到数组里面
                        result.push(arr[i]);
                    }
                }
                return result;
            }
            console.log(flat(arr)); // [1,2,3,4,5,6]

2.1.2 Using the spread operator and the array method some

The specific idea is to traverse the array arr, as long as it is not completely flattened, it will always be flattened

            let arr = [1, 2, [3, 4], [5, [6, 7]]];
            function flat(arr) {
    
    
                // 主要数组元素还是多维数组,就会一直为true,一直指向拍平操作
                while (arr.some((item) => Array.isArray(item))) {
    
    
                    arr = [].concat(...arr);
                    console.log(arr);
                }
                return arr;
            }
            console.log(flat(arr));

2.1.3 Using the reduce method to iterate

            let arr = [1, 2, [3, 4], [5, [6, 7]]];
            function flat(arr) {
    
    
                return arr.reduce((pre, cur) => {
    
    
                    return pre.concat(Array.isArray(cur) ? flat(cur) : cur);
                }, []);
            }
            console.log(flat(arr));

2.1.4 Use the toString method to flatten the array

            let arr = [1, 2, [3, 4], [5, [6, 7]]];
            function flat(arr) {
    
    
                return arr
                    .toString()
                    .split(',')
                    .map((item) => Number(item));
            }
            console.log(flat(arr));

2.1.5 You can directly use the new flat method of ES6

Flatten the array and return a new array without affecting the original data

flat() will only "flatten" one layer by default. If you want to "flatten" a multi-layer nested array, you can write the parameter of the flat() method as an integer, indicating the number of layers you want to flatten. The default is 1

Example of
using Infinity (infinity) to shoot flat

            let arr = [1, 2, [3, 4], [5, [6, 7]]];
            // 一般我们计算要拍平几层,直接使用Infinity(无穷大)方法
            // 有几层我便拍平几层
            function flat(arr) {
    
    
                return arr.flat(Infinity);
            }
            console.log(flat(arr)); // [1, 2, 3, 4, 5, 6, 7]

2.1.6 JSON.Stringify implementation and regular expressions

            let arr = [1, 2, [3, 4], [5, [6, 7]]];
            function flat(arr) {
    
    
                // 先价格
                let str = JSON.stringify(arr);
                // 将[和] 都替换为空字符串
                str = str.replace(/(\[|\])/g, '');
                // 然后再两侧加上[]就成了一维数组
                str = '[' + str + ']';
                return JSON.parse(str);
            }
            console.log(flat(arr)); // [1, 2, 3, 4, 5, 6, 7]

2.2 Realize the value of the exchange variable (without using the intermediate variable temp)

successfully achieved

            let a = 3,
                b = 1;
            a = a + b;
            b = a - b;
            a = a - b;
            console.log(a); // 1
            console.log(b); // 3

2.3 Implement the date formatting function (year, month, day)

            const dateFormat = function (date, format) {
    
    
                let year = date.getFullYear();
                // 月份加一,从0开始
                let month = date.getMonth() + 1;
                let day = date.getDate();
                // 正则替换
                format = format.replace(/YYYY/, year);
                format = format.replace(/MM/, month);
                format = format.replace(/DD/, day);
                return format;
            };
            console.log(dateFormat(new Date(), 'YYYY/MM/DD')); // 2023/6/23
            console.log(dateFormat(new Date(), 'YYYY年MM月DD日')); // 2023年6月23日

I have talked about the date object in detail before, you can take a look at the detailed explanation of the Date object

Welcome everyone to discuss and study, thank you for your support

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131352067