我在下面有一個簡單的 for 回圈,我將在其中檢查具有空值的特定屬性。我想計算空值的總數并將它們存盤在一個變數中,該變數應該是 7。我一直將空值轉換為 0 或未定義。
const test = [
{
'theKey': null,
'theName': 'bill'
},
{
'theKey': null,
'theName': 'jon'
},
{
'theKey': null,
'theName': 'theo'
},
{
'theKey': null,
'theName': 'rich'
},
{
'theKey': null,
'theName': 'rigo'
},
{
'theKey': null,
'theName': 'cleo'
},
{
'theKey': null,
'theName': 'jill'
},
]
for (var i = 0; i < test.length; i ) {
const theValues = test[i]['theKey']
console.log(theValues)
}
我試過了...
console.log(theValues.length)
和
for (var i = 0; i < test.length; i ) {
const theValues = test[i]['theKey']
const theSum = _.sum(theValues)
// console.log(theValues)
console.log(theSum)
}
uj5u.com熱心網友回復:
使用for-loop:
const test = [ { 'theKey': null, 'theName': 'bill' }, { 'theKey': null, 'theName': 'jon' }, { 'theKey': null, 'theName': 'theo' }, { 'theKey': null, 'theName': 'rich' }, { 'theKey': null, 'theName': 'rigo' }, { 'theKey': null, 'theName': 'cleo' }, { 'theKey': null, 'theName': 'jill' } ];
let count = 0;
for (var i = 0; i < test.length; i ) {
if (test[i]['theKey'] === null) {
count ;
}
}
console.log(count);
使用Array#reduce:
const test = [ { 'theKey': null, 'theName': 'bill' }, { 'theKey': null, 'theName': 'jon' }, { 'theKey': null, 'theName': 'theo' }, { 'theKey': null, 'theName': 'rich' }, { 'theKey': null, 'theName': 'rigo' }, { 'theKey': null, 'theName': 'cleo' }, { 'theKey': null, 'theName': 'jill' } ];
const count = test.reduce((total, { theKey }) =>
theKey === null ? total 1 : total
, 0);
console.log(count);
uj5u.com熱心網友回復:
theValues不是陣列,它沒有長度。它也是for回圈本地的,所以你不能在回圈之后訪問它。
不需要陣列,只需增加一個計數器變數。
let nullCount = 0;
for (let i = 0; i < test.length; i ) {
if (test[i].theKey === null) {
nullCount ;
}
}
console.log(nullCount);
uj5u.com熱心網友回復:
const test = [
{
'theKey': null,
'theName': 'bill'
},
{
'theKey': null,
'theName': 'jon'
},
{
'theKey': null,
'theName': 'theo'
},
{
'theKey': null,
'theName': 'rich'
},
{
'theKey': null,
'theName': 'rigo'
},
{
'theKey': null,
'theName': 'cleo'
},
{
'theKey': null,
'theName': 'jill'
},
];
let count = 0;
for (var i = 0; i < test.length; i ) {
if(test[i]['theKey'] == null){
count ;
}
}
console.log(count);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359062.html
標籤:javascript 节点.js
上一篇:為什么我在使用videojs時將NaN作為視頻持續時間
下一篇:java.io.FileNotFoundException:/opt/tomcat/work/Catalina/localhost/ROOT/org/apache/jsp/index_jsp.clas
