[js]字符串和数组的方法

字符串和数组两种数据结构,经常用到,逃不过, 所以就总结一下

js里str和arr对应的方法和py里类似.只不过写法有点恶心.

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);

猜你喜欢

转载自www.cnblogs.com/iiiiiher/p/8976449.html