[英]How to delete dynamic property of an object?
我嘗試刪除對象的動態屬性。 問題是該屬性取決於一組鍵。 讓我們看看代碼:
let keys = ['23', 'test', '12']; // Example but this is dynamic
let temp = this.array;
keys.forEach(k => {
temp = temp[k];
});
delete temp;
我想刪除this.array ['23'] ['test'] ['12']。 但我收到一個錯誤:'嚴格模式下無法在標識符上調用刪除'。 怎么做 ?
我想刪除this.array ['23'] ['test'] ['12']
寫這個, delete this.array['23']['test']['12']
,會有效。 但是使用語法delete temp
,您沒有刪除屬性,而是嘗試刪除變量。 那不會飛。 即使在非嚴格模式下,它也不會改變this.array
對象,你只需要聲明一個變量並取消它。
使用循環,您應該提前停止一步以刪除屬性,而不是變量:
keys.forEach((key, index, arr) => {
if (index < arr.length - 1) {
temp = temp[key];
} else {
delete temp[key];
}
});
您可能無法刪除它,但可以將其設置為null
。 嘗試:
temp = null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.