这段代码中 else if 我感觉永远不会被触发,求大神答疑,何时触发else if中的语句,谢谢。
module.exports = spinalCaseValue => {
//删除'use strict'中的''拿到实际值。
let strArray = spinalCaseValue.split('');
let shouldCapitalize = false;
return strArray.reduce((acc, cur) => {
if(cur === '-') {//==判断值 ===判断类型和值
shouldCapitalize = true;
return acc;
} else if (shouldCapitalize) {
shouldCapitalize = false;
return acc.concat(cur.toUpperCase());
} else {
return acc.concat(cur);
}
})
}
修改下
this-Is-A-Tree
应该是
thisIsATree,吃掉了-
reduce对每个字符都会调用一次,而shouldCapitalize作为一个闭包变量,可以理解为全局变量。对于单次调用,肯定要么if要么else,但是多次调用,前一次走了if,设置了shouldCapitalize,就会导致第二次走else
这段代码的作用是对一个字符串去掉-并且把首字符改为大写。比如
this-is-a-tree 转换为this-Is-A-Tree
走入else if的时机是,上一个字符是-,因此shouldCapitalize被设置为true