[英]Index an object multiple levels deep with one variable
我有一個對象:
object.day.time
我需要在其中訪問時間屬性。
由於函數的性質,我只能訪問基礎對象。 IE瀏覽器
function access(property){
let item = object[property]
// Do a lot of stuff with item
}
我不想重寫該函數,因為主要用例是訪問一級對象。 IE一天的財產。 有什么辦法可以使這項工作嗎?
我唯一能想到的是:
property = [['day']['time']]
但這沒用。
編輯:我最初有對象作為訪問這是錯誤的參數。 在這種情況下,我可以將object.day作為值傳遞
您可以在以下time
執行以下操作以轉到time
屬性:
var object = { day: { time: (new Date()).getTime() } }; var properties = ["day","time"]; function access(object,properties){ for(var index=0; index < properties.length; index++){ // go to deeper into object until your reached time object = object[properties[index]]; } // here we have reached time and can do something with it or just returning it return object; } console.log(access(object,properties));
希望這對您有所幫助。
調用此函數時,傳遞object.day而不是僅傳遞基礎對象,這意味着函數中的對象已經是object.day,因此,如果執行object.time,則應獲取該值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.