Split Strings

题目

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (‘_’).

Examples:

1
2
solution('abc') // should return ['ab', 'c_']
solution('abcdef') // should return ['ab', 'cd', 'ef']

思路

判断字符串长度,奇数就在最后补全”_”,然后分割。

  • arr.push() 数组的末尾添加新的元素

答案

1
2
3
4
5
6
7
8
9
function solution(str) {
str.length % 2 !== 0 ? str += "_": str;
var arr = new Array;
for (i = 0; i < str.length; i = i + 2) {
str2 = str[i] + str[i + 1];
arr.push(str2);
}
return arr;
}