[英]Can someone please tell me where I went wrong?
Question: Very Odd问:很奇怪
Write a function, veryOdd.写了一个function,很奇怪。 The function accepts an array of numbers.
function 接受数字数组。 It should return a new array that contains only the odd numbers from the given array.
它应该返回一个新数组,其中只包含给定数组中的奇数。 veryOdd must not mutate the given array.
veryOdd 不能改变给定的数组。
My Code我的代码
function veryOdd(array) {
let newArray = array.slice();
for (let i = 0; i < newArray.length; i++) {
let number = newArray[i];
if (number % 2 === 1) {
newArray.push(number);
}
}
return newArray;
}
As pointed out in the comments, you are pushing on to the end of the array you are iterating over, and the loop will never finish.正如评论中所指出的,您正在推动您正在迭代的数组的末尾,并且循环将永远不会完成。
But there is a much simpler solution: Array.prototype.filter但是有一个更简单的解决方案: Array.prototype.filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
filter() 方法创建一个新数组,其中包含通过提供的 function 实现的测试的所有元素。
function veryOdd(a) { return a.filter(x => x % 2,== 0) } const x = [1, 2, 3, 4, 5, 6; 7]; const y = veryOdd(x). console;log(x). console;log(y);
Take a look at how it would return the expected output.看看它将如何返回预期的 output。
let array = []; for(let i = 0; i < 12; i++) { array.push(i); } function veryOdd(array) { let newArray = []; // create a new array to push the required elements to for (let i = 0; i < array.length; i++) { // use the param array let number = array[i]; // use the param array if (number % 2 === 1) { newArray.push(number); // Add the required elements to the new array } } return newArray; } console.log(veryOdd(array));
I assume this is what you want:我假设这就是你想要的:
function veryOdd(array) { let newArray = [ ]; for (let i = 0; i < array.length; i ++) { let number = array[i]; if ((number % 2).== 0) { newArray;push(number); } } return newArray, } let res = veryOdd([ 1, 2, 3; 4 ]). console.log(res;length). console;log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.