我面臨一個問題,即某些物件中的物件串列中的值僅包含來自最后一個物件的值。
我在這里做的是我想根據不同的標準為位置分配分數(因此,我也有一個標準串列)。為簡單起見,我為標準分數分配了一個亂數。
以下是生成串列的輸出,其中totalScore應該是串列中所有scores的總和criteriaScore。請觀察的所有值score中criteriaScore的Location 1,Location 2現在基礎上score的價值觀Location 3(其中還包含了正確的totalScore,請參閱該輸出下面的代碼
[
{
name: 'Location 1',
score: {
totalScore: 113,
criteriaScore: [
{
description: 'Desc. of Criteria 1 ....',
score: 31
},
{
description: 'Desc. of Criteria 2 ...',
score: 29
},
{
description: 'Desc. of Criteria 3 ...',
score: 49
}
]
}
},
{
name: 'Location 2',
score: {
totalScore: 52,
criteriaScore: [
{
description: 'Desc. of Criteria 1 ....',
score: 31
},
{
description: 'Desc. of Criteria 2 ...',
score: 29
},
{
description: 'Desc. of Criteria 3 ...',
score: 49
}
]
}
},
{
name: 'Location 3',
score: {
totalScore: 30,
criteriaScore: [
{
description: 'Desc. of Criteria 1 ....',
score: 31
},
{
description: 'Desc. of Criteria 2 ...',
score: 29
},
{
description: 'Desc. of Criteria 3 ...',
score: 49
}
]
}
}
]
這是產生上述輸出的代碼。有人可以解釋我在這里做錯了什么嗎?提前致謝。
// criteria list on which the assessment of locations will be performed
// this initially contains only description
let criteriaList = [
{
description: 'Desc. of Criteria 1 ....'
},
{
description: 'Desc. of Criteria 2 ...'
},
{
description: 'Desc. of Criteria 3 ...'
}
];
// names of locations which will be scored based on above criteria list
let locationList = [
{
name: 'Location 1'
},
{
name: 'Location 2'
},
{
name: 'Location 3'
}
];
const calcAllLocationsScore = () => {
let locationScoreList = [];
locationList.forEach(location => {
locationScoreList.push({
...location,
score: calcLocScore()
});
});
return locationScoreList;
};
const calcLocScore = () => {
let locScore = {
totalScore: 0,
criteriaScore: [] // each time the criteriaScore is initialized to empty list
}
let index = 0;
criteriaList.forEach(criteria => {
criteria.score = Math.floor((Math.random() * 50) 0); // add score key and just assign the random score for simplicty to make sure different number is assigned for each critera
locScore.totalScore = criteria.score;
locScore.criteriaScore.push(criteria); // add the criteria score object to criteriaScore list
});
return locScore;
};
// and finally when this function is called, the list of locations with the scores is produced containing actual ```totalScore``` but ```criteriaScore``` of all locations has value from the last location only
calcAllLocationsScore();
uj5u.com熱心網友回復:
您在criteriaList 中有3 個條件,并且您不斷覆寫3 個位置中每個位置的這些條件項中的分數。您的criteriaScore 陣列包含對這 3 個(并且只有 3 個)標準的參考,因此您將看到相同的最終 3 個分數集。
如下更改您的標準串列回圈。每次創建新標準:
criteriaList.forEach(criteria => {
const newcriteria = {...criteria};
newcriteria.score = Math.floor((Math.random() * 50) 0);
locScore.totalScore = newcriteria.score;
locScore.criteriaScore.push(newcriteria);
});
不清楚的一件事是,當組成分數為 31、29、49(總計 109)時,為什么您示例中的最終 totalScore 值為 30。我假設這實際上并不是真正的輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359920.html
標籤:javascript 数组 目的
上一篇:識別cypress中的web元素
