2013-10-17 33 views
0

我在API數組有點麻煩。基本上我只想顯示來自API數組的信息的第一個對象。我一直在玩Slice()和substr()函數,並沒有設法讓它工作。我做了一個fiddle來表明你想要我的意思。有點幫助w/Javascript數組

HTML:

<h3>Wind Speed:</h3><div class='speed'></div> <br> 
<h3>Wind Direction:</h3><div class='thug'></div><br> 
<h3>Wave Height:</h3><div class='test'></div><br> 
<h3>Ignore:</h3><div class='wave'></div><br> 

JS:

var url = 'http://magicseaweed.com/api/CP86f5quQqmB1fpW2S3bZVUCS8j1WpUF/forecast/?spot_id=1323' 

$.ajax({ 
    dataType: "jsonp", 
    url: url 
}).done(function(data) { 
    console.log(data); 
    sum = 0; 

    //---Wind Speed---------------------------------- 
    $.each(data, function(){ 
     sum += this.wind.speed; 
    }); 
    $('.speed').html(sum/data.length + data[0].wind.unit); 



    //---Ignore---------------------------------- 
    $.each(data, function(){ 
     sum += this.swell.maxBreakingHeight; 
    }); 
    $('.wave').html(sum); 


    //---Wave Height---------------------------------- 

    $.each(data, function(){ 
     $('.test').append('<p>' + this.swell.maxBreakingHeight + '</p>'); 
    }); 


    //---Wind Direction---------------------------------- 

    $.each(data, function(){ 
     sum += this.wind.compassDirection ; 
    }); 

    var numbers = sum; 
    $('.thug').append('<p>' + numbers.slice(3,4) + '</p>'); 
}); 

在本例中,我只希望它顯示所述第一數量,其在這種情況下是 '4'。我真的很感激,如果有人可以幫助我,我相當新的Javascript和我一直在撓我的頭很久了!

感謝

+0

請在您的問題所有相關的代碼。不僅提供鏈接 – musefan

+0

如果小提琴有提供鏈接... –

+0

甚至沒有鏈接。 – Andy

回答

0

爲了讓您的值的平均值,你可以做,

//---Wave Height---------------------------------- 
    var averageMaxBreakingHeight=0; 
    var numberOfValues=0; 
    $.each(data, function(){ 
     averageMaxBreakingHeight+=parseFloat(this.swell.maxBreakingHeight); 
      numberOfValues++; 
     /*$('.test').append('<p>' + this.swell.maxBreakingHeight + '</p>'); */ 
    }); 
    averageMaxBreakingHeight=averageMaxBreakingHeight/numberOfValues; 
    $('.test').append('<p>'+averageMaxBreakingHeight+'</p>'); 


    //---Wind Direction---------------------------------- 

//下面的數字變量可以是你需要的是即averageMaxBreakingHeight

如果任何變量你只需要十進制數的單位,然後你可以做,

numbers.substr(0,numbers.indexOf('.')) 

圍捕,

Math.round(parseFloat(numbers)); 

爲了圓您的人數達小數點後兩位做,

Math.round(parseFloat(numbers) * 100)/100;