Array of Array, JSON.stringify() giving empty array instead of entire object

后端 未结 4 1173
后悔当初
后悔当初 2020-12-17 02:26

Here\'s my array (from Chrome console):

\"array

Here\'s the pertinent part of code:

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 02:55

    Like all JavaScript objects, Arrays can have properties with string-based keys like the ones you're using. But only integer keys (or keys that can be cleanly converted to integers) are actually treated as elements of an Array. This is why JSON isn't catching your properties, and it's also why your Arrays are all reporting their length as zero.

    If you really need to use non-integer keys, you should be using plain Objects, not Arrays. This method has its own gotchas -for example, you need to be careful with for-in loops- but JSON will work the way you expect it to.

    var hours = {
        "Mon" : {
            "11h30" : "15h00",
            "18h30" : "21h30"
        }, 
        "Tue" : {},
        "Wed" : {
            "11h30" : "15h00",
            "18h30" : "21h30"
        }, 
        "Thu" : {},
        "Fri" : {},
        "Sat" : {},
        "Sun" : {
            "11h30" : "15h00",
            "18h30" : "21h30"
        }, 
    }
    

提交回复
热议问题