[removed] array.length returns undefined

后端 未结 5 1152
执念已碎
执念已碎 2020-12-23 19:29

I have a set of data that is being passed on by the PHP\'s json_encode function. I\'m using the jQuery getJSON function to decode it:



        
相关标签:
5条回答
  • 2020-12-23 19:44

    It looks as though it's not an array but an arbitrary object. If you have control over the PHP serialization, you might be able to change that.

    As raina77ow pointed out, one way to do this in PHP would be by replacing something like this:

    json_encode($something) 
    

    with something like:

    json_encode(array_values($something))
    

    But don't ignore the other answers here about Object.keys. They should also accomplish what you want if you don't have the ability or the desire to change the serialization of your object.

    0 讨论(0)
  • 2020-12-23 19:54

    One option is:

    Object.keys(myObject).length
    

    Sadly it not works under older IE versions (under 9).

    If you need that compatibility, use the painful version:

    var key, count = 0;
    for(key in myObject) {
      if(myObject.hasOwnProperty(key)) {
        count++;
      }
    }
    
    0 讨论(0)
  • 2020-12-23 20:02

    try this

    Object.keys(data).length
    

    If IE < 9, you can loop through the object yourself with a for loop

    var len = 0;
    var i;
    
    for (i in data) {
        if (data.hasOwnProperty(i)) {
            len++;
        }
    }
    
    0 讨论(0)
  • 2020-12-23 20:05

    An easy fix to this question is to add '[' in the start of your json file, and ending it with a ']'. This solved it for me.

    0 讨论(0)
  • 2020-12-23 20:06

    Objects don't have a .length property.

    A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:

    Object.keys(data).length;
    

    If you have to support IE 8 or lower, you'll have to use a loop, instead:

    var length= 0;
    for(var key in data) {
        if(data.hasOwnProperty(key)){
            length++;
        }
    }
    
    0 讨论(0)
提交回复
热议问题