高阶JavaScript用法

简介:

高阶JavaScript用法通常指的是利用JavaScript中的函数作为一等公民(first-class citizens)的特性,以及函数的闭包(closure)和函数里化(currying)等特性,实现更加灵活和高效的编程方式。以下是几个常见的高阶JavaScript用法:
1.函数作为参数传递:JavaScript中的函数可以作为参数传递给另一个函数,这种方式通常被用于实现回调函数(callback),例如在事件处理中,当某个事件触发时,执行某个特定的回调函数。
2.函数作为返回值:JavaScript中的函数也可以作为返回值,这种方式通常被用于实现柯里化(currying)和闭包(closure)。柯里化是指将一个多参数函数转化为一系列单参数函数的过程,这种方式可以使函数更加灵活。闭包是指函数可以访问其定义时所处的作用域中的变量,这种方式可以使函数更加封闭和安全。
3.函数组合:函数组合是指将多个函数组合成一个新函数的过程,通常使用函数柯里化和函数合成(function composition)实现。函数合成是指将多个函数组合成一个新函数的过程,其中每个函数的输出作为下一个函数的输入。
4.高阶函数:高阶函数是指接受一个或多个函数作为参数,并返回一个新函数的函数。这种方式通常被用于实现某些通用的功能,例如函数记忆化(memoization)和函数装饰器(function decorator)等。

记录JS中一些高阶用法和应用场景,方便工作中处理业务逻辑(不定期更新)

reduce函数:

它将一个数组中的所有元素累加到一个值上,返回一个新的值。该函数接受两个参数:一个累加器函数和一个初始值。累加器函数接受两个参数:累加器和当前值,然后返回累加器的值。

reduce()函数的语法

array.reduce(function(accumulator, currentValue, currentIndex, array) {
    
    
  // 逻辑处理
}, initialValue);

参数说明:

  • accumulator:累加器,每次累加的结果会被存储在accumulator中,并在下一次迭代中作为第一个参数传入。
  • currentValue:当前值,是数组中当前被处理的元素。
  • currentIndex:当前索引,可选,是当前元素在数组中的索引值。
  • array:原数组,可选,是reduce()被调用的数组。
  • initialValue:初始值,可选,作为第一次调用累加器函数时的第一个参数传入。

常见的使用场景:

1.数组求和:

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15

2.数组求平均值:

const arr = [1, 2, 3, 4, 5];
const average = arr.reduce((accumulator, currentValue, currentIndex, array) => {
    
    
  accumulator += currentValue;
  if (currentIndex === array.length - 1) {
    
    
    return accumulator / array.length;
  } else {
    
    
    return accumulator;
  }
}, 0);
console.log(average); // 3

3.数组去重:

