我有物件,鍵是日期,點之前是月份,之后是年份:
const dataObj = {
'01.2015': 0.01,
'02.2015': 0.10,
'03.2015': 0.05,
'04.2015': 0.25,
// ...
}
該函式需要兩個日期并回傳一個陣列,其中包含來自 dataObj 的值的物件
interface Point {
date: string;
value: number;
}
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type Day = `${Digit}${Digit}`;
type Month =
| '01'
| '02'
// ...
| '11'
| '12';
type Year = '2015' | '2016' | '2017';
type DateString = `${Day}.${Month}.${Year}`;
type MonthDateString = `${Month}.${Year}`;
function count(firstDate: DateString, secondDate: DateString): Point[] {
const result: Point[] = [];
let currentDate = firstDate.slice(3) as MonthDateString;
// loop through dataObj and push in result
return result // [{date: '01.2015', value: 0.01}, {...}, ...]
}
如何回圈通過dataObj?我試過for回圈
for(let i = currentDate; i !== secondDate.slice(3); )
但不知道如何處理最終運算式,如何更新計數器變數,從 dataObj 傳遞下一個鍵(帶日期的字串)。
uj5u.com熱心網友回復:
關于預期的輸出有些混亂。該函式count需要回傳一個Point陣列,該陣列是一個物件陣列,其中每個物件都有兩個道具,即date(一個字串)和value(數字,代碼中每個行內注釋的浮點數)。
假設OP需要找到鍵值對,dataObj使得鍵(即月-年)在firstDate和secondDate(count函式引數)之間。
基于這個假設,下面的代碼可以實作預期的目標(生成Point元素陣列)。
const isGreaterOrEqual = (dtOne: MonthDateString, dtTwo: MonthDateString) : Boolean => {
const getYear = (dt: MonthDateString) : string => dt.slice(3);
const getMonth = (dt: MonthDateString) : string => dt.substring(0, 2);
return ((getYear(dtOne) > getYear(dtTwo)) ||
(getYear(dtOne) === getYear(dtTwo) &&
getMonth(dtOne) >= getMonth(dtTwo)
)
);
};
function count(firstDate: DateString, secondDate: DateString): Point[] {
let beginDate = firstDate.slice(3) as MonthDateString;
let endDate = secondDate.slice(3) as MonthDateString;
return (
Object.entries(dataObj)
.filter(([k, v]) => isGreaterOrEqual(k as MonthDateString, beginDate) && isGreaterOrEqual(endDate, k as MonthDateString))
.map(([k, v]) => ({ date: k, value: v} as Point))
);
};
console.log(count( "01.01.2015" as DateString, "01.02.2015" as DateString));
TS游樂場:鏈接在這里
uj5u.com熱心網友回復:
下面的一些例子:
for (let key in dataObj) {
console.log(key, dataObj[key]);
}
for (let [key, value] of Object.entries(dataObj)) {
console.log(key, value);
}
如果您想擁有并更新計數器變數:
let keys = Object.keys(dataObj);
for (let i = 0; i < keys.length; i ) {
console.log(i, keys[i], dataObj[keys[i]]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450796.html
標籤:javascript 打字稿
