简体   繁体   English

Javascript:只返回一个空数组

[英]Javascript: Only returning an empty array

I'm tinkering with an answer to fizzbuzz that returns an array of the accrued integers and strings, but return is only returning an empty array.我正在修改 fizzbuzz 的答案,它返回一个累积整数和字符串的数组,但return只返回一个空数组。 I can print the array to console and that works just fine (ie, has all of my intended alterations).我可以将数组打印到控制台,效果很好(即,有我所有的预期更改)。 What am I missing conceptually?我在概念上缺少什么?

Code:代码:

function display(){
let fizzbuzz = [];

for (let i =1; i<=100; i++){

    let by3 = i%3==0; // i is divisble by 3
    let by5 = i%5==0; // i is divisible by 5
    let output="";


    if (by3){output+="Fizz";}
    if (by5){output+="Buzz";}
    if (output==="") {output = i;}
    fizzbuzz.push(output);
}

//console.log(fizzbuzz); 

return fizzbuzz; // will return an empty array. But why? 
}
display();

You are not displaying the output of the function display.您没有显示 function 显示器的 output。 You can do:你可以做:

window.onload = function() { console.log(display()); }

or you can do,或者你可以这样做,

window.onload = function() { let arrayFuzz = display(); console.log(arrayFuzz); }

Like above return is for functions.就像上面的 return 是函数一样。 Something like this:像这样的东西:

function runFizzBuzz() {
  let fizzbuzz = []

  for (let i = 1; i <= 100; i++) {

    let by3 = i % 3 == 0 // i is divisble by 3
    let by5 = i % 5 == 0 // i is divisible by 5
    let output = ""


    if (by3) { output += "Fizz" }
    if (by5) { output += "Buzz" }
    if (output === "") { output = i }
    fizzbuzz.push(output)
  }
  return fizzbuzz
}

const array = runFizzBuzz()
console.log(array)

Your function display() is working properly.您的 function display()工作正常。 Maybe try console.log(display()) at the end of the script so you can verify that it is indeed returning the array with some information.也许在脚本末尾尝试console.log(display()) ,这样您就可以验证它确实返回了包含一些信息的数组。 Also if you need the array for something else you can store it in another variable.此外,如果您需要该数组来做其他事情,您可以将其存储在另一个变量中。 ie. IE。 myArray = display()

WHOOPS.哎呀。 Thanks, guys.多谢你们。 As soon as the answers started coming in I realized that wasn't thinking straight.当答案开始出现时,我意识到这不是直截了当的想法。

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

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