gpt4 book ai didi

javascript - Array.splice() 显示太多

转载 作者:行者123 更新时间:2023-11-28 03:29:02 25 4
gpt4 key购买 nike

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

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']

关于javascript - Array.splice() 显示太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58336286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com