簡體   English   中英

Javascript - 用參數在函數中定義對象

[英]Javascript - define object in function with arguments

我正在構建一個大對象,最終將由一個單獨的庫處理。 對象中有重復的結構元素,它們采用不同的參數,所以我希望編寫一個函數,讓我稍微自動化這個過程。

function addTable(headline) {
    var table = { header: headline, ... }
}

但是當我嘗試訪問對象中的函數參數時出現錯誤。 也就是說,我不能在對象中使用headline 如何訪問這些參數? 或者這是錯誤的方法?

更新:

看起來這是處理對象的庫的問題,但其他的東西很奇怪。 如果我這樣做:

var table = { header: ""+headline+"" ... }

有用。 但我不明白。 headline""+headline+""都是字符串。 以空引號開頭和結尾的字符串與不以空引號開頭的字符串之間可能有什么區別?

您應該能夠訪問它們“如果它們被傳遞到方法中”,但是 undefined 也可以從調用者傳入。

使用 F12 工具檢查參數和調用堆棧

function addTable(headline) {
    // headline is undefined if its not passed
    // headline can also be passed in as null or undefined
    // headline == arguments[0];
    // if nothing is passed then arguments.length should equal 0
    // add a F12 breakpoint and inspect all arguments and the callstack
    var table = { header: headline, ... }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM