gpt4 book ai didi

JavaScript 数组帮助

转载 作者:行者123 更新时间:2023-12-02 18:14:22 25 4
gpt4 key购买 nike

我正在尝试使用 ammap 绘制线条,但我一直在生成起点和终点的坐标数组。我必须使用以 case_study 作为键的 json 数组,如下所示

var data = {
"countries_involved": [
{"c_id": 6, "country": "India", "longitude": "21", "latitude": "78.0000", "involvement": 3, "case_study": 4},
{"c_id": 7, "country": "Canada", "longitude": "62", "latitude": "105.3809", "involvement": 3, "case_study": 4},
{"c_id": 8, "country": "Comoros", "longitude": "12", "latitude": "44.2333", "involvement": 1, "case_study": 5},
{"c_id": 9, "country": "Madagascar", "longitude": "20", "latitude": "47.0000", "involvement": 1, "case_study": 5},
{"c_id": 10, "country": "Mauritius", "longitude": "20", "latitude": "57.5000", "involvement": 1, "case_study": 5}
],
"country_details": [
{"name": "Kenya", "longitude": "-1", "latitude": "36.8000", "case_study": 4},
{"name": "Kenya", "longitude": "-1", "latitude": "36.8000", "case_study": 5}
]
};

我使用 jquery 过滤器返回以下格式的数据

{longitudes: [country_details.longitude,countries_involved.longitude], latitudes: [country_details.latitude,countries_involved.latitude],}

这是我在 for 循环中的函数

for (var i = 0; i < data.country_details.length; i++)
{
var obj = {
id: data.country_details[i]['name'].replace(/\s+/g, ''),
color: "#000000",
svgPath: targetSVG,
title: data.country_details[i]['country'],
latitude: data.country_details[i]['longitude'],
longitude: data.country_details[i]['latitude'],
scale: 1.5,
zoomLevel: 2.74,
lines: data.countries_involved.filter(function(involved) {
return involved.case_study === data.country_details[i].case_study
}).map(function(item) {
return {latitudes: [data.country_details[i].latitude, item.latitude], longitudes: [data.country_details[i].longitude, item.longitude]}
})
};
}

但是,我只得到一个仅包含起点而不包含端点的数组,这意味着 item.latitudeitem.longitude 未计算。有人可以帮忙吗?

最佳答案

在这段代码中:

data.countries_involved.filter(function(involved){
return involved.case_study === data.country_details[i].case_study
}).map(function(item){
return {
latitudes: [data.country_details[i].latitude, item.latitude],
longitudes: [data.country_details[i].longitude, item.longitude]
};
});

变量“i”未定义。

我相信在内置 JavaScript 数组“map”和“filter”函数的情况下,您正在迭代的集合中的索引将作为第二个参数传递。因此,将“i”声明为这两行中的第二个参数:

data.countries_involved.filter(function(involved, i){
// and:
}).map(function(item, i){

编辑:Array.prototype.map 和 Array.prototype.filter 并非在所有浏览器中都可用。要使用 jQuery map 和过滤器,请执行以下操作:

$($.grep(data.countries_involved, function(involved){
return involved.case_study === data.country_details[i].case_study
})).map(function(idx, item){
return {
latitudes: [data.country_details[i].latitude, item.latitude],
longitudes: [data.country_details[i].longitude, item.longitude]
};
}).get()

关于JavaScript 数组帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com