[js] methods for strings and arrays

Two data structures, string and array, are often used and cannot escape, so let’s summarize

The methods corresponding to str and arr in js are similar to those in py. It's just that the writing is a bit disgusting.

s的方法
    根据k取v:
        取首尾项
    根据v取k:
        s.indexOf
    取切片
        s.substr(1,3)   //含3
        s.substring(1,3)//不含3
    split:
        s = 'maotai|maomao'
        s.split('|') // ["maotai", "maomao"]
        
        arr = ["maotai", "maomao"]
        arr.join('|') // 'maotai|maomao'
arr的方法
    arr.include:判断是否包含此项
        返回布尔

    arr.find:查找每项中是否包含关键字,
        参数: 回调函数
        返回: 找到的那一项的值
        回调函数中: 当返回的true, 表示有
        let res = arr.find(function (item, index) {
            return item.toString().indexOf('maotai') > -1; //这里返回的索引
        });


    arr.forEach: 遍历
    
        arr.forEach(function (value, key) {
            console.log(key + ':' + value);
        });

    arr.map = 遍历+修改 reduce filter
    
        let arr2 = arr.map(function (key, value) {
            return value * 10;
        });


    arr.every
        功能: 点击按钮检测数组的所有元素是否都大于 18 :
        参数: 回调函数
        返回值: 布尔
        let ages = [32, 33, 40];

        function checkAdult(age) {
            return age >= 18;
        }

        let res = ages.every(checkAdult);
        console.log(res);

    arr.reduce: 收敛
    
        let res = arr.reduce(function (prev, next, index, item) {
            // console.log(arguments);
            // console.log(prev, next); 
            return prev + next; //本次的返回值会作为上一次的prev
        });

        console.log(res);

        // 栗子1: 计算价格
        let res2 = [
            {'price': 30, count: 3},
            {'price': 60, count: 6},
            {'price': 90, count: 9}
        ].reduce(function (prev, next) {
            return prev+next.price*next.count;
        }, 0);

        console.log(res2);

        // 栗子2: 二维数组变一维数组
        let res3 = [
            [1,2,3],
            [4,5,6],
            [7,8,9]
        ].reduce(function (prev,next) {
            return prev.concat(next);
        });
        console.log(res3);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325102450&siteId=291194637