要获取数组中真/假值的数量,代码如下-
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