无法遍历通过数据传递的数组,但是当我创建完全相同的数组的变量时,它就可以工作

时间:2022-02-01 21:33:07

This is the array that's passed through to my ajax call:

这是传递给我的ajax调用的数组:

data.comments

data.comments

[['rwerw', '215', '/news/215/'], ['wrwerwer', '215', '/news/215/'], ['Woinfoqf', '215', '/news/215/'], ['Good', '215', '/news/215/'], ["He's good", '215', '/news/215/']]

If I do:

如果我做:

data.comments.forEach(function(a, index) {
          console.log('new', a);
        });

the forEach() does not work and I get this error in the console:

forEach()不起作用,我在控制台中收到此错误:

Uncaught TypeError: data.comments.forEach is not a function
  at Object.success (base.js:180)
  at i (jquery-2.2.1.min.js:2)
  at Object.fireWith [as resolveWith] (jquery-2.2.1.min.js:2)
  at z (jquery-2.2.1.min.js:4)
  at XMLHttpRequest.<anonymous> (jquery-2.2.1.min.js:4)

But if I make a variable of the exact same array, then it works:

但是,如果我创建一个完全相同的数组的变量,那么它的工作原理:

    var arr = [['rwerw', '215', '/news/215/'], ['wrwerwer', '215', '/news/215/'], ['Woinfoqf', '215', '/news/215/'], ['Good', '215', '/news/215/'], ["He's good", '215', '/news/215/']];

    arr.forEach(function(a, index) {
      console.log('new', a);
    });

console.log:

的console.log:

new ["rwerw", "215", "/news/215/"]
new ["wrwerwer", "215", "/news/215/"]
new ["Woinfoqf", "215", "/news/215/"]
new ["Good", "215", "/news/215/"]
new ["He's good", "215", "/news/215/"]

Any idea what the problem is?

知道问题是什么吗?

Edit: ajax call:

编辑:ajax调用:

$('#user_comments').on('click', function () {
    var user = $(this).data('user');

    $.ajax({
        type: 'GET',
        url: '/profile_comments/',
        data: {
            user: user
        },
        success: function (data) {
            console.log(data.comments);

            var arr = [['rwerw', '215', '/news/215/'], ['wrwerwer', '215', '/news/215/'], ['Woinfoqf', '215', '/news/215/'], ['Good', '215', '/news/215/'], ["He's good", '215', '/news/215/']];

            arr.forEach(function(a, index) {
              console.log('new', a);
            });

        }
    })


});

1 个解决方案

#1


-1  

data.comments is passed through as a string not an Array.

data.comments作为字符串而不是数组传递。

console.log(Array.isArray(data.comments)); // false
var data = $.makeArray(data.comments); 
console.log(Array.isArray(data)); // true

#1


-1  

data.comments is passed through as a string not an Array.

data.comments作为字符串而不是数组传递。

console.log(Array.isArray(data.comments)); // false
var data = $.makeArray(data.comments); 
console.log(Array.isArray(data)); // true