简体   繁体   English

为什么我的代码可以在一种环境中工作,而不能在另一种环境中工作?

[英]Why does my code work in one environment, but not in another?

I'm doing a kata on Codewars.我在 Codewars 上做一个 kata。 I'm supposed to write a function that returns the index of which number, is not like the others, in evenness(ie [1, 2, 4] should return 0).我应该写一个 function 返回哪个数字的索引,与其他数字不同,均匀度(即 [1, 2, 4] 应该返回 0)。 I believe I have a solution, and it proves true when copy/pasting the code, and console.logging on freecodecamps live server, however, when i try to run the code where it is written, it only passes one test.我相信我有一个解决方案,并且在复制/粘贴代码时证明是正确的,并且 console.logging 在 freecodecamps 实时服务器上,但是,当我尝试运行它编写的代码时,它只通过了一个测试。 What is going wrong here?这里出了什么问题?

I've tried testing with console.logs, and my solution holds.我已经尝试使用 console.logs 进行测试,并且我的解决方案成立。 I know I could just use filter to solve the problem, but i wan't to practice fundamentals.我知道我可以只使用过滤器来解决问题,但我不想练习基础知识。

 let odd = []; let even = []; function isEven(num) { if (num % 2 === 0) { return true; } else { return false; } } function iqTest(numbers) { let nums = numbers.split(' ').map(function(item) { return parseInt(item, 10); }) for (let i in nums) { if (isEven(nums[i])) { even.push(nums[i]) } else { odd.push(nums[i]) } } if (even.length > odd.length) { return nums.indexOf(odd[0]) + 1; } else { return nums.indexOf(even[0]) + 1; } }

The function should accept a string of numbers, one of which will not be either even or odd, then return the index of that number + 1. function 应该接受一串数字,其中一个既不是偶数也不是奇数,然后返回该数字的索引 + 1。

You could take the in comments mentioned approach and search for at least one odd and one even and one additional item, at least three items and exit early if this combination is found.您可以采用评论中提到的方法并搜索至少一个奇数和一个偶数以及一个附加项目,至少三个项目,如果找到此组合,请提前退出。

No need to convert the values in advance, because the value get converted to number by using the remainder operator of isEven function.不需要预先转换值,因为使用isEven function 的余数运算符将值转换为数字。

For a faster return value store the index instead of the value and omit a later indexOf seach.为了更快的返回值存储索引而不是值并省略以后的indexOf搜索。

 function isEven(i) { return i % 2 === 0; } function iqTest(numbers) { var even = [], odd = [], values = numbers.split(' '); for (let i = 0; i < values.length; i++) { (isEven(values[i])? even: odd).push(i); if (even.length && odd.length && even.length + odd.length > 2) return (even.length < odd.length? even: odd)[0] + 1; } } console.log(iqTest("1 2 4")); // 1 console.log(iqTest("2 4 7 8 10")) // 3 console.log(iqTest("1 2 1 1")); // 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM