Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 密码战:字母对称_Javascript - Fatal编程技术网

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;
    });
}