我如何计算特定键的数量,它在对象数组中有一个值? 例如:
myArray = [ {file:null}, {file:hello.jpg}, {file:hai.jpg}, {file:null}] ;
输出=文件2的计数。 输出为2,因为数组中有两个文件。 注意:我不想使用for循环。
答案 0 :(得分:0)
您可以迭代数组并检查文件是否为null:
@{
RenderBody();
}
答案 1 :(得分:0)
尝试使用for循环和if条件
var myArray = [ {file:null}, {file:'hello.jpg'}, {file:'hai.jpg'}, {file:null}] ;
var length = myArray.length - 1;
var count = 0;
for(var x = 0; x < length; x++) {
if(myArray[x].file !== null) {
count += 1;
}
}
console.log('File count is ' + count);
console.log('---------------Using array map-------------');
var mapCount = 0;
myArray.map(function(value, index) {
if(value.file)
mapCount += 1;
});
console.log('File count is ' + mapCount);
答案 2 :(得分:0)
尝试这种地图和过滤器的组合
myArray = [ {file:null}, {file:'hello.jpg'}, {file:'hai.jpg'}, {file:null}] ;
let result = myArray
.map(x => x.file)
.filter(x => x != null) // or simply x => x
.length;
console.log(result);