在另一个方法中使用一个forEach方法中的变量 [英] Use variable from one forEach Method in another
本文介绍了在另一个方法中使用一个forEach方法中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在另一个getJSON
和forEach
方法中使用一个值.我有什么办法吗?
I am trying to use a value from inside one getJSON
, forEach
method in another. Is there any way for me to do that?
JavaScript
JavaScript
$.getJSON(json1, result => {
result.forEach((elem, i, array) => {
$('#x').text(elem.x);
$('#y').text(elem.y);
});
$.getJSON(json2, result => {
result.forEach((elem, i, array) => {
$('#v').text(elem.v);
$('#pv').text(elem.pv);
});
我想在json2
中使用json1
中的elem.x
.我需要能够计算elem.x/elem.v
.有什么办法吗?
I want to use elem.x
from json1
inside json2
. I need to be able to calculate elem.x/elem.v
. Is there any way to do that?
推荐答案
根据您所写的评论,我更喜欢这样做(认为两者的长度相同):
By the comment you wrote, I'd prefer do it like this (think that both will have same length):
var first, second;
$.when(
$.getJSON(json1, result => first = result),
$.getJSON(json2, result => second = result)
).then(function() {
if (first && second) {
let results = first.map((item, index) => item.x / second[index].v);
// do whatever you want
}
});
这篇关于在另一个方法中使用一个forEach方法中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文