![](/img/trans.png)
[英]Can I prevent accidental overwrite of local variables in TypeScript / JavaScript?
[英]How can I read/write local variables dynamically in JavaScript/TypeScript?
我對 angular 很陌生,想知道如何動態訪問LOCAL變量。 這是我面臨的情況:
我在IF 語句中聲明了 7 個對象:
if (...) {
const day1 = { date: null, total: 0 };
const day2 = { date: null, total: 0 };
const day3 = { date: null, total: 0 };
const day4 = { date: null, total: 0 };
const day5 = { date: null, total: 0 };
const day6 = { date: null, total: 0 };
const day7 = { date: null, total: 0 };
}
稍后在該 IF 語句中,我需要根據也在該 IF 語句中完成的計算為“total”鍵分配一個值。
現在,不要稍后在 IF 語句中執行類似的操作:
day1.date = ... ;
day2.date = ... ;
day3.date = ... ;
day4.date = ... ;
day5.date = ... ;
day6.date = ... ;
day7.date = ... ;
我想做這樣的事情來保持我的代碼整潔和高效(顯然,這不起作用):
for (let i = 1; i <= 7; i++) {
['day' + i].date = ... ;
}
如果全局聲明 7 個對象然后使用this['day' + i].date
,它會起作用。 但是在 IF 語句中本地聲明的對象,我不能使用這種語法。
我的問題如下:
謝謝您的支持。
改變這個:
if (...) {
const day1 = { date: null, total: 0 };
const day2 = { date: null, total: 0 };
const day3 = { date: null, total: 0 };
const day4 = { date: null, total: 0 };
const day5 = { date: null, total: 0 };
const day6 = { date: null, total: 0 };
const day7 = { date: null, total: 0 };
// ...
day1.date = ... ;
day2.date = ... ;
day3.date = ... ;
day4.date = ... ;
day5.date = ... ;
day6.date = ... ;
day7.date = ... ;
}
...對此:
// Declared in module scope:
type Day = { date: Date | null, total: number };
// Inside your function:
if( ... ) {
const days: Day[] = [
{ date: null, total: 0 },
{ date: null, total: 0 },
{ date: null, total: 0 },
{ date: null, total: 0 },
{ date: null, total: 0 },
{ date: null, total: 0 },
{ date: null, total: 0 }
];
//
for( let i = 0; i < 7; i++ ) {
days[i].date = ...
}
}
您也可以在循環中初始化days
:
const days: Day[] = [];
for( let i = 0; i < 7; i++ )
{
days[i] = { date: null, total: 0 };
}
如果您想繼續使用day1
、 day2
等,您可以命名對數組中元素的引用(但請記住,這些是對數組中 object值的引用,而不是數組索引的別名):
const day1 = days[0];
const day2 = days[1];
...盡管盡量不要讓您的基於 1 的日期編號與 JavaScript/TypeScript 基於 0 的數組索引相混淆。
eval
: 您可以使用eval()
操作本地人,但永遠不應該使用eval()
。 但是你可以這樣做:
if (...) {
const day1 = { date: null, total: 0 };
const day2 = { date: null, total: 0 };
const day3 = { date: null, total: 0 };
const day4 = { date: null, total: 0 };
const day5 = { date: null, total: 0 };
const day6 = { date: null, total: 0 };
const day7 = { date: null, total: 0 };
for (let i = 1; i <= 7; i++) {
const expr = 'day' + i + ' = ...;';
console.log( expr );
eval( expr );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.