Array.splice() 显示太多



我的拼接有问题。我有代码

const findMissingLetter=(array)=>{
let result,alphabet = "abcdefghijklmnopqrstuvwxyz";
if(array[0]===array[0].toUpperCase()) alphabet = alphabet.toUpperCase();
let start = alphabet.split('').indexOf(array[0]);
return alphabet.split('').splice(start,start+array.length+1);
}

此函数应查找字母表中缺少的字母并返回此

参数仅包含小写字母或大写字母。 这段代码中的问题是,如果我在参数上使用它:

['a','b','c','d','f']- 那么它运行良好,返回['a', 'b', 'c', 'd', 'e', 'f']

但是如果我有大写字母:['O','Q','R','S']- 然后它返回['O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'].

const findMissingLetter = (array) => {
let result, alphabet = "abcdefghijklmnopqrstuvwxyz";
if (array[0] === array[0].toUpperCase()) alphabet = alphabet.toUpperCase();
let start = alphabet.split('').indexOf(array[0]);
return alphabet.split('').splice(start, start + array.length + 1);
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));

问题可能出在哪里?

你只需要array.length + 1没有开始索引,因为这是结果数组的所需长度。

const findMissingLetter = array => {
let alphabet = Array.from("abcdefghijklmnopqrstuvwxyz");
if (array[0] === array[0].toUpperCase()) alphabet = alphabet.map(c => c.toUpperCase());
let start = alphabet.indexOf(array[0]);
return alphabet.splice(start, array.length + 1);
}
console.log(...findMissingLetter(['a', 'b', 'c', 'd', 'f'])); // ['a', 'b', 'c', 'd', 'e', 'f']
console.log(...findMissingLetter(['O', 'Q', 'R', 'S'])); // ['O', 'P', 'Q', 'R', 'S']

最新更新