Using dot notation with number passed into function

前端 未结 1 698
余生分开走
余生分开走 2021-01-28 15:03

If I have an object and function

var obj {
    \"1234\": {\"example\": \"sample\"},
    \"5678\": {\"example\": \"sample\"}
}    

function example(num, str) {
          


        
相关标签:
1条回答
  • 2021-01-28 15:56

    Why do I have to write obj[num] instead of obj.num?

    Because obj[num] takes the value of num (for instance, 1234) and uses that value as the property name, but obj.num uses "num" (literally) as the property name. Brackets vs. dot is how the JavaScript parser knows when you're giving the property name literally (dot notation) or using an expression you want to use the result of (brackets notation).


    (Side note: Granted, when we do foo[1], we literally mean the property 1 in foo. But from the parser's perspective, we're effectively using an expression there.)

    0 讨论(0)
提交回复
热议问题