我有我試圖傳遞一個字符串出來,創造出新的變量的函數 - 見下:從函數傳遞字符串變量的Javascript
function networks(networkGroupId) {
jQuery.ajax({
type: 'GET'
, url: apiURL + 'api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
, dataType: 'json'
, success: function (networkGroup) {
var regionList = []; // temporary array
jQuery.each(networkGroup.countryList, function (i, countryList) {
regionList.push(countryList.code + ": 'NORTH AMERICA'")
});
var regionListOutput = '{' + regionList + '}';
console.log(regionListOutput);
}
});
};
var networkList = networks('15001');
console.log('Network List = ' + networkList);
我是,當我運行這個問題我得到的
Network List = undefined
{AG: 'NORTH AMERICA',AI: 'NORTH AMERICA',AR: 'NORTH AMERICA',AW: 'NORTH AMERICA',BB: 'NORTH AMERICA',BM: 'NORTH AMERICA',BO: 'NORTH AMERICA',BR: 'NORTH AMERICA',CL: 'NORTH AMERICA',CO: 'NORTH AMERICA',CR: 'NORTH AMERICA',CW: 'NORTH AMERICA',DM: 'NORTH AMERICA',DO: 'NORTH AMERICA',EC: 'NORTH AMERICA',GD: 'NORTH AMERICA',GF: 'NORTH AMERICA',GT: 'NORTH AMERICA',HT: 'NORTH AMERICA',JM: 'NORTH AMERICA',KN: 'NORTH AMERICA',KY: 'NORTH AMERICA',LC: 'NORTH AMERICA',PA: 'NORTH AMERICA',PE: 'NORTH AMERICA',PY: 'NORTH AMERICA',TC: 'NORTH AMERICA',TT: 'NORTH AMERICA',UY: 'NORTH AMERICA',VC: 'NORTH AMERICA',VE: 'NORTH AMERICA',VG: 'NORTH AMERICA',MQ: 'NORTH AMERICA',GP: 'NORTH AMERICA',SV: 'NORTH AMERICA',HN: 'NORTH AMERICA',NI: 'NORTH AMERICA',BS: 'NORTH AMERICA',BZ: 'NORTH AMERICA',GY: 'NORTH AMERICA',MF: 'NORTH AMERICA',MS: 'NORTH AMERICA',SR: 'NORTH AMERICA',BQ: 'NORTH AMERICA',BL: 'NORTH AMERICA',SX: 'NORTH AMERICA'}
控制檯輸出當我實際上需要雙方的日誌爲字符串{...}
我想我明白,networkList
正在恢復,因爲它爲未定義沒有等待networks('15001')
的結果,但我不知道如何去糾正這個問題。任何人都可以幫忙嗎?
編輯
爲了進一步增加一些澄清,設置networkList的變量是字符串{AG: 'NORTH AMERICA',AI: 'NORTH AMERICA'...}
那麼我想它傳遞給變量regionStyling
見下文後(控制檯日誌只爲我檢查正確的字符串正在通過):
function networks(networkGroupId, callback) {
jQuery.ajax({
type: 'GET'
, url: apiURL + 'api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
, dataType: 'json'
, success: function (networkGroup) {
var regionList = []; // temporary array
jQuery.each(networkGroup.countryList, function (i, countryList) {
regionList.push(countryList.code + ": 'NORTH AMERICA'")
});
var regionListOutput = '{' + regionList + '}';
console.log(regionListOutput);
callback(regionListOutput);
}
});
};
var networkList = [];
networks('15001', function (regionListGottenFromTheNetworksFunction) {
networkList = regionListGottenFromTheNetworksFunction;
console.log('Network List = ' + networkList);
});
console.log(networkList);
var regionStyling = {
regions: [{
values: networkList //this should be the string {AG: 'NORTH AMERICA',AI:...}
, scale: {
"NORTH AMERICA": "#2761ad"
, "EUROPE": "#d58aa3"
, "ASIA": "#ee549f"
, "LATIN AMERICA": "#15bbba"
, "AFRICA & MIDDLE EAST": "#8864ab"
}
}]
};`
您的函數'networks'沒有'return'語句,因此函數的返回值總是'undefined'。 – BoltKey