头尾计数器

时间:2018-10-03 20:20:08

标签: javascript arrays alert var

我正在尝试用javascript创建头尾系统。 我坚持尝试保持冲刷状态

到目前为止,我有:

   0.00169 started
  0.001821 n_workers: 5
  0.001833 throttle: 1
  0.002152 fetching https://httpbin.org/delay/4
     1.012 fetching https://httpbin.org/delay/2
     2.014 fetching https://httpbin.org/delay/2
     3.017 fetching https://httpbin.org/delay/3
      4.02 fetching https://httpbin.org/delay/0
     5.022 fetching https://httpbin.org/delay/2
     6.024 fetching https://httpbin.org/delay/2
     7.026 fetching https://httpbin.org/delay/3
     8.029 fetching https://httpbin.org/delay/0
     9.031 fetching https://httpbin.org/delay/0
     10.61 finished

我不确定自己在做什么错。 有什么建议吗?

谢谢

3 个答案:

答案 0 :(得分:0)

看来您正在混淆一些逻辑。

var arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

我假设0表示正面,1表示背面?

arr["Result"] = "heads";

这会将对象Result上的属性arr更改为等于字符串“ heads”,并且可能不是必需的。

let arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

let headCount = 0,
  tailCount = 0;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 0)
    headCount += 1;
  else
    tailCount += 1;
}

console.log("Heads: " + headCount + " " + "Tails: " + tailCount);

这将遍历数组,并根据该索引处数组的值递增计数变量之一。

答案 1 :(得分:0)

除了Eric H's answer之外,您还可以使用Array.reduce()array destructuring轻松获得相同的结果:

const arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

const [headCount, tailCount] = arr.reduce((r, n) => {
  r[n] += 1;
  
  return r;
}, [0, 0]);


console.log("Heads: " + headCount + " " + "Tails: " + tailCount);

答案 2 :(得分:0)

let arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

let headCount = 0, tailCount = 0;

arr.forEach(value => value ? headCount+=1 : tailCount+=1)

console.log(
  `HeadCount: ${headCount}  
TailCount: ${tailCount}`)