跳至主要內容

函数

chanchaw大约 1 分钟javascript

嵌套函数

f() 表示执行外层函数,返回内存函数,f()()表示从外层函数开始执行最终返回内层函数的返回结果,下面案例是对象数组按照多属性排序的代码

function sortOneProp(property){
		let order = 1;
		if(property[0] === '-'){
			order = -1;
			property = property.substr(1);
		}
		
		return function (a,b){
			const result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0
			return result * order;
		}
	}
	
	// 按照多个属性进行排序
	function sortMultiProps(){
		/*
		 * 保存arguments对象,因为它将被覆盖
		 * 注意arguments对象是一个类似数组的对象
		 * 由要排序的属性的名称组成
		 */
		let props = arguments
		return function (obj1, obj2) {
			let i = 0, result = 0, numberOfProperties = props.length
			// 从0开始获取不同的结果,因为有多个属性需要比较
			while(result === 0 && i < numberOfProperties) {
				result = sortOneProp(props[i])(obj1, obj2)
				i++
			}
			return result
		}
	}
	
function testCompareFun(){
    const arrData = [
        {name: 'tom4', mdate: '202012',id:3},
        {name:'tom2', mdate:'202001',id:3},
        {name: 'tom1', mdate: '202008',id:1},
        {name: 'tom3', mdate: '202005',id:2}
    ]
    // 属性前面带有减号表示倒序排列,没有则表示正序排列
    // 排序函数 sortOneProp 只能根据一个属性进行排序
    //const newArr = arrData.sort(sortOneProp('-id'));
    //console.log(newArr);
    
    // 按照多个属性排序
    const newArr = arrData.sort(sortMultiProps('id','name'));
    console.log(newArr);
}

函数柯里化

函数的柯里化
函数的柯里化