需求:修改主标题限制中文30个字符,英文60个字符;副标题限制中文40个字符,英文80个字符
//主标题
<el-input
v-model="navigateItem.title"
@input="(val)=> {handleInput(val,'title')}"></el-input>
//副标题
<el-input
v-model="navigateItem.subTitle"
@input="(val)=> {handleInput(val,'subTitle')}"></el-input>
handleInput(value, key) {
let index = 0
const selfValue = value.split('')
let count = 0
let charCode = -1
let titleLength
// 主标题和副标题限制不同长度
if (key === 'title') {
titleLength = 30
} else if (key === 'subTitle') {
titleLength = 40
}
// 遍历输入字符
selfValue.forEach((item, _index) => {
if (index) {
return
}
charCode = item.charCodeAt(item)
// 判断中英文字符
if (charCode >= 0 && charCode <= 128) {
count += 1
} else {
count += 2
}
if (count > titleLength) {
index = _index
}
})
// 输入框截断字符
if (index) {
this.navigateItem[key] = value.substring(0, index)
}
}
后续导师希望做一个小demo把forEach换成reduce
一开始思路如下:
selfValue.reduce((pre,cur,_index)=>{
if(pre >= titleLength){
index=_index
return pre
}
charCode = cur.charCodeAt(0)
if(charCode>=0 && charCode<=128){
return pre+1
}else{
return pre+1
}
},0)
if(index){
this.navigateItem[key] = value.substring(0,index)
}
然而在这过程中会出现如下问题
由于reduce是不会中断循环,直到遍历结束才会停止,因此可能存在达到num=6后后面的字符的num也为6,因此根据index拿到的值为错误的
解决方岸:上锁
checkInput(val){
let index = 0
let charCode = -1
let flag = true
let selfValue = val.split('')
slefValue.reduce(pre,cur,_index) =>{
if(pre>=4 && flag){
index = _index
this.input = val.substring(0,index)
flag = true
return pre
}
charCode = cur.charCodeAt(0)
if(charCode>=0 && charCode<=128){ return pre+1 }
else { return pre+2}
},0)
}