Instead of creating an array, you can directly access characters of the string with bracket notation.
const splitPairs = (input) => {
if(!input) return [];
let pairs = [];
if(input.length % 2 !== 0) {input += '_'}
for(let i = 0; i < input.length; i+= 2) {
pairs.push(`${input[i] + input[i+1]}`)
}
return pairs;
}
let result1 = splitPairs('abc');//--> [ 'ab', 'c_' ]
console.log(result1);
let result2 = splitPairs('abcdef');//--> [ 'ab', 'cd', 'ef' ]
console.log(result2);
let result3 = splitPairs('retrograde');//--> [ 're', 'tr', 'og', 'ra', 'de' ]
console.log(result3);
let result4 = splitPairs('endurance');//--> [ 'en', 'du', 'ra', 'nc', 'e_' ]
console.log(result4);
let result5 = splitPairs('');//--> []
console.log(result5);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…