有没有办法将数组中的项目用作布尔值? Node.js

Is there a way to use items in an array as booleans? Node.js

我正在 node.js 开发地牢爬虫。我想要一种优雅的方式来跟踪用户的结局。我在想,如果我可以拥有每个结局的数组,然后在实现该结局时将一个项目设置为 true,那会很好。这将使浏览列表并打印实现的结局然后计算完成百分比变得容易。

我的尝试:

var end1 = true
var end2 = true
var end3 = false
var end4 = true
var end5 = false

var endings = [end1, end2, end3, end4, end5]

function listEndings() {
  console.log("You have found these endings:")
  var total = 0

  for (let i = 0; i < endings.length; i++) {
    if (endings[i] = true) {
      console.log(String(endings[i]))
      total = total + 1
    }
  }

  console.log(`\nIn total you have ${total}/${endings.length + 1} endings. (${(total/(endings.length + 1))*100}%)`)
}

我想要的输出

You have found these endings:
end1
end2
end4

In total you have 3/5 endings. (60%)

是否可以使用这样的方法?您有其他推荐的方法吗?

非常感谢您的帮助!

我认为最好将值存储为一个数组来存储玩家已经找到的结局:

let endingsFound = []
const totalEndings = 5
//(as a side note, better use let than var)

console.log('Endings found')
//suppose we find endings three and four
endingsFound.push(3)
endingsFound.push(4)

endingsFound.forEach((end) => console.log(`Ending ${end}`))

console.log(`In total you have found ${endingsFound.length +1}/${totalEndings}`);

如果您仍然决定将其存储为布尔数组,则使用以下函数:

const indices = arr.reduce(
    (out, bool, index) => bool ? out.concat(index) : out, 
    []
  )

如所呈现的那样找到找到的结尾数组,然后执行相同的操作。

使用 object 代替 array 并使用 Object.entries 遍历 keyvalue 会简单直接想要的结果。

var end1 = true;
var end2 = true;
var end3 = false;
var end4 = true;
var end5 = false;

var endings = { end1, end2, end3, end4, end5 };

function listEndings() {
  let count = 0, entries = Object.entries(endings);
  
  console.log("You have found these endings:");
  for (let [k, v] of entries) {
    if (v) {
      console.log(`${k}`);
      ++count;
    }
  }

  console.log(
    `In total you have ${count}/${entries.length} endings. (${
      (count * 100) / entries.length
    }%)`
  );
}

listEndings();

在本例中,声明包含对象的数组变量。所以,你的数据是灵活的。如果您需要某些条件,您可以随时添加数据。

使用过滤器和映射函数创建这样的输出

var endings = [
{"no": 1,"bool": true},
{"no": 2,"bool": true},
{"no": 3,"bool": false},
{"no": 4,"bool": true},
{"no": 5,"bool": false},
{"no": 6,"bool": true},
{"no": 7,"bool": false}
]

var result = endings.filter((a)=>a.bool==true)
var resultMsg = result.map((a)=> `end${a.no}\n`)
var resultVal = parseInt((result.length/endings.length)*100)

console.log(`You have found these endings:\n ${resultMsg}`)
console.log(`\nIn total you have ${result.length}/${endings.length} endings. (${resultVal}%)`)