const arr = [1, 2, 3, 4, 3, 2, 1];
const uniqueArr = arr.reduce((accumulator, currentValue) => {
    
    
  if (!accumulator.includes(currentValue)) {
    
    
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4]

4.数组对象求和:

const arr = [
  {
    
     name: "A", score: 90 },
  {
    
     name: "B", score: 80 },
  {
    
     name: "C", score: 70 },
];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue.score, 0);
console.log(sum); // 240

5.数组对象分组:

const arr = [
  {
    
     name: "A", score: 90 },
  {
    
     name: "B", score: 80 },
  {
    
     name: "C", score: 70 },
];
const groupByScore = arr.reduce((accumulator, currentValue) => {
    
    
  const score = currentValue.score;
  if (!accumulator[score]) {
    
    
    accumulator[score] = [];
  }
  accumulator[score].push(currentValue);
  return accumulator;
}, {
    
    });
console.log(groupByScore);
// {
    
    
//   90: [{ name: "A", score: 90 }],
//   80: [{ name: "B", score: 80 }],
//   70: [{ name: "C", score: 

工作处理场景

// 接口返回数据
const data = [
  {
    
    
    "name": "运行状态",
    "code": "code001",
    "deviceId": "1645689299270561794",
    "deviceTypeId": "1646767246385205249",
    "isTemplate": false,
    "unit": "",
    "isWritable": false,
    "showOrder": 1,
    "showType": "",
    "isNumber": false,
    "regName": "",
    "value": "",
    "saveInterval": 5,
    "valueText": null,
    "deviceParamDictId": 1648870911295139800,
    "subList": [
      {
    
    
        "name": "运行",
        "value": "1.00"
      },
      {
    
    
        "name": "停止",
        "value": "0.00"
      },
      {
    
    
        "name": "测试导入",
        "value": null
      },
      {
    
    
        "name": "测试导入",
        "value": null
      }
    ]
  },
  {
    
    
    "name": "手自动状态",
    "code": "shouzidong",
    "deviceId": "1645689299270561794",
    "deviceTypeId": "1646767246385205249",
    "isTemplate": false,
    "unit": "",
    "isWritable": false,
    "showOrder": 2,
    "showType": "",
    "isNumber": false,
    "regName": "tagName12",
    "value": "",
    "saveInterval": 5,
    "valueText": null,
    "deviceParamDictId": 1648870911295139800,
    "subList": [
      {
    
    
        "name": "运行",
        "value": "1.00"
      },
      {
    
    
        "name": "停止",
        "value": "0.00"
      },
      {
    
    
        "name": "测试导入",
        "value": null
      },
      {
    
    
        "name": "测试导入",
        "value": null
      }
    ]
  },
  {
    
    
    "name": "送风温度反馈",
    "code": "fankui",
    "deviceId": "1645689299270561794",
    "deviceTypeId": "1646767246385205249",
    "isTemplate": false,
    "unit": "℃",
    "isWritable": false,
    "showOrder": 3,
    "showType": "",
    "isNumber": false,
    "regName": "tagname2",
    "value": "",
    "saveInterval": 5,
    "valueText": null,
    "deviceParamDictId": null,
    "subList": null
  },
  {
    
    
    "name": "启停状态",
    "code": "qiting",
    "deviceId": "1645689299270561794",
    "deviceTypeId": "1646767246385205249",
    "isTemplate": false,
    "unit": "",
    "isWritable": true,
    "showOrder": 4,
    "showType": "switch",
    "isNumber": false,
    "regName": "tagname4",
    "value": "",
    "saveInterval": 5,
    "valueText": null,
    "deviceParamDictId": 1648864822247862300,
    "subList": [
      {
    
    
        "name": "开",
        "value": "1.00"
      },
      {
    
    
        "name": "关",
        "value": "0.00"
      }
    ]
  },
  {
    
    
    "name": "季节转换",
    "code": "jijiezhuanhuan",
    "deviceId": "1645689299270561794",
    "deviceTypeId": "1646767246385205249",
    "isTemplate": false,
    "unit": "",
    "isWritable": true,
    "showOrder": 5,
    "showType": "select",
    "isNumber": false,
    "regName": "tagname5",
    "value": "",
    "saveInterval": 5,
    "valueText": null,
    "deviceParamDictId": 1648865304638959600,
    "subList": [
      {
    
    
        "name": "春",
        "value": "0.00"
      },
      {
    
    
        "name": "夏",
        "value": "1.00"
      },
      {
    
    
        "name": "秋",
        "value": "2.00"
      },
      {
    
    
        "name": "冬",
        "value": "3.00"
      }
    ]
  },
  {
    
    
    "name": "送风温度设定",
    "code": "sheding",
    "deviceId": "1645689299270561794",
    "deviceTypeId": "1646767246385205249",
    "isTemplate": false,
    "unit": "℃",
    "isWritable": true,
    "showOrder": 6,
    "showType": "inputnumber",
    "isNumber": false,
    "regName": "tagname6",
    "value": "11",
    "saveInterval": 5,
    "valueText": null,
    "deviceParamDictId": null,
    "subList": null
  }
]
	// 使用reduce处理逻辑
	initDeviceParams() {
    
    
            const result = {
    
    
                regNames: [], // 获取所有的regName
                writableArray: [], // writable 为true
                notWritableArray: [],  // else
                deviceMapData: {
    
    }, // 处理成map 类型
            };
            data.reduce((acc, cur) => {
    
    
                if (cur.regName !== '') {
    
    
                    acc.regNames.push(cur.regName);
                }
                if (cur.isWritable) {
    
    
                    acc.writableArray.push(cur);
                } else {
    
    
                    acc.notWritableArray.push(cur);
                }
                if (cur.subList && cur.subList.length > 0) {
    
    
                    const subItem = cur.subList.find(
                        (item) => item.name === cur.value
                    );
                    acc.deviceMapData[cur.name] = subItem
                        ? subItem.value
                        : cur.value;
                } else {
    
    
                    acc.deviceMapData[cur.name] = cur.value;
                }
                return acc;
            }, result);

            this.regNames = result.regNames;
            this.writableArray = result.writableArray;
            this.notWritableArray = result.notWritableArray;
            this.deviceMapData = result.deviceMapData;
            this.isLoaded = true;

            console.log(this.deviceMapData);
            // 输出结果
			//{
    
    
			    //"运行状态": "",
			    //"手自动状态": "",
			    //"送风温度反馈": "",
			    //"启停状态": "",
			    //"季节转换": "",
			    //"送风温度设定": "11"
			//}
            
        },

map函数:

JavaScript中的Map是一种新的数据结构,可以将任意类型的值(包括对象)作为键(key)存储,而不仅仅是字符串和符号,从而提供了更加灵活的键值对存储方式。Map是ES6中引入的新特性,使用方法类似于对象,但具有更多的功能和扩展性。
使用new Map()可以创建一个空的Map对象,也可以通过传入一个二维数组或者一个可迭代对象来初始化Map对象,这里的二维数组或可迭代对象中每个元素是一个键值对,第一个元素是键,第二个元素是值。Map对象具有以下方法和属性:

  • set(key, value):将键值对添加到Map对象中,如果该键已经存在,则更新对应的值
  • get(key):获取指定键对应的值,如果键不存在,则返回undefined。
  • has(key):判断Map对象中是否存在指定键。
  • delete(key):删除Map对象中指定键及其对应的值。
  • clear():清空Map对象中所有键值对。
  • size:返回Map对象中键值对的数量。
  • entries():返回一个包含Map对象中所有键值对的迭代器。
  • keys():返回一个包含Map对象中所有键的迭代器。
  • values():返回一个包含Map对象中所有值的迭代器。
    例子:
const map = new Map([
  ["key1", "value1"],
  ["key2", "value2"],
  ["key3", "value3"]
]);

console.log(map.size); // 3

map.set("key4", "value4");
console.log(map.get("key2")); // "value2"

for (const [key, value] of map.entries()) {
    
    
  console.log(`${
      
      key}: ${
      
      value}`);
}

// key1: value1
// key2: value2
// key3: value3
// key4: value4

说明:

首先使用一个包含三个键值对的二维数组初始化了一个Map对象。然后,我们使用set()方法向Map对象中添加了一个新的键值对,使用get()方法获取了一个键对应的值。最后,我们使用一个for…of循环遍历了Map对象中所有的键值对。

猜你喜欢

转载自blog.csdn.net/weixin_45906632/article/details/130296818