3

I have a code like this :

var width = [];

$.ajax({
   url : "http://xxx.xxx.xxx" ,
   type : "Get",
   dataType: "json",
   async   : true,
   success : function(data){
       for (var index in data)
       {
           var options = data[index].option;
           var position = (++index);
           width[index] = new Array();
           for (var keys in options)
           {
              width[index][keys] = options[keys].votes;
           }
       }
   }
});

in the chrome browser, it works fine, but in the safari, the error look likes:

TypeError: undefined is not an object (evaluating 'width[index][keys] = options[keys].votes')

But if I open debug mode in safari, there is no error, so what's the problem in this code?

angelcool.net
  • 2,505
  • 1
  • 24
  • 26
linbob
  • 45
  • 5
  • Are you saying that the error disappears if you open the debug tools in safari? Or just that there's no other additional error being reported? – James Thorpe May 09 '16 at 15:14
  • Once, you use jQuery why do you mix it with pure javascrtipt? Just a question. – vaso123 May 09 '16 at 15:15
  • 3
    @lolka_bolka jQuery is JavaScript. Why would you replace any of their "pure JavaScript" stuff with jQuery helpers? All they're using is a couple of for-in loops. – Mike Cluck May 09 '16 at 15:17
  • 1
    What kind of data is options[keys].votes? – nurdyguy May 09 '16 at 15:20
  • Probably you've got some polyfills in Safari? See [How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop](http://stackoverflow.com/q/13296340/1048572) – Bergi May 09 '16 at 15:21
  • 3
    Start off with iterating arrays with a regular for loop ([no for..in](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea)). – A1rPun May 09 '16 at 15:21
  • If i open debug tools in safari, thers is no error and no other additional error being reported, but If I close the debug tools and refresh, the error will appears. – linbob May 09 '16 at 15:23
  • You're incrementing the loop counter inside the loop (`++index`). Don't do that. – Reinstate Monica Cellio May 09 '16 at 15:44
  • What does `data` contain? Please provide an example. – trenthaynes May 09 '16 at 19:25
  • As @Archer pointed out - you are incrementing your loop variable `index` while using it inside the loop. – trenthaynes May 09 '16 at 19:27

1 Answers1

0

I change my for loop code like this:

    for (var index = 0;index < data.length;index++) {
        var options = data[index].option;
        var position = index + 1;
        width[index] = new Array();
        for (var keys = 0; keys < options.length; keys++) {
            width[index][keys] = options[keys].votes;
        }
    }

there is no error in any browser.

linbob
  • 45
  • 5