简体   繁体   English

循环通过Json对象

[英]Looping through Json object

I am trying to only print a unique value of 'sum' by doing a compare at the end of the loop, but I'm seeing that every time it does a compare it has already moved on to the next element and therefore when its comparing the two values they're always the same. 我试图通过在循环结束时进行比较来打印'sum'的唯一值,但我看到每次进行比较时它已经转移到下一个元素,因此当它进行比较时这两个值总是一样的。 Is there another way to do this? 还有另一种方法吗?

 $(document).ready(function(){
    $.getJSON('XML.php', function(data) {
        JSON.stringify(data);
        var prevCardCode = '';

        $.each( data, function(index, element){
            var prevCardCode = element['CardCode'];

            if (!(element['CardCode'] == prevCardCode)) {

                var sum = element['payment_sum'] + '<br/>';
                $('#showdata').append(sum);
                }
                alert(element['CardCode'] + 'compare' + prevCardCode);
        });

    });
});

You need to move the prevCharCode assignment to the end of the loop and remove the var in front of it: 您需要将prevCharCode赋值移动到循环的末尾并删除它前面的var

var prevCardCode = '';
$.each( data, function(index, element) {
    if (!(element['CardCode'] == prevCardCode)) {
        // your code...
    }

    prevCardCode = element['CardCode'];
});

The var keyword doesn't belong within the each in this case, and you need to move it to after the comparison. 在这种情况下, var关键字不属于每个关键字,您需要在比较后将其移动到。

var prevCardCode = '';
$.each(data, function(index, element) {
    if (!(element['CardCode'] == prevCardCode)) {
        var sum = element['payment_sum'] + '<br/>';
        $('#showdata').append(sum);
    }
    alert(element['CardCode'] + 'compare' + prevCardCode);
    prevCardCode = element['CardCode'];
});​

If the var is left in place before prevCardCode , it will never set the one defined outside of the $.each and will not carry over to the next iteration of $.each . 如果varprevCardCode之前prevCardCode ,它将永远不会设置在$.each之外定义的$.each并且不会转移到$.each的下一次迭代。

prevCardCode is not the precedent element but the current... Then you compare current with current... prevCardCode不是先前元素,而是当前...然后你将当前与当前比较......

If you want to compare precedent element with current, you should use a while or a do while. 如果要将先前元素与当前元素进行比较,则应使用while或do while。

var i = 1;
var precedentEl = array[0];

while (i < array.length) {

   // Do some stuff like compare current and precedent

   precedentEl = array[i];
   i++;
}

Secondly, you call XML.php which return json... It's sound strange... 其次,你调用返回json的XML.php ......这听起来很奇怪......

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

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