简体   繁体   English

我无法理解这段代码是如何工作的

[英]I can't understand how this code works

I am facing trouble understanding how exactly does the code return a value to randFace();我在理解代码究竟是如何将值返回给 randFace() 时遇到了麻烦;

I have understood the use of rand(0,5), so that it can randomly generate a number which happens to be the length of the ["crown", "anchor",..] array.我已经理解了 rand(0,5) 的用法,因此它可以随机生成一个数字,该数字恰好是 ["crown", "anchor",..] 数组的长度。

I cannot understand the working of the code.我无法理解代码的工作原理。 Let's say, rand(0,5) returns 3 as a number, then I do get the idea that randFace() would return "spade", but how?假设 rand(0,5) 以数字形式返回 3,那么我确实知道 randFace() 会返回“黑桃”,但是如何?

function rand(m, n) {
return m + Math.floor((n - m + 1)*Math.random());
}

// randomly returns a string representing one of the six
// Crown and Anchor faces

function randFace() {
return ["crown", "anchor", "heart", "spade", "club", "diamond"]
[rand(0, 5)];
}

Here's your code, rewritten for easier understanding.这是您的代码,为了更容易理解而重写。 Does the same thing.做同样的事情。 Only extracted two variables and gave them names.只提取两个变量并给它们命名。

function randFace() {
  var faces = ["crown", "anchor", "heart", "spade", "club", "diamond"];
  var faceIndex = rand(0, 5);
  return faces[faceIndex];
}

When you do array[index] , you will get element at position index in that array.当您执行array[index] ,您将在该数组中的位置index处获得元素。 If there is not element, undefined will be returned as default.如果没有元素,则默认返回undefined

You code is a shorter version of something like this:您的代码是类似以下内容的较短版本:

 function rand(m, n) { return m + Math.floor((n - m + 1) * Math.random()); } function randFace(m,n) { var array = ["crown", "anchor", "heart", "spade", "club", "diamond"]; var index = rand(m,n); return array[index] } console.log(randFace(0,5)) console.log(randFace(10,15))

So when you do functionName(args) , function will be called first and the output will be passed to parent scope.因此,当您执行functionName(args) ,将首先调用 function 并将输出传递给父作用域。 So when you do [...][rand(0,5)] , first rand(0,5) will execute.因此,当您执行[...][rand(0,5)] ,第一个rand(0,5)将执行。

The output will be used as index value to fetch element in array.输出将用作索引值以获取数组中的元素。

As correctly commented by @ sergio tulentsev , in following line正如@ sergio tulentsev正确评论的那样,在以下行中

return ["crown", "anchor", "heart", "spade", "club", "diamond"][rand(0,5)]

order of execution would be执行顺序是

  1. initialize array: ["crown", "anchor", "heart", "spade", "club", "diamond"]初始化数组: ["crown", "anchor", "heart", "spade", "club", "diamond"]
  2. Then rand(0,5) and output will be passed to second []然后rand(0,5)和输出将传递给第二个[]
  3. Second [] will be executed and element will be fetched第二个[]将被执行并获取元素
  4. fetched value will be returned.获取的值将被返回。

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

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