简体   繁体   English

使用jquery.each无法遍历关联数组

[英]Cant iterate through an associative array using jquery.each

Well, I have used jquery.each before but today seems to be my bad day as whatever I am doing is going way wrong. 好吧,我之前使用过jquery.each ,但是今天似乎是我的糟糕日子,因为我所做的一切都出了问题。 I used the following to get the values from the array but I get 我使用以下代码从数组中获取值,但得到了

TypeError: invalid 'in' operand a TypeError:无效的“ in”操作数

JS JS

var updateBoard = function() {
        $.ajax({
            type: "POST",
            url: "engine/main.php",
            data: {code: 2},
            success: function(response) {
                $.each(response, function(i, val) {
                    console.log(i);
                });
                setTimeout(updateBoard, 2500);
            }
        });
    };
    updateBoard();

RESPONSE IN MY SUCCESS FUNCTION 对我的成功功能的回应

Array
(
    [0] => Array
        (
            [cell] => a2
            [sign] => ◯
        )

    [1] => Array
        (
            [cell] => b2
            [sign] => ◯
        )

)

each its work only on jQuery element but response isn't bind with jQuery selector so just use javascript loop like this 每个仅适用于jQuery元素,但响应未与jQuery选择器绑定,因此仅使用像这样的javascript循环

you can use map function of es6 or foreachfunction if your response is an array 如果响应为数组,则可以使用es6的map函数或foreachfunction

try : 尝试:

response.map(function(obj){
  console.log(obj)
})

or 要么

response.forEach(function(obj){
  console.log(obj)
})

source of MDN MDN的来源

foreach 的foreach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

map 地图

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Try with 试试看

var obj = JSON.parse(response);
$(obj).each(function(i, val) {
  console.log(val.cell);
  console.log(val.sign);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM