Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - When I store the function in a variable, it prints out a slightly different result? ("undefined" thrown in at the end)

I'm self-studying JavaScript and new to functions. I'm playing around with it and the results of one I made confuse me a bit--please see my code below. The first time my function is run, it spells out "cat" as "c", "a", "t" in the console. That makes sense to me. But when I store it in a variable and call that variable, it does the same exact thing but with "undefined" at the end. Shouldn't the results be the same? I don't understand how there is "undefined" when you call a function via a variable. I'd really appreciate any help to explain this.

function printCat(x) {
  for (i = 0; i < x.length; i++) {
    console.log(x[i])
  }
}

printCat("cat")

var func1 = printCat

console.log(func1("cat"))
question from:https://stackoverflow.com/questions/65884724/when-i-store-the-function-in-a-variable-it-prints-out-a-slightly-different-resu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The output is the same. It prints cat. undefined is being printed by the last console.log(). When you print console.log('A'), it prints 'A'. As you are trying to console.log(function), it prints undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...