简体   繁体   English

关于“函数调用其他函数”的问题

[英]A question about ' Functions Calling Other Functions'

enter image description here在此处输入图像描述

const percentageOfWorld2 = function (population) {
   return (population / 7900) * 100
};

let Koreapl = percentageOfWorld2(52);
let Japanpl = percentageOfWorld2(60);
let Chinapl = percentageOfWorld2(1441);

console.log(Koreapl, Japanpl, Chinapl);

const describePopulation = function (country, population) {
    return `${country} has ${population} million people, which is about ${percentageOfWorld2(population)}% of the world`
}
console.log(describePopulation('korea', 52));
console.log(describePopulation('Japan', 60));
console.log(describePopulation('China', 1441));

Hello.I'm new at coding world,And I've been working on this code.你好。我是编码世界的新手,我一直在研究这个代码。 and the image that I put on is the answer for this code, Either way I've got the same result.我贴上的图像就是这段代码的答案,无论哪种方式,我都得到了相同的结果。 with my code and the answer, I get that above one is better but could anyone explain more, why it's better to declare the const variables into the function?without just returning like what I did in my answer?用我的代码和答案,我知道上面的那个更好,但谁能解释更多,为什么最好将 const 变量声明到 function 中?而不像我在答案中所做的那样返回?

If this version is your function:如果这个版本是你的 function:

const describePopulation = function (country, population) {
    return `${country} has ${population} million people, which is about ${percentageOfWorld2(population)}% of the world`
}

then I like your answer better than the "correct" answer.那么我更喜欢你的答案而不是“正确”的答案。 It depends on what describePopulation is supposed to do.这取决于describePopulation应该做什么。 Is it supposed to both compute a description, and then, as a side effect, display that description to the console?它是否应该计算描述,然后作为副作用,将该描述显示到控制台? Or, is it simply meant to compute a description?或者,它只是为了计算描述?

IMHO, a function should do only one thing, and do that one thing well.恕我直言,function 应该只做一件事,并且做好一件事。 I prefer the implementation where describePopulation is meant to compute a description, and it is left for some other function to output that to the console.我更喜欢describePopulation用于计算描述的实现,它留给其他一些 function到 output 到控制台。 So, I like your version better.所以,我更喜欢你的版本。

As to using a variable only once, as someone mentioned in a comment, one very important aspect of programming is to make your code readable.至于只使用一次变量,正如有人在评论中提到的那样,编程的一个非常重要的方面是使您的代码可读。 Code is read much, much more than it is written.阅读代码的次数远远多于编写的代码。 Code is typically modified many, many times over its lifetime.代码通常在其生命周期内被多次修改。 Anything you can do to make your code easy to read and easy to understand at a glance is good.你可以做任何使你的代码易于阅读和一目了然的事情都是好的。 This includes using what others may view as "pointless" variables.这包括使用其他人可能认为“无意义”的变量。 They are not pointless if they make the meaning of what you are reading leap from the screen.如果它们使您正在阅读的内容的含义从屏幕上跳出来,它们并不是毫无意义的。

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

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