简体   繁体   English

API 使用 JavaScript 从数据中访问某些值

[英]API accessing certain values from data with JavaScript

I have the following API Data:我有以下 API 数据:

[
    {
        "symbol": "AAPL",
        "name": "Apple Inc.",
        "price": 144.98,
        "changesPercentage": -1.22,
        "change": -1.79,
        "dayLow": 142.54,
        "dayHigh": 146.96,
        "yearHigh": 150,
        "yearLow": 93.7125,
        "marketCap": 2419368132608,
        "priceAvg50": 138.45343,
        "priceAvg200": 131.05212,
        "volume": 113982837,
        "avgVolume": 85057328,
        "exchange": "NASDAQ",
        "open": 144.81,
        "previousClose": 146.77,
        "eps": 4.449,
        "pe": 32.587097,
        "earningsAnnouncement": "2021-07-27T16:30:00.000+0000",
        "sharesOutstanding": 16687599204,
        "timestamp": 1627504655
    }
]

And here is my code with a fake API code:这是我的带有虚假 API 代码的代码:

var $stocks = $('#stocks');
    $.ajax({
        type: 'GET',
        url: 'https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=c0dabd2d8a382584d2144bdefde830f2',
        success: function (percent) {
            $.each(percent, function (i, item) {
                $stocks.append(percent.changesPercentage);
            })
        }
    });

All I would like to do is get the changesPercentage and display it on my webpage with HTML and CSS.我想要做的就是获取 changesPercentage 并使用 HTML 和 CSS 在我的网页上显示它。 I will have various data from different companies, so a versatile solution would be very helpful.我将拥有来自不同公司的各种数据,因此通用解决方案将非常有帮助。

You're trying to get changesPercentage from percent , which is the entire response array.您正在尝试从percent获取changesPercentage ,这是整个响应数组。 So that property would be undefined .因此该属性将是undefined

Instead, it looks like you want to get that value from each element in the array.相反,您似乎想从数组中的每个元素中获取该值。 For that you would use the item parameter of the callback function in $.each :为此,您将在$.each中使用回调函数的item参数:

$stocks.append(item.changesPercentage);

Alternatively, you could also use the i parameter as an indexer for the original array:或者,您也可以使用i参数作为原始数组的索引器:

$stocks.append(percent[i].changesPercentage);

As an aside, this appears to be a result of using poor variable names which confuse yourself.顺便说一句,这似乎是使用糟糕的变量名称使您感到困惑的结果。 percent is a misleading name for an array of objects. percent是对象数组的误导性名称。 Something like results would be better, or perhaps the plural form of whatever noun actually describes what these API results are.results这样的东西会更好,或者任何名词的复数形式实际上描述了这些 API 结果是什么。

Names are important in code.名称在代码中很重要。 They carry information about what that thing is and how it can be used.它们携带有关该东西是什么以及如何使用它的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM