我的代碼有問題。jk = P
我想顯示記錄總和jk = L
const JK = ["L", "P"];
const data = [{
"name": "Faris",
"jk": "L"
}, {
"name": "Nanda",
"jk": "P"
}, {
"name": "Ani",
"jk": "P"
}]
var b = []
for (var a = 0; a < JK.length; a ) {
for (var i = 0; i < data.length; i ) {
if (data[i].jk == JK[a]) b.push(data[a] = 1)
}
}
console.log(b);
我想b = [1, 2]
uj5u.com熱心網友回復:
b.push(data[a] = 1)
在這里不起作用。您需要將陣列元素設定在最好在開始時完成的位置,然后您可以添加到它們。嘗試創建一個長度為 0 的陣列JK
var b = Array(JK.length).fill(0)
然后您可以使用給定的索引添加到該陣列
if (data[i].jk == JK[a]) { b[a] = 1 }
uj5u.com熱心網友回復:
筆記
好的,我想我明白你想要做什么。您想遍歷資料串列并計算存在多少“jk”型別。
JS
const dataList = [
{ "name": "Faris", "jk": "L" },
{ "name": "Nanda", "jk": "P" },
{ "name": "Ani", "jk": "P" }
];
const counts = {};
const selectKey = 'jk';
// Loop through each item in dataList
for ( const item of dataList ){
// Skip item if it is missing or missing the needed key
if ( !item || !item[ selectKey ] ) continue;
// initialize counts if first time accessing
if ( !counts[ item[ selectKey ] ] ) counts[ item[ selectKey ] ] = 0;
// increment key count
counts[ item[ selectKey ] ] ;
}
console.log( 'counts object', counts ); // Result = {L: 1, P: 2}
console.log( 'counts array', [ counts.L, counts.P ] ); // Result = [ 1, 2 ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523807.html