题目描述
•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组
示例1
输入
abc
123456789
输出
abc00000
12345678
90000000
本来我是这么写的,代码又臭又长,其实有很多地方可以优化,这里展示我的代码最初版本:
let str = ['asdfasad', 'addlfnajsf', 'dashd', '12345678123456789'] //输入的字符串数组
let newArr = []
str.forEach(item => {
if (item.length <= 8) { //若字符串长度小于等于8
while (item.length < 8) {
item = item.concat('0') //拼接0直到字符串长度为8
}
newArr.push(item)
} else { //若字符串长度大于8
if (item.length % 8 === 0) { //若字符串长度为8的倍数
for (let i = 0; i < item.length; i += 8) {
newArr.push(item.substr(i, 8)) //剪切完直接push到newArr里
}
} else { //若字符串不是8的倍数
for (let i = 0; i < item.length; i += 8) {
if (i === (item.length - item.length % 8)) { //当循环到最后一次时
let teststr = item.substr(i, item.length % 8)
while (teststr.length < 8) {
teststr = teststr.concat('0') //拼接0直到字符串长度为8
}
newArr.push(teststr)
} else {
newArr.push(item.substr(i, 8))
}
}
}
}
})
console.log(newArr);
输出结果:
学了ES6以后,再加上自己写的代码也多了,对这段代码做了优化。
其中用到了ES6的新字符串方法padEnd():返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串。
比如:
console.log("h".padEnd(5,"o")); // "hoooo"
如果指定的长度等于原字符串的长度,则返回原字符串。
console.log("hello".padEnd(5,"A")); // "hello"
所以新代码写为:
str.forEach(item => {
for(let i = 0; i < item.length; i+=8){ //每8个一循环
newArr.push(item.slice(i,i+8).padEnd(8,0)) //字符串长度满8就略过,不满8就补齐
}
})
输出结果相同: