使用 JavaScript 获取数组中真/假值的数量?
javascriptweb developmentfront end technologyobject oriented programming
要获取数组中真/假值的数量,代码如下 −
var obj = [ { isMarried: true }, { isMarried: false }, { isMarried: true }, { isMarried: true }, { isMarried: false } ] function numberOfTrueValues(obj) { var counter = 0; for (var index = 0; index < obj.length; index++) { if (obj[index].isMarried === true) { counter++; } } return counter; } function numberOfFalseValues(obj) { var counter = 0; for (var index = 0; index < obj.length; index++) { if (obj[index].isMarried === false) { counter++; } } return counter; } console.log("Number Of true values=" + numberOfTrueValues(obj)); console.log("Number Of false values=" + numberOfFalseValues(obj));
要运行上述程序,您需要使用以下命令 −
node fileName.js.
这里,文件名是 demo318.js。
输出
这将产生以下输出 −
PS C:\Users\Amit\javascript-code> node demo318.js Number Of true values=3 Number Of false values=2