function $(id){
return typeof id==='string'?document.getElementsById(id):id;
}
為什么還需要判斷id是不是等于string字符串 而不是直接返回document.getElementsById(id)
什么情況下它才不是字符串?
function $(id){
return typeof id==='string'?document.getElementsById(id):id;
}
為什么還需要判斷id是不是等于string字符串 而不是直接返回document.getElementsById(id)
什么情況下它才不是字符串?
2014-09-20
舉報
2014-09-23
如果傳入的參數(shù)是一個單純的數(shù)字,比如8,那么如果不做typeof類型的判斷,會執(zhí)行document.getElementById(8)這樣瀏覽器是會報錯的,所以要做個判斷,如果id是數(shù)字那么會直接返回數(shù)字本身。