JavaScript操作顺序

时间:2015-09-23 14:30:41

标签: javascript

我正在尝试从对象中检索信息,但我似乎无法以正确的顺序获取信息。这样做,total始终等于null

如何确保在计算平均值之前始终填充total

你可以看到here y仍未定义

$(function () {
    var data =[];
    var time =[];
    var abc =[
        {"val":"2015-07-02 03:55:00","name":"TIME_STAMP"},
        {"val":"19981","name":"TOTAL"},
        {"val":"2051","name":"\"A\""},
        {"val":"274","name":"\"B\""},
        {"val":"8826","name":"\"C\""},
        {"val":"5351","name":"\"D\""},
        {"val":"2628","name":"\"E\""},
        {"val":"501","name":"\"F\""},
        {"val":"350","name":"\"G\""},
        {"val":" ","name":"\"H\" "}];
    var total = null;

    $.each(abc,function(i,el){
        if (el.name == "TIME_STAMP") {
            time.push({ name: el.name, y: parseInt(el.val) });
        }
        else if (el.name == "TOTAL") {
            total = parseInt(el.val);
        }
        else if (total != null) {
            var p = parseFloat(el.val) / total * 100;
            data.push({name: el.name, y: p});
            console.log(el.name + " " + el.y);
        }
    });
 });

2 个答案:

答案 0 :(得分:0)

更改此行...

console.log(el.name + " " + el.y);

到此......

console.log(el.name + " " + p);

没有el.y

或者,创建el.y而不是p ...

$.each(abc,function(i,el){
    if (el.name == "TIME_STAMP") {
        time.push({ name: el.name, y: parseInt(el.val) });
    }
    else if (el.name == "TOTAL") {
        total = parseInt(el.val);
    }
    else if (total != null) {
        el.y = parseFloat(el.val) / total * 100;
        data.push({name: el.name, y: el.y});
        console.log(el.name + " " + el.y);
    }
});

答案 1 :(得分:0)

添加此检查修复了它。

$.each(json, function(i,el){
        if (el.val != " "){
            if(el.name == "TIME_STAMP" || el.name == "TOTAL"){
                excess.push({name: el.name, y: parseInt(el.val)});
            }else{
                endData.push({name: el.name, y: parseInt(el.val)});
            }
        }
    });