gpt4 book ai didi

javascript - 如何在 jquery 中访问 forEach 之外的值

转载 作者:行者123 更新时间:2023-11-30 19:50:28 24 4
gpt4 key购买 nike

     GetMandatoryFieldsforUser: function (data) {
var field = [];
$.get("api/mapping/mandatoryfield?type=USER", function (data) {
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field) //able to print value
})
console.log(field) // not able to print value
return MandatoryFields.User;
},

EDIT

 MandatoryFields = {
User: field,
}

我的问题是我需要在 forEach 循环之外访问字段值。如何使用 jquery 或 javascript 实现这一点

EDIT

"api/mapping/mandatoryfield?type=USER" returns 

["First Name", "Last Name", "Location", "Email", "Password"],

查看已编辑的问题,我想在 MandatoryFields.User 中使用该字段数组,但如果我使用它,它不会显示值

最佳答案

这实现了 $.ajax:

GetMandatoryFieldsforUser: function (data) {
var field = [];

$.ajax({
url: "api/mapping/mandatoryfield?type=USER"

}).done(function(data) {
// THIS PORTION IS EXECUTED AFTER DATA IS LOADED
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field)

/*
USE return HERE!
*/
return field; // OR SOMETHING ELSE

})

// THIS WON'T WORK, BECAUSE DATA IS RETRIEVED IN ASYNC!
console.log(field)
},

关于javascript - 如何在 jquery 中访问 forEach 之外的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54533782/

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