简体   繁体   English

遍历 javascript 中的数组并返回新数组

[英]iterate through array in javascript and return in new array

i'm totally new to coding: i want to iterate through the array input , select the positive numbers only, then put them in a new array liste and then print the new array in the console.我对编码完全陌生:我想遍历数组输入select只有正数,然后将它们放入一个新的数组列表中,然后在控制台中打印新数组。 what am i doing wrong here???我在这里做错了什么???

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];

var liste = [];

function cut(input){
    for (var i=0; i<cut.length; i++){
        if (i>0){
            liste.push(input[i]);
            return liste;
    } 
}

var result = cut(input);
console.log(result);

Since I can't accurately portray in a comment what I would want to explain, I am posting an answer:由于我无法在评论中准确描述我想解释的内容,因此我发布了一个答案:

I find it much easier to balance braces when I format my code like so当我像这样格式化我的代码时,我发现平衡大括号要容易得多

function cut(input)
{
    for (var i=0; i<cut.length; i++)
    {
        if (i>0)
        {
            liste.push(input[i]);
            return liste;
    } 
}

And now its pretty apparent where the unbalanced brace is.现在很明显不平衡的支架在哪里。

There are other syntax errors that others have already been pointed out:还有其他人已经指出的其他语法错误:

  1. Its not cut.length , rather input.length .它不是cut.length ,而是input.length
  2. Your if statement needs to be if (input[i] > 0) , not if (i > 0)您的if语句需要是if (input[i] > 0) ,而不是if (i > 0)
  3. return liste shouldn't be inside of the loop, rather at the end of the function, because once a value is found it will stop the loop and immediately return only 1 value inside of the array. return liste不应在循环内部,而应在 function 的末尾,因为一旦找到一个值,它将停止循环并立即仅返回数组内部的 1 个值。

Here should be a working example of what you intended to do.这应该是您打算做什么的工作示例。 Other than those few syntax errors, good job with the logic!除了那几个语法错误,逻辑做得很好!

 let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]; function cut(input){ let liste = []; for (var i=0; i<input.length; i++){ if (input[i]>0){ liste.push(input[i]); } } return liste; } var result = cut(input); console.log(result);

There are 4 mistakes in your code您的代码中有 4 个错误

  1. i<cut.length, you have to check the input length not the length of the function i<cut.length,你必须检查输入长度而不是 function 的长度

  2. i>0, it should be input[i]>0, since you are comparing the input indecis i>0,应该是input[i]>0,因为你比较的是indecis

  3. Curly braces of if statement is not closed if 语句的花括号没有闭合

  4. Return is not outside the for loop return不在for循环外

After fixing all these it should work修复所有这些后它应该工作

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];

var liste = [];
function cut(input){
  
    for (var i=0; i<input.length; i++){ //error 1
        if (input[i]>0){//2
            liste.push(input[i]);
        }//error 3
    } 
        return liste;//error 4
    }

var result = cut(input);
console.log(result);

I'll attempt to combine the points made in several other answers here, and add some more explanation.我将尝试在这里结合其他几个答案中的观点,并添加更多解释。

Fixing the For Loop, One Line at a Time修复 For 循环,一次一行

Most of your code is fine;您的大部分代码都很好; the only issues are in your for loop.唯一的问题在你的for循环中。 Let's review that from top to bottom.让我们从上到下回顾一下。

