JavaScript 中循环 2 个数组无法正常工作

2023-12-26

我有以下 JavaScript 代码,据我所知,该代码应该仅输出一次日期和相应的计算值。但是由于某种原因,我看到内部的输出不正确parseData日期记录两次并且值被覆盖的函数。我不确定是什么导致了这里的问题:这是可以使用 node.js 运行的完整要点 https://gist.github.com/anupdsouza/c2a79643743688af050d7d7b3c24f7eb

var express = require("express")
const NIFTY50_SYMBOL = 'NIFTY 50'
const NIFTYSMALLCAP250_SYMBOL = 'NIFTY SMLCAP 250'
const startDate = '02-Jan-2007'
const requestUrl = `https://www.niftyindices.com/Backpage.aspx/getTotalReturnIndexString`
const requestHeaders = {
  'Content-type': 'application/json; charset=UTF-8',
  'Accept-Language': 'en-GB',
  'Accept': '*/*'
}

const PORT = process.env.PORT || 3000

var app = express()
var path = require('path')
app.use(express.static(path.join(__dirname,"public")))

app.listen(PORT, () => {
  console.log("Server running on port " + PORT)
})

function getTodayAsString() {
  let today = new Date()
  let options = { day: '2-digit', month: 'short', year: 'numeric' }
  return today.toLocaleDateString('en-GB', options).replace(/ /g, '-')
}

async function fetchDataAsync(url, headers, body) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(body),
      headers: headers,
    })
    const data = await response.json()
    return data
  } catch (error) {
    console.log('Error:', error)
  }
}

app.get("/", (req, res) => {
  const NIFTY50_REQ_BODY = {
    'name': NIFTY50_SYMBOL,
    'startDate': startDate,
    'endDate': '27-Mar-2023'//getTodayAsString()
  }

  const NIFTYSMALLCAP250_REQ_BODY = {
    'name': NIFTYSMALLCAP250_SYMBOL,
    'startDate': startDate,
    'endDate': '27-Mar-2023'//getTodayAsString()
  }

  const promise1 = fetchDataAsync(requestUrl, requestHeaders, NIFTY50_REQ_BODY)
  const promise2 = fetchDataAsync(requestUrl, requestHeaders, NIFTYSMALLCAP250_REQ_BODY)

  Promise.all([promise1, promise2])
  .then(([json1, json2]) => {
    parseData(json1.d, json2.d)
    res.send('Finished parsing data')
  })
  .catch(error => console.log('Error:', error))
})

const smallcapInitialTRI = parseFloat(2100.00)
const niftyInitialTRI = parseFloat(4807.77)

function parseData(niftyData, smallcapData) {
  const linebreak = "=".repeat(50);
  console.log(linebreak)
  console.log("Start parsing data:")
  console.log(linebreak)

  const niftyValues = JSON.parse(niftyData)
  const smallcapValues = JSON.parse(smallcapData)

  for(const smallcapObj of smallcapValues) {
    const smallcapDate = smallcapObj.Date
    const smallcapTRI = parseFloat(smallcapObj.TotalReturnsIndex)
    let niftyTRI = 0

    for (const niftyObj of niftyValues) {
      const niftyDate = niftyObj.Date

      if (niftyDate === smallcapDate) {
        niftyTRI = parseFloat(niftyObj.TotalReturnsIndex)
        console.log("date: "+ smallcapDate + " niftyTRI: " + niftyTRI + " smallcapTRI: " + smallcapTRI)
        break
      }
    }

    if (smallcapTRI && niftyTRI) {
      const relativeValue = ((smallcapTRI / smallcapInitialTRI) / (niftyTRI / niftyInitialTRI))
      console.log("date: "+ smallcapDate + " relative value: " + relativeValue)
    }
  }

  console.log(linebreak)
  console.log("Finished parsing data:")
  console.log(linebreak)
}

module.exports = app

输出有时会被错误地记录两次。我已在链接的要点评论中共享了整个输出。 可以找到 nifty_50_data 和 nifty_smallcap_data 的 JSON 响应here https://drive.google.com/file/d/1ELTi85mrxbN9eIpL524JJA_ESAxqV4U6/view?usp=sharing & here https://drive.google.com/file/d/1BJBGeor7KsRmbC4hqxGXYP6TsaOC_lxD/view?usp=sharing分别是因为回复太大而无法插入帖子中。

