[英]Access value of a variable outside a function
我知道這個問題已經問了很多遍了,但是我仍然找不到任何解決方案! 這是我的代碼:我正在對一組加密貨幣的值進行編程,但是在嘗試創建圖形時被卡住了。
ajaxGet("https://api.coinmarketcap.com/v1/ticker/?limit=300", function (reponse) {
// Transforme la réponse en tableau d'objets JavaScript
var monnaie = JSON.parse(reponse);
$("#tableBody").empty();
var tr;
function page1(event) {
var timestamp = Math.round(new Date().getTime() / 1000);
console.log(timestamp);
for (var i = 0; i < 50; i++) {
ajaxGet("https://min-api.cryptocompare.com/data/histohour?fsym=" + monnaie[i].symbol + "&tsym=USD&limit=28&aggregate=6&toTs=" + timestamp, function (reponse2) {
var monnaieGraph = JSON.parse(reponse2)['Data'];
var points = '';
var maximum = Math.max.apply(Math,monnaieGraph.map(function(o){return o.high;}))
var minimum = Math.min.apply(Math,monnaieGraph.map(function(o){return o.low;}))
for (var j=0; j<=28; j++){
var moyenne = ((monnaieGraph[j].high)+(monnaieGraph[j].low))/2;
echelle = ((-100/(maximum-minimum))*(moyenne-minimum))+100;
points += (j*12) + ',' + echelle + '\n';
}
});
tr = $('<tr/>');
tr.append("<td>" + monnaie[i].rank + "</td>");
tr.append("<td>" + "<img class=imageCrypto src=logos/" + monnaie[i].symbol + ".png" + " " + "style=width:37.5px; height:37.5px;" + ">" + "<div class=nomCurr><a href=http://www.google.com/" + monnaie[i].id +">" + monnaie[i].name + "</a>" + "<div>" + monnaie[i].symbol + "</div></div></td>");
tr.append("<td>" + formatter.format(monnaie[i].price_btc) + " BTC" + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].price_usd) + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].market_cap_usd) + "</td>");
tr.append("<td>" + formatter.format(monnaie[i].available_supply) + " " + monnaie[i].symbol + "</td>");
if (Number(monnaie[i].percent_change_24h) > 0) {
tr.append("<td class=pourcentPositif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-up'" + "</td>");
//tr.append("<i class=fa fa-caret-up>" + "</i>");
}
else {
tr.append("<td class=pourcentNegatif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-down'" + "</td>");
}
tr.append('<td><svg viewBox="0 0 336 100" width=116 height=35><polyline fill=none stroke=#0074d9 stroke-width=6 points="' + points + '"/></svg></div>');
$('#tableBody').append(tr);
}
}
一切正常! 我得到了一個包含所有所需值的數組。
正如我所說,我正在嘗試為每種貨幣添加一列圖表! 我嘗試了3種不同的代碼,但沒有一個起作用! 以下是3個代碼以及每個結果的圖片:
for (var i = 0; i < 50; i++) {
ajaxGet("https://min-api.cryptocompare.com/data/histohour?fsym=" + monnaie[i].symbol + "&tsym=USD&limit=28&aggregate=6&toTs=" + timestamp, function (reponse2) {
var monnaieGraph = JSON.parse(reponse2)['Data'];
var points = '';
var maximum = Math.max.apply(Math,monnaieGraph.map(function(o){return o.high;}))
var minimum = Math.min.apply(Math,monnaieGraph.map(function(o){return o.low;}))
for (var j=0; j<=28; j++){
var moyenne = ((monnaieGraph[j].high)+(monnaieGraph[j].low))/2;
echelle = ((-100/(maximum-minimum))*(moyenne-minimum))+100;
points += (j*12) + ',' + echelle + '\n';
}
});
tr = $('<tr/>');
tr.append("<td>" + monnaie[i].rank + "</td>");
tr.append("<td>" + "<img class=imageCrypto src=logos/" + monnaie[i].symbol + ".png" + " " + "style=width:37.5px; height:37.5px;" + ">" + "<div class=nomCurr><a href=http://www.google.com/" + monnaie[i].id +">" + monnaie[i].name + "</a>" + "<div>" + monnaie[i].symbol + "</div></div></td>");
tr.append("<td>" + formatter.format(monnaie[i].price_btc) + " BTC" + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].price_usd) + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].market_cap_usd) + "</td>");
tr.append("<td>" + formatter.format(monnaie[i].available_supply) + " " + monnaie[i].symbol + "</td>");
if (Number(monnaie[i].percent_change_24h) > 0) {
tr.append("<td class=pourcentPositif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-up'" + "</td>");
//tr.append("<i class=fa fa-caret-up>" + "</i>");
}
else {
tr.append("<td class=pourcentNegatif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-down'" + "</td>");
}
tr.append('<td><svg viewBox="0 0 336 100" width=116 height=35><polyline fill=none stroke=#0074d9 stroke-width=6 points="' + points + '"/></svg></div>');
$('#tableBody').append(tr);
}
在我的“ for”循環中,我添加了ajaxGet,在其中創建了一個變量“ points”,該變量從針對該圖縮放的API中獲取值。
該代碼不起作用,出現錯誤:“未定義點”。
這是我的第二次嘗試:
for (var i = 0; i < 50; i++) {
tr = $('<tr/>');
tr.append("<td>" + monnaie[i].rank + "</td>");
tr.append("<td>" + "<img class=imageCrypto src=logos/" + monnaie[i].symbol + ".png" + " " + "style=width:37.5px; height:37.5px;" + ">" + "<div class=nomCurr><a href=http://www.google.com/" + monnaie[i].id +">" + monnaie[i].name + "</a>" + "<div>" + monnaie[i].symbol + "</div></div></td>");
tr.append("<td>" + formatter.format(monnaie[i].price_btc) + " BTC" + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].price_usd) + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].market_cap_usd) + "</td>");
tr.append("<td>" + formatter.format(monnaie[i].available_supply) + " " + monnaie[i].symbol + "</td>");
if (Number(monnaie[i].percent_change_24h) > 0) {
tr.append("<td class=pourcentPositif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-up'" + "</td>");
//tr.append("<i class=fa fa-caret-up>" + "</i>");
}
else {
tr.append("<td class=pourcentNegatif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-down'" + "</td>");
}
ajaxGet("https://min-api.cryptocompare.com/data/histohour?fsym=" + monnaie[i].symbol + "&tsym=USD&limit=28&aggregate=6&toTs=" + timestamp, function (reponse2) {
var monnaieGraph = JSON.parse(reponse2)['Data'];
var points = '';
var maximum = Math.max.apply(Math,monnaieGraph.map(function(o){return o.high;}))
var minimum = Math.min.apply(Math,monnaieGraph.map(function(o){return o.low;}))
for (var j=0; j<=28; j++){
var moyenne = ((monnaieGraph[j].high)+(monnaieGraph[j].low))/2;
echelle = ((-100/(maximum-minimum))*(moyenne-minimum))+100;
points += (j*12) + ',' + echelle + '\n';
}
tr.append('<td><svg viewBox="0 0 336 100" width=116 height=35><polyline fill=none stroke=#0074d9 stroke-width=6 points="' + points + '"/></svg></div>');
});
$('#tableBody').append(tr);
}
這次,我在ajaxGet中添加了該列的創建。 這些圖還可以,但是它們僅顯示為一行,位於最后一行!
這是我最后的嘗試:
for (var i = 0; i < 50; i++) {
ajaxGet("https://min-api.cryptocompare.com/data/histohour?fsym=" + monnaie[i].symbol + "&tsym=USD&limit=28&aggregate=6&toTs=" + timestamp, function (reponse2) {
var monnaieGraph = JSON.parse(reponse2)['Data'];
var points = '';
var maximum = Math.max.apply(Math,monnaieGraph.map(function(o){return o.high;}))
var minimum = Math.min.apply(Math,monnaieGraph.map(function(o){return o.low;}))
for (var j=0; j<=28; j++){
var moyenne = ((monnaieGraph[j].high)+(monnaieGraph[j].low))/2;
echelle = ((-100/(maximum-minimum))*(moyenne-minimum))+100;
points += (j*12) + ',' + echelle + '\n';
}
tr = $('<tr/>');
tr.append("<td>" + monnaie[i].rank + "</td>");
tr.append("<td>" + "<img class=imageCrypto src=logos/" + monnaie[i].symbol + ".png" + " " + "style=width:37.5px; height:37.5px;" + ">" + "<div class=nomCurr><a href=http://www.google.com/" + monnaie[i].id +">" + monnaie[i].name + "</a>" + "<div>" + monnaie[i].symbol + "</div></div></td>");
tr.append("<td>" + formatter.format(monnaie[i].price_btc) + " BTC" + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].price_usd) + "</td>");
tr.append("<td>" + "$ " + formatter.format(monnaie[i].market_cap_usd) + "</td>");
tr.append("<td>" + formatter.format(monnaie[i].available_supply) + " " + monnaie[i].symbol + "</td>");
if (Number(monnaie[i].percent_change_24h) > 0) {
tr.append("<td class=pourcentPositif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-up'" + "</td>");
//tr.append("<i class=fa fa-caret-up>" + "</i>");
}
else {
tr.append("<td class=pourcentNegatif>" + Number(monnaie[i].percent_change_24h) + "%" + "<i class='fa fa-caret-down'" + "</td>");
}
tr.append('<td><svg viewBox="0 0 336 100" width=116 height=35><polyline fill=none stroke=#0074d9 stroke-width=6 points="' + points + '"/></svg></div>');
$('#tableBody').append(tr);
});
}
我在ajaxGet內添加了整個表的聲明! 我不明白結果:這次,圖形是我想要的,但是數組的其余部分(每行中的每一列)具有第51個硬幣的值(但是“ graphs”列有效),而我的變量我應該是0
希望我的問題很清楚,對不起,我無法發布圖片...謝謝您的時間!
我認為,如果您更改以下內容,則三個代碼段中的第一個應該起作用:
points
變量的范圍僅限於您提供給ajaxGet
函數的回調函數。 因此,當您嘗試在構建表時使用它時,將無法訪問它。 這就是為什么您points is not defined
錯誤points is not defined
。 在您的for循環范圍內聲明points
變量以解決此問題。
在構建點時,您用 \\n
分隔點對,在這種情況下,我不確定該點對是否適用於SVG代碼。也許嘗試用空格分隔。
SVG圖像未顯示的問題是因為顯然您必須重新加載生成的實際HTML才能在瀏覽器中呈現SVG圖像。 看到這個相關的答案 。 根據您的情況,每次添加一行后,都應重新加載表的HTML。 使用jQuery看起來像這樣:
// Row creation logic...
$('#tableBody').append(tr);
$("#tableBody").html($("#tableBody").html());
function getTimestamp() {
return Math.round(new Date().getTime() / 1000);
}
function getAveragePrice(pricepoint) {
return (pricepoint.high + pricepoint.low) / 2;
}
function getPointMap(min, max) {
return function (price, index) {
var range = max - min;
var offset = price - min;
var value = 100 - (offset * 100 / range);
return `${index * 12},${value}`;
}
}
function getPoints(prices) {
var min = Math.min(...prices);
var max = Math.max(...prices);
var points = prices.map(getPointMap(min, max));
return points.join(" ");
}
function getSvg(points) {
var line = $('<polyline/>');
line.attr("fill", "none");
line.attr("stroke", "#0074d9");
line.attr("stroke-width", 6);
line.attr("points", points);
var svg = $('<svg/>');
svg.attr("viewBox", "0 0 336 100");
svg.attr("width", 116);
svg.attr("height", 35);
svg.append(line);
return svg;
}
function getCell(content) {
return $("<td/>").append(content);
}
function getRow(coin, points) {
// Set id to SortOrder provided by API so
// we can use it to add the rows to the
// table in the right order.
var tr = $('<tr/>');
tr.attr("id", coin.SortOrder);
tr.append(getCell(coin.SortOrder));
tr.append(getCell(coin.CoinName));
tr.append(getCell(`${coin.TotalCoinSupply}`));
tr.append(getCell(getSvg(points)));
return tr;
}
function addRow(row, table)
{
var current = table.children().first();
// While there is a next row
while(current.is("tr")) {
// Check if the rank of current row is
// larger than the rank of the row we
// want to add.
if(Number(current.attr("id")) > Number(row.attr("id"))) {
// If true, add the row before the
// current row and we are done.
current.before(row);
return;
}
// Else check the next row.
current = current.next();
}
// If the table does not contain rows yet or
// the end of the table is reached without
// finding larger ranks, just add the row at
// the end.
table.append(row);
}
function getHistoryCallback(table, coin) {
return function (history) {
var prices = history.Data.map(getAveragePrice);
var points = getPoints(prices);
var row = getRow(coin, points);
addRow(row, table);
table.html(table.html());
}
}
function sortCoins(a, b) {
return a.SortOrder - b.SortOrder;
}
function getCoinsCallback(table) {
return function (coinlist) {
var coins = Object.values(coinlist.Data).sort(sortCoins);
table.empty();
for (var i = 0; i < 10; i++) {
var coin = coins[i];
var url = "https://min-api.cryptocompare.com/data/histohour";
var data = {
fsym: coin.Symbol,
tsym: "USD",
limit: 28,
aggregate: 6,
toTs: getTimestamp()
};
var callback = getHistoryCallback(table, coin);
$.getJSON(url, data, callback);
}
}
}
function populateTable(table_id) {
var table = $(`#${table_id}`);
var url = "https://min-api.cryptocompare.com/data/all/coinlist";
var callback = getCoinsCallback(table);
$.getJSON(url, callback);
}
$(document).ready(function () {
populateTable("tableBody");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.