1、题目描述
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
2、示例
3、思路
将字符串转化为数组,直接用while循环在两个数组都不为空的前提下使用数组的api进行操作,最后返回的时候注意会有空数组,所以要全部进行join处理。
4、代码
/**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
var mergeAlternately = function(word1, word2) {
const arr = []
const result1 = word1.split('')
const result2 = word2.split('')
while(result1.length&&result2.length){
arr.push(result1.shift())
arr.push(result2.shift())
}
return [...arr,...result1,...result2].join('')
};