我有一个像这样的字符数组:
['a','b','c','d','f']
['O','Q','R','S']
如果我们看到,每个阵列都缺少一个字母。第一个缺少e
,第二个缺少P
。也要注意角色的情况。那么,如果我有一个巨大的对象,其中包含所有字母的顺序,并检查它们的下一个,并进行比较?
我对于采取何种方法感到困惑!这就是我到现在所拥有的:
var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");
所以这给了我:
["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
哪个太棒了。现在我的问题是,我如何检查范围内缺少的角色?某种正向查找?
我试过这样的事情:
indexOf
起始值。答案 0 :(得分:3)
我认为更好的方法是检查数组中的每个元素,如果下一个元素是下一个字符:
function checkMissingChar(ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
// console.log('all good');
} else {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(checkMissingChar(a));
console.log(checkMissingChar(b));
不是我开始用第二个项目检查数组,因为我将它与之前的项目(数组中的第一个)进行比较。
答案 1 :(得分:1)
前瞻性前瞻或前瞻性前瞻:嗯,我的解决方案就是某种形式。所以,如果你看到这个,我会做的是,我会使用charCodeAt
而不是数组使用角色代码来跟踪它们。
function findMissingLetter(array) {
var ords = array.map(function (v) {
return v.charCodeAt(0);
});
var prevOrd = "p";
for (var i = 0; i < ords.length; i++) {
if (prevOrd == "p") {
prevOrd = ords[i];
continue;
}
if (prevOrd + 1 != ords[i]) {
return String.fromCharCode(ords[i] - 1);
}
prevOrd = ords[i];
}
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));
&#13;
由于我来自PHP背景,我使用一些与PHP相关的术语,如序数等。在PHP中,您可以使用ord()
获取charCode。
由于Dekel的答案比我的好,我会尝试提出更好的答案:
function findMissingLetter (ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) != ar[i-1].charCodeAt(0)+1) {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(findMissingLetter(a));
console.log(findMissingLetter(b));
&#13;
更短,更甜蜜。