我尝试记录里面的值if (nifty_smallcap_tri && nifty_50_tri) {块,我看到奇怪的行为,同一日期发生了两次循环。我原以为它总是一次性的,因为我试图匹配内部 for 循环中的日期,考虑到日期只出现一次,理想情况下应该只发生一次:

Log 1:
date: 26 Mar 2010 nifty_smallcap_initial: 2100 nifty_50_initial: 4807.77
date: 26 Mar 2010 nifty_smallcap_tri: 2824.34 nifty_50_tri: 2824.34
date: 26 Mar 2010 relative value: 2.289414285714286

And

Log 2:
date: 26 Mar 2010 nifty_smallcap_initial: 2100 nifty_50_initial: 4807.77
date: 26 Mar 2010 nifty_smallcap_tri: 6562.47 nifty_50_tri: 2824.34
date: 26 Mar 2010 relative value: 5.3195481307390144

更奇怪的是日期26 Mar 2010json 响应中收到的 nifty_smallcap_tri 和 nifty_50_tri 值如下:

Server JSON response values:
{\"Index Name\":\"Nifty Smlcap 250\",\"Date\":\"26 Mar 2010\",\"TotalReturnsIndex\":\"2824.34\"}
{\"Index Name\":\"Nifty 50\",\"Date\":\"26 Mar 2010\",\"TotalReturnsIndex\":\"6562.47\"}

为什么日志1中都是nifty_smallcap_tri & nifty_50_tri的价值Nifty Smlcap 250从响应和日志 2 中为什么是nifty_smallcap_tri & nifty_50_tri响应中的值与实际值进行交换?

编辑: 我通过使用 JSON 响应作为字符串来验证 parseData 函数,它工作正常。下面是一个包含截断数据的工作示例,其中我使用 JSON 响应作为本地字符串调用该函数,并且运行良好。由于字符限制,无法发布整个数据转储。我不确定在对通过 api 获取的数据进行解析时导致问题的原因。

var result_list = []
var tri_data = {}
const nifty_smallcap_initial = 2100.00
const nifty_50_initial = 4807.77

const niftyJSON = "[{\"IndexName\":\"NIFTY50\",\"Date\":\"27Mar2020\",\"TotalReturnsIndex\":\"12193.62\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"26Mar2020\",\"TotalReturnsIndex\":\"12167.15\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"25Mar2020\",\"TotalReturnsIndex\":\"11710.71\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"24Mar2020\",\"TotalReturnsIndex\":\"10983.15\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"23Mar2020\",\"TotalReturnsIndex\":\"10710.41\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"20Mar2020\",\"TotalReturnsIndex\":\"12298.74\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"19Mar2020\",\"TotalReturnsIndex\":\"11620.92\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"18Mar2020\",\"TotalReturnsIndex\":\"11904.02\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"17Mar2020\",\"TotalReturnsIndex\":\"12604.41\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"16Mar2020\",\"TotalReturnsIndex\":\"12928.18\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"13Mar2020\",\"TotalReturnsIndex\":\"13987.31\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"12Mar2020\",\"TotalReturnsIndex\":\"13474.38\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"11Mar2020\",\"TotalReturnsIndex\":\"14694.31\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"09Mar2020\",\"TotalReturnsIndex\":\"14684.56\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"06Mar2020\",\"TotalReturnsIndex\":\"15440.48\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"05Mar2020\",\"TotalReturnsIndex\":\"15833.21\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"04Mar2020\",\"TotalReturnsIndex\":\"15805.53\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"03Mar2020\",\"TotalReturnsIndex\":\"15878.98\"},{\"IndexName\":\"NIFTY50\",\"Date\":\"02Mar2020\",\"TotalReturnsIndex\":\"15632.14\"}]"

const smallcapJSON = "[{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"27Mar2020\",\"TotalReturnsIndex\":\"3867.88\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"26Mar2020\",\"TotalReturnsIndex\":\"3834.21\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"25Mar2020\",\"TotalReturnsIndex\":\"3705.15\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"24Mar2020\",\"TotalReturnsIndex\":\"3614.88\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"23Mar2020\",\"TotalReturnsIndex\":\"3649.74\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"20Mar2020\",\"TotalReturnsIndex\":\"4164.75\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"19Mar2020\",\"TotalReturnsIndex\":\"4073.10\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"18Mar2020\",\"TotalReturnsIndex\":\"4293.66\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"17Mar2020\",\"TotalReturnsIndex\":\"4570.10\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"16Mar2020\",\"TotalReturnsIndex\":\"4677.61\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"13Mar2020\",\"TotalReturnsIndex\":\"4945.46\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"12Mar2020\",\"TotalReturnsIndex\":\"4911.61\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"11Mar2020\",\"TotalReturnsIndex\":\"5386.57\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"09Mar2020\",\"TotalReturnsIndex\":\"5400.60\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"06Mar2020\",\"TotalReturnsIndex\":\"5663.56\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"05Mar2020\",\"TotalReturnsIndex\":\"5795.22\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"04Mar2020\",\"TotalReturnsIndex\":\"5768.55\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"03Mar2020\",\"TotalReturnsIndex\":\"5859.40\"},{\"IndexName\":\"NiftySmlcap250\",\"Date\":\"02Mar2020\",\"TotalReturnsIndex\":\"5790.35\"}]"

function parseData(nifty_50_data, nifty_smallcap_data) {
  console.log("==============================================================")
  console.log("Start parsing data:")
  console.log("==============================================================")

  const niftySmallcapValues = JSON.parse(nifty_smallcap_data)
  const niftyFiftyValues = JSON.parse(nifty_50_data)

  for(const nifty_smallcap of niftySmallcapValues) {

    const date = nifty_smallcap.Date
    const nifty_smallcap_tri = parseFloat(nifty_smallcap.TotalReturnsIndex)
    let nifty_50_tri = 0

    for (const nifty_50 of niftyFiftyValues) {
      if (nifty_50.Date === nifty_smallcap.Date) {
        nifty_50_tri = parseFloat(nifty_50.TotalReturnsIndex)
        break
      }
    }

    if (nifty_smallcap_tri && nifty_50_tri) {
      const relative_value = ((nifty_smallcap_tri / nifty_smallcap_initial) / (nifty_50_tri / nifty_50_initial))
      console.log("date: "+ date + ", relative value: " + relative_value)

      tri_data['date'] = nifty_smallcap.Date
      tri_data['nifty_smallcap_tri'] = nifty_smallcap_tri
      tri_data['nifty_50_tri'] = nifty_50_tri
      tri_data['relative_value'] = relative_value

      result_list.push(tri_data)
    }
  }

  console.log("==============================================================")
  console.log("Finished parsing data:")
  console.log("==============================================================")
}

parseData(niftyJSON, smallcapJSON)

你的问题在于niftyindices.com

如果您尝试将其记录为

async function count() {
    const promise1 = fetchDataAsync(requestUrl, requestHeaders, NIFTY50_REQ_BODY);
    const promise2 = fetchDataAsync(requestUrl, requestHeaders, NIFTYSMALLCAP250_REQ_BODY, );
  const [json1,json2] = await Promise.all([promise1, promise2])
    
    const [niftyValues,smallcapValues] = [json1, json2].map(j=>JSON.parse(j.d))
    console.log({
        nifty: niftyValues.length,
        small: smallcapValues.length
    })
}
for (let i = 0; i < 30; i++) {
    await count()
}

你会发现它的结果是相当随机的

{ nifty: 4023, small: 4023 }
{ nifty: 5814, small: 8047 }
{ nifty: 8046, small: 12069 }
{ nifty: 4023, small: 12069 }
{ nifty: 12069, small: 9325 }
{ nifty: 12069, small: 8046 }
{ nifty: 4023, small: 8046 }
{ nifty: 8046, small: 4023 }
{ nifty: 4023, small: 8046 }
{ nifty: 4023, small: 8046 }
{ nifty: 4023, small: 8046 }
{ nifty: 4023, small: 8046 }
{ nifty: 12069, small: 8046 }
{ nifty: 8046, small: 4023 }
{ nifty: 8046, small: 4023 }
{ nifty: 4023, small: 8046 }
{ nifty: 8047, small: 12070 }
{ nifty: 4023, small: 6454 }

所以, 不Promise.all,按顺序等待每个人

    const json1 = await fetchDataAsync(requestUrl, requestHeaders, NIFTY50_REQ_BODY);
    const json2 = await fetchDataAsync(requestUrl, requestHeaders, NIFTYSMALLCAP250_REQ_BODY);
    parseData(json1, json2)

并检查数组长度是否正确(或者至少两个数组的长度相同)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中循环 2 个数组无法正常工作 的相关文章

随机推荐

  • PyCharm - 预期类型“Optional[IO[str]]”,却得到“TextIOWrapper[str]”

    将 PyCharm 更新到 2017 1 后 在一切看似简单且正确的地方开始弹出新的检查警告 它看起来如下 看起来像open 不返回预期的类型file参数 但代码非常简单 最重要的是 它确实按预期工作 使用 Python 3 5 2 Pyt
  • Symfony 2.2 扩展 ExceptionController

    这个问题与跟随变化 https github com symfony symfony commit 35d63df044cba20cdf441963ca85a7f4d51200cc Symfony 2 2 版本的一部分 Part 1 在 S
  • 放置 onSharedPreferenceChangeListener 的最佳位置

    我正在尝试向我的应用程序添加设置 我已添加新设置 但不知道该放在哪里OnSharedPreferenceChangeListener 我把它放在活动中并添加了一个Log d 但是Log d 永远不会被触发 有任何想法吗 最佳地点根据Andr
  • 如何获取空值的先前值

    我的表中有以下数据 Id FeeModeId Name Amount 1 NULL NULL 20 2 1 Quarter 1 5000 3 NULL NULL 2000 4 2 Quarter 2 8000 5 NULL NULL 500
  • 如何检测用户是否已经打开了某个网址并在已打开的情况下重定向到相同的网址?

    谁能告诉我如何检测用户是否已打开链接 url 选项卡 如果 url 已打开 是否可以将链接重定向到活动浏览器选项卡 例如 用户单击链接 js 代码将在浏览器中打开一个新选项卡 现在 如果用户再次单击该链接 我希望他重定向到活动会话 而不是打
  • 无法播放某些视频

    我正在尝试通过我们的服务器在 Android 设备上播放电影 它不是一个媒体服务器 只是一个普通的 Apache 服务器 我们使用相同的 API 来访问 iPhone 上的视频 效果很好 在 Android 设备上 某些视频可以播放 而另一
  • Office 插件开发:在 Word 2016 中插入表格

    我尝试使用 Office js 在文档正文中插入表格 但无济于事 我使用了以下代码 function insertSampleTable showNotification Insert Table Inserting table Word
  • 无法看到部署的 Firebase 功能

    我按照以下步骤操作 Firebase CLI 命令行界面 需要 Node js 和 npm 您可以按照以下说明进行安装https nodejs org https nodejs org 安装 Node js 也会安装 npm 安装 Node
  • 将 Fog 与 Ruby 结合使用生成预签名 URL 以将文件放入 Amazon S3 中

    我正在使用 Fog gem 生成预签名的 url 我可以成功地执行此操作以获得对该文件的读取访问权限 这就是我所做的 fog s3 Fog Storage new provider gt AWS aws access key id gt k
  • 从 Exact Online 检索联系人时出现错误

    我想在 Exact Online 中检索一家公司的所有联系人 但收到以下错误 select from AccountContacts Error itgenusg026 不支持请求的 3 308 列数 将请求的列数限制为最多 1 000 列
  • 哪些 MVC 框架可用于 Java 桌面/winform 应用程序?

    我要开发一个winform应用程序 我想将模型 视图和控制器分开 我没有使用过任何Java MVC框架 并且已经脱离Java几年了 谁能根据自己的经验告诉我一些合适的框架及其优缺点 我计划使用 NetBeans IDE Griffon ht
  • 使用不同的数据库进行开发与生产 Flask

    我有一个 Flask 应用程序 它根据生产环境变量和开发环境变量使用不同的数据库 我担心开发人员在运行本地 Flask 应用程序之前忘记设置 FLASK ENV development 然后突然对生产数据库进行更新 我想到的唯一简单的解决方
  • 维基数据的重复结果

    我创建了以下对 Wikidata 的 SPARQL 查询 该查询的结果是与德国各州相关的记录 但正如您所看到的 结果连续出现四次 您可以在此处测试它 https query wikidata org https query wikidata
  • 使用 php 更改 css 背景图像

    我正在为这个网站做一个个人资料 我想做一个像 Facebook 那样的封面照片元素 我遇到的问题是 首先如何保存封面的背景图片 比如 我可以将图像的 url 保存在数据库中 但是我如何才能将其放入 css 中呢 我真的不想只是说 div s
  • 如何覆盖父/扩展元素内部的 Xsd 元素

    我正在我的公司创建一个新的数据交换服务 我们想要扩展 core xsd 定义文件中定义的现有对象 这是我需要做的一个例子
  • 当鼠标悬停在浏览器栏/后退按钮上时,Javascript 弹出窗口

    我想在这个页面上模仿这个确切的功能 将鼠标移向顶部浏览器栏 http my personal growth com personal growth what anthony robbins teaches about emotions an
  • iOS 9 中的 Facebook 登录 SDK

    我正在使用 facebook 登录 SDK 它在 iOS 7 8 和 9 中完美运行 但是 如果手机有 facebook 应用程序登录验证 则可以在 iOS 7 和 8 中打开该应用程序 但 IOS 9 无法打开 facebook 应用程序
  • 如何在 Neo4j 中有效地创建独特的关系?

    跟进我的问题here https stackoverflow com questions 29873015 create on not match command for neo4js cql noredirect 1 comment486
  • keras.argmax中axis=-1的含义是什么?

    我是 Keras 的初学者 需要帮助才能理解keras argmax a axis 1 and keras max a axis 1 是什么意思axis 1 when a shape 19 19 5 80 以及输出是什么keras argm
  • JavaScript 中循环 2 个数组无法正常工作

    我有以下 JavaScript 代码 据我所知 该代码应该仅输出一次日期和相应的计算值 但是由于某种原因 我看到内部的输出不正确parseData日期记录两次并且值被覆盖的函数 我不确定是什么导致了这里的问题 这是可以使用 node js