Javascript 密码战:字母对称
我几乎要完成一项名为“字母对称”的代码战任务。Javascript 密码战:字母对称,javascript,Javascript,我几乎要完成一项名为“字母对称”的代码战任务。 以下是链接: 我试着用JavaScript语言完成它 因此,我的代码正在运行,它通过了所有测试,除了一个: Test.assertDeepEquals(solve(["IAMDEFANDJKL","thedefgh","xyzDEFghijabc"]),[6, 3, 7]); 错误:预期为:[6,5,7],而实际为:[6,3,7] 我的代码: 请帮我找到问题所在 谢谢你;) 这是一个逻辑
以下是链接:
我试着用JavaScript语言完成它
因此,我的代码正在运行,它通过了所有测试,除了一个:
Test.assertDeepEquals(solve(["IAMDEFANDJKL","thedefgh","xyzDEFghijabc"]),[6, 3, 7]);
错误:预期为:[6,5,7],而实际为:[6,3,7]我的代码: 请帮我找到问题所在
谢谢你;) 这是一个逻辑问题:
el == alphabeth[elArr.indexOf(el)])
您不是直接查看索引,而是通过查找元素的索引来间接执行。输入的deff
包含两个字母e
和h
,这会干扰您的结果
首先尝试按索引进行,如下所示:
function solve(arr) {
return arr.map(function(input) {
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
let arr = input.toLowerCase().split('');
let sum = 0;
// You can iterate an array with a forEach AND keep the index:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
arr.forEach(function(val, i) {
// Now the check is much simpler. See if the character in index I
// matches the character in the alphabet at index i
if(val === alphabet[i])
sum++
});
return sum;
});
}
function solve(arr) {
return arr.map(function(input) {
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
let arr = input.toLowerCase().split('');
let sum = 0;
// You can iterate an array with a forEach AND keep the index:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
arr.forEach(function(val, i) {
// Now the check is much simpler. See if the character in index I
// matches the character in the alphabet at index i
if(val === alphabet[i])
sum++
});
return sum;
});
}