如何将数组作为组合函数参数?解决TypeError报错问题
解决TypeError: arr.map is not a function并实现allToLower组合函数
报错原因
你的compose函数是从右往左依次执行传入的函数,原来的代码中compose里先执行arr.join("-"),把数组直接转成了字符串。后续的arr.map是对字符串调用map方法,但字符串并没有map方法,因此抛出TypeError: arr.map is not a function。
修复报错
调整compose内函数的顺序,先执行map处理数组的每个元素,再执行join拼接字符串:
let capitalizeAllFirst = modifyArray( compose( (arr) => arr.join("-"), (arr) => arr.map( (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() ) ) );
实现allToLower变量
使用compose组合一个遍历数组将每个字符串转为小写的函数,再用modifyArray包裹:
let allToLower = modifyArray( compose( (arr) => arr.map(str => str.toLowerCase()) ) );
如果需要对处理后的数组追加其他操作(比如拼接),直接在compose中按从右到左的执行顺序添加函数即可。
完整测试代码
const testArray = ["CusTom", "Web", "aNd", "MoBile", "PlaTfoRms"]; const compose = (...fncs) => (val) => fncs.reduceRight((acc, fnc) => fnc(acc), val); const modifyArray = (ModifyCondition) => (data) => ModifyCondition(data); // 修复后的capitalizeAllFirst let capitalizeAllFirst = modifyArray( compose( (arr) => arr.join("-"), (arr) => arr.map( (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() ) ) ); // 实现的allToLower let allToLower = modifyArray( compose( (arr) => arr.map(str => str.toLowerCase()) ) ); console.log(capitalizeAllFirst(testArray)); // 输出 "Custom-Web-And-Mobile-Platforms" console.log(allToLower(testArray)); // 输出 ["custom", "web", "and", "mobile", "platforms"]
内容的提问来源于stack exchange,提问作者Volodymyr Berkych
相关产品推荐
相关产品推荐

