我想重寫一個由d3.js提供的例子。原碼具有這樣的功能:JavaScript數組查詢
function interpolateValues(values, year) {
var i = bisect.left(values, year, 0, values.length - 1),
a = values[i];
if (i > 0) {
var b = values[i - 1],
t = (year - a[0])/(b[0] - a[0]);
return a[1] * (1 - t) + b[1] * t;
}
return a[1];
}
其中「值」是看起來像這樣的數組:
"income":[[1800,359.93],[1820,359.93],[1913,556.12],[1950,3363.02], etc.
但是,我們的數據存儲在不同的方式。不同的是「名」:[一年,價值] ...格式,我們的數據存儲在不同的方式,就像一個數據庫(樣本數據跟蹤):
{"region":"A","income":1178.0,"lifeExpectancy":788.0,"year":1800.0,"population":1292.0,"country":"Angola"},
{"region":"B","income":847.0,"lifeExpectancy":1183.0,"year":1800.0,"population":803.0,"country":"Benin"},
{"region":"A","income":798.0,"lifeExpectancy":765.0,"year":1801.0,"population":967.0,"country":"Angola"},
{"region":"B","income":1293.0,"lifeExpectancy":1497.0,"year":1801.0,"population":792.0,"country":"Benin"},
我期待更換interpolateValues()函數用不同的一個是這樣的:
SELECT income FROM dataset WHERE year = 1980
我知道這是SQL,我只是用它來嘗試和跨越的想法。 基本上你有一個數組的數組,一個有數年的數組,我正在尋找一個返回特定年份數據的函數。
插值功能應該很好,但現在不是太重要。問題在於我只是在學習使用js,而到目前爲止我所嘗試的任何東西都失敗了。
感謝您的幫助!
編輯:
我有這個功能,它的工作原理:
function provideData(year) {
return nations.map(function(d) {
return {
name: d.country,
region: d.region,
income: d.income,
population: d.population,
lifeExpectancy: d.lifeExpectancy
};
});
}
但是,正如你所期望的返回造成的輸出以及在整個陣列 澄清一些額外的信息一百年的數據。現在,只要有返回d.income如果d.year ==一年..
它看起來就像你不熟悉的命令性代碼範例。在JS中,你不告訴機器你想要得到什麼(如在SQL中),你告訴_how_來做它。因此,您需要定義新數組,在舊數組上運行循環,比較您的條件並推送到您想要的新陣列實體。插值是我猜想的一個不同的特徵。 – Tommi