访问函数外部变量的值

时间:2018-02-08 01:38:53

标签: 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);
    $("#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个硬币的值(但“图形”列有效),而我的变量i应该为0

希望我的问题很明确,对不起,我无法发布图片...... 谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

如果您更改以下内容,我认为三个代码段中的第一个应该有效:

points变量的范围仅限于您提供给ajaxGet函数的回调函数。因此,当您在构建表时尝试使用它时,无法访问它。这就是您收到错误points is not defined的原因。在for-loop的范围内声明points变量来解决此问题。

在构建积分时,您需要按\n分隔点对,我不确定在这种情况下它是否适用于您的SVG代码。也许试着用空格分隔。

SVG图像未显示的问题是因为显然您必须重新加载您生成的实际HTML以获取在浏览器中呈现的SVG图像。见this related anwer。 在您的情况下,您应该在每次添加行后重新加载表的HTML。使用jQuery看起来像这样:

// Row creation logic...

$('#tableBody').append(tr);
$("#tableBody").html($("#tableBody").html());

编辑:

  • 使用闭包解决了范围和异步问题。
  • 使用单独的功能以提高可读性。
  • 使用jQuery构建表和SVG元素。
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");
});