for (var i=0; i<cut.length; i++){

You have the right idea here.你在这里有正确的想法。 However, in this for loop, you want to make i loop from 0 to the length of the array you're looping over-- not the length of the function you wrote.但是,在这个for循环中,您想让i从 0 循环到您正在循环的数组的长度——而不是您编写的 function 的长度。 So you should replace cut.length with input.length .所以你应该用cut.length替换input.length This way, i will loop from 0 to 14.这样, i将从 0 循环到 14。

    if (i>0){

i is a number you're using to keep track of how far into the array you are. i是您用来跟踪您进入数组的距离的数字。 As mentioned above, for your array, it will go from 0 to 14. You're trying to check if the number at the i th position is positive, not if i itself is.如上所述,对于您的数组,它将 go 从 0 到 14。您正在尝试检查第i个 position 处的数字是否为正数,而不是i本身是否为正数。 To access the number at the i th position, you can use input[i] instead of just i .要访问第i个 position 的号码,您可以使用input[i]而不仅仅是i

        liste.push(input[i]);

This line is fine;这条线很好; nice work!干得好! You're finding the number at the i th position of the input array and adding it to liste .您在input数组的第i个 position 找到数字并将其添加到liste Because of the if statement before, this only happens when that number is positive.由于之前的if语句,只有当该数字为正时才会发生这种情况。

        return liste;

This line will return the list immediately, exiting your cut function. You want this to happen only after you're done looping through all the numbers, so you just need to move this line after the for loop.此行将立即返回列表,退出您的cut function。您希望仅在完成所有数字的循环后发生这种情况,因此您只需将此行移动到for循环之后。

And one last thing-- you forgot a curly brace to end your if statement.最后一件事——你忘记了用花括号来结束你的if语句。 Be careful with this, as it can mess up your program.对此要小心,因为它会弄乱你的程序。

I've gone ahead and made all these changes.我已经进行了所有这些更改。 You can check them out in the following snippet:您可以在以下代码段中查看它们:

 let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]; var liste = []; function cut(input){ for (var i=0; i<input.length; i++){ if (input[i]>0){ liste.push(input[i]); } } return liste; } var result = cut(input); console.log(result);

Some things to explore:一些值得探索的事情:

  • What happens if you move var liste = [];如果你移动var liste = [];会发生什么? inside cut , like in Shmack's answer? inside cut ,就像在 Shmack 的回答中一样? Does the code still work?代码还能用吗? Why?为什么?
  • What happens if you rename all input s inside cut to something else?如果将cut中的所有input重命名为其他名称,会发生什么情况? Does the code still work?代码还能用吗? Why?为什么?

Understanding these questions isn't necessary, but learning the answers may help you to get better at coding for the future.理解这些问题不是必需的,但了解答案可能会帮助您更好地为未来编码。

A Better Method更好的方法

But wait, there's more?但是等等,还有更多? What if there was a built-in feature that could do this more easily for us?如果有一个内置功能可以更轻松地为我们做到这一点呢?

Introducing filter !介绍过滤器

filter is a useful method that all arrays have that lets them filter their contents based on a function that you give them. filter是一个有用的方法,所有 arrays 都可以让他们根据您提供给他们的 function 过滤他们的内容。 Using filter lets you bypass writing a for loop at all (although it is still good to practice writing them; sometimes they are very useful).使用filter可以让您完全绕过编写for循环(尽管练习编写它们仍然很好;有时它们非常有用)。

The function you provide to filter is usually written as an "arrow function" , which basically just means turning this:您提供给filter的 function 通常被写成一个“箭头函数” ,这基本上只是意味着转动这个:

function(input){
    //Do stuff
    return output;
}

into this:进入这个:

(input) => {
    //Do stuff
    return output;
}

It's very useful for writing quick little functions, so I'll use it in my example.它对于编写快速的小函数非常有用,所以我将在示例中使用它。

To filter the array using filter and arrow functions, all you have to do is this:要使用filter和箭头函数过滤数组,您所要做的就是:

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
var result = input.filter((number)=>{return number > 0});
console.log(result);
 for (var i=0; i<input.length; i++){

here you want to user input.length not cut.length, because you want i to go through all the indexes in the input array.在这里你想要用户 input.length 而不是 cut.length,因为你希望 i 到 go 通过输入数组中的所有索引。

You also forgot a brace to close the for loop您还忘记了一个大括号来关闭 for 循环

In addition you are returning from inside the loop, which means the loop is exited, so as soon as the first element is found, you will exit the function, so you'll only get one element in your liste.此外,您正在从循环内部返回,这意味着循环已退出,因此一旦找到第一个元素,您将退出 function,因此您只会在列表中获得一个元素。

Questions like these can be solved with googling a bit but for now, it seems like in your second expression, you have i<cut.length which doesn't make sense.像这样的问题可以通过谷歌搜索来解决,但就目前而言,在你的第二个表达式中,你有i<cut.length这没有意义。 You have to change it to i < input.length because you want to iterate through the input.您必须将其更改为i < input.length因为您想遍历输入。 You also can't have a return statement because you will exit out of the loop.您也不能有 return 语句,因为您将退出循环。 You can also use a higher order function like the filter function to return any number that is higher than 0. input.filter((num) => num > 0) Hope this helped!!您还可以使用更高阶的 function 像过滤器 function 来返回任何大于 0 input.filter((num) => num > 0)希望这有帮助!

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

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