Javascript 函数外部变量的访问值
我知道这个问题已经问了很多次了,但我仍然找不到任何解决办法! 这是我的代码:我正在编写一个加密货币值数组,但当我试图创建图形时,我被卡住了Javascript 函数外部变量的访问值,javascript,Javascript,我知道这个问题已经问了很多次了,但我仍然找不到任何解决办法! 这是我的代码:我正在编写一个加密货币值数组,但当我试图创建图形时,我被卡住了 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)
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,在其中我创建了一个变量点,该变量点从为图形缩放的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个硬币的值,但是图形列可以工作,而我的变量I应该是0
希望我的问题是清楚的,我很抱歉我不能发布图片。。。
谢谢你抽出时间 如果您更改以下内容,我认为三个代码片段中的第一个应该可以工作: points变量的范围仅限于提供给ajaxGet函数的回调函数。因此,当您在构建表时尝试使用它时,无法访问它。这就是为什么没有定义错误点的原因。在for循环的范围内声明points变量以解决此问题 在构建点时,您通过\n分隔点对,我不确定在本例中,这是否适用于SVG代码。也许试着用一个空白来划界 SVG图像不显示的问题是,显然您必须重新加载生成的实际HTML,才能在浏览器中呈现SVG图像。看见 在您的情况下,应该在每次添加行后重新加载表的HTML。使用jQuery,它看起来像这样:
// Row creation logic...
$('#tableBody').append(tr);
$("#tableBody").html($("#tableBody").html());
编辑:
通过使用闭包解决了作用域和异步问题。
使用单独的函数来提高可读性。
使用jQuery构建表和SVG元素。
. 您可以声明全局变量并在函数中使用它。您说过,我在for循环中声明了点!该列创建得很好,但图形是空的:多段线存在,但里面没有点。我不确定它是否是新线分隔,因为SVG规范允许它。在SVG创建行的末尾还有一个尾随。您能提供一个简单的代码片段来创建SVG部分吗?我删除了/n并尝试用一个空格替换它,但结果相同。我不知道问题是否来自这里,这个变量在我第一篇文章中展示给你的一次尝试中起作用。我把它移走了,这是个错误,它和这里没有任何关系!我认为这与您的Ajax调用是异步的这一事实有关,因此您的程序在Ajax请求之后继续,并在创建点之前创建SVG图像。谢谢!我从未使用过这种风格的代码回调和这种风格的ajax请求。学它很有趣!我仍然有一些问题需要理解,但我能够适应我真正想要的!我只是有两个问题我不明白:-数据没有有序地出现在表中-我想更改我使用的第二个APIhttps://api.coinmarketcap.com/v1/ticker/ 进入https://min-api.cryptocompare.com/data/all/coinlist 获取每种货币的名称,但我真的不明白您的请求是如何工作的:/谢谢您抽出时间!
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");
});