像這樣:
function show (message)
{
alert(message.head);
// or
alert(message['head']); // Note the quotes
}
你調用它是好的。
要提供的默認設置,爲David points out,您可以使用curiously powerful ||
operator:
function show (message)
{
var head = message.head || 'error',
body = message.body || 'msg';
alert(head);
}
(以上是從大衛的做法,因爲它避免了改變已傳遞的message
對象,這通常不是略有不同一個好主意,因爲該功能不擁有該對象,調用者。)
這工作,因爲如果head
(例如)不是message
對象上的話,那就是falsey等head = message.head || 'error'
最終分配'error'
至head
。這是一個方便的技巧,但是有一個問題:如果head
已經有錯誤的值,並且這是有效的,那麼您不想使用||
技巧。相反,你可以使用in
檢查:
function show (message)
{
var head = 'head' in message ? message.head : 'error',
body = 'body' in message ? message.body : 'msg';
alert(head);
}
將使用從message
的值,如果它的存在,無論它是否是falsey。
相關,甚至是重複的:http://stackoverflow.com/questions/10813852/concise-way-to-accept-an-options-object-as-an-argument-falling-back-to-缺省 –