本文介绍了迭代并执行$ .ajax opertaion时,数组元素未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 $(document).ready(function(){loadStreamInfo(); displayAll();}); var allStreamInfo = [{ user:ogaminglol},{user:faceittv},{user:twitch},{user:hearthstonesea},{user:stephensonlance},{ user:aegabriel}]; function loadStreamInfo(){for(var i = 0; i< 6; i ++){$ .ajax({url:(https://wind-bow.gomix.me / twitch-api / streams /+ allStreamInfo [i] .user),jsonp:callback,dataType:jsonp,success:function(data){if(data.stream == null){allStreamInfo [i] [status] =离线;} else {allStreamInfo [i] [status] =在线;}}}); } for(var i = 0; i< 6; i ++){$ .ajax({url:(https://wind-bow.gomix.me/twitch-api/channels/+ allStreamInfo [i]。 user),jsonp:callback,dataType:jsonp,success:function(data){allStreamInfo [i] [logo] = data.logo; allStreamInfo [i] [gameName] = data.game; allStreamInfo [i] [views] = data.views; allStreamInfo [i] [followers] = data.followers; allStreamInfo [i] [url] = data.url;}}); function displayAll(){for(var i = 0; i< 6; i ++){var outString =; outString + =< div class ='item'>; outString + =< img src ='+ allStreamInfo [i] .logo +'alt ='logo'>; outString + =< a href ='+ allStreamInfo [i] .url +'>< span id ='gameName'> + allStreamInfo [i] .gameName +< / span>< / a>; outString + =< span id ='state'> + allStreamInfo [i] .status +< / span>; outString + =< span id ='views-block'>观看次数:< span id ='view'> + allStreamInfo [i] .views +< / span>< / span>; outString + =< span id ='follow-block'>关注者:< span id ='关注'> + allStreamInfo [i] .followers +< / span>< / span>; outString + =< / div>; $( #结果)追加(outString)。 } body {padding:40px; ;}。toggle-button {width:400px;白颜色;身高:100px; text-align:center; margin:0 auto;}。all {background-color:#6699CC;宽度:30%;身高:70px; line-height:70px; border-right:2px实心灰色;显示:内联;向左飘浮; cursor:pointer;}。online {cursor:pointer; line-height:70px; background-color:cadetblue; border-right:2px实心灰色;宽度:30%;身高:70px;显示:内联; float:left;}。offline {cursor:pointer; background-color:darkorange; line-height:70px;宽度:30%;身高:70px;显示:内联; float:left;}#results {margin-top:30px;}。item {width:500px;身高:70px;保证金:5px auto; background-color:#666699; border-left:4px纯红色;颜色:白色; / * border:2px solid red; * /} a {text-decoration:none;} img {width:50px;身高:50px; margin-top:10px; margin-left:20px; margin-right:21px;} span#gameName,span#views-block,span#state,span#follow-block {position:relative;底部:18px;} span #gameName,span#state,span#views-block {margin-right:21px;} < script src =https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js>< / script>< div class =toggle-button> < div class =allonclick =displayAll()> All< / div> < div class =onlineonclick =displayOnline()> Online< / div> < div class =offlineonclick =displayOffline()>离线< / div>< / div>< div id =result>< / div> 我想在JSON对象中动态添加属性。我读过post1 和 POST2 。但为什么我得到了未定义的财产? allStreamInfo [i] [prop] =value不是向对象添加属性的方法吗?在调试窗口中,有 Uncaught TypeError:无法设置undefined(...)的属性'logo'。我已经检查了API调用,它很顺利。似乎我没有定义道具,但它不是动态添加道具的方式吗?解决方案当您使用 $ .ajax()时,这是循环中的异步操作。当得到 ajax 操作的结果时,将没有启动它的值,所以 allStreamInfo [i] 是 undefined 。 您可以使用 关闭 ,以维持 i 的值,直到ajax操作完成 闭包是指独立(自由)变量的函数(在本地使用但在封闭范围内定义的变量)。换句话说,这些函数记住它们的创建环境。 for (var i = 0; i< 6; i ++){(function(j){ $ .ajax({ url:https://wind-bow.gomix。 me / twitch-api / streams /+ allStreamInfo [j] .user, jsonp:callback, dataType:jsonp, success:function(data){ allStreamInfo [j] [status] = data.stream == null?离线:在线; } }); })(i); } 请阅读循环内部的JavaScript闭包 - 简单的实际示例 $(document).ready(function() { loadStreamInfo(); displayAll();});var allStreamInfo = [{ "user": "ogaminglol"}, { "user": "faceittv" }, { "user": "twitch"}, { "user": "hearthstonesea"}, { "user": "stephensonlance"}, {"user": "aegabriel" }];function loadStreamInfo() { for (var i = 0; i < 6; i++) { $.ajax({ url: ("https://wind-bow.gomix.me/twitch-api/streams/" + allStreamInfo[i].user), jsonp: "callback", dataType: "jsonp", success: function(data) { if (data.stream == null) { allStreamInfo[i]["status"] = "offline"; } else { allStreamInfo[i]["status"] = "online"; } } }); } for (var i = 0; i < 6; i++) { $.ajax({ url: ("https://wind-bow.gomix.me/twitch-api/channels/" + allStreamInfo[i].user), jsonp: "callback", dataType: "jsonp", success: function(data) { allStreamInfo[i]["logo"] = data.logo; allStreamInfo[i]["gameName"] = data.game; allStreamInfo[i]["views"] = data.views; allStreamInfo[i]["followers"] = data.followers; allStreamInfo[i]["url"] = data.url; } }); }}function displayAll() { for (var i = 0; i < 6; i++) { var outString = ""; outString += "<div class='item'>"; outString += "<img src='" + allStreamInfo[i].logo + "' alt='logo'>"; outString += "<a href='" + allStreamInfo[i].url + "'><span id='gameName'>" + allStreamInfo[i].gameName + "</span></a>"; outString += "<span id='state'>" + allStreamInfo[i].status + "</span>"; outString += "<span id='views-block'>Views:<span id='view'>" + allStreamInfo[i].views + "</span></span>"; outString += "<span id='follow-block'>Followers:<span id='followed'>" + allStreamInfo[i].followers + "</span></span>"; outString += "</div>"; $("#result").append(outString); }}body { padding: 40px; ;}.toggle-button { width: 400px; color: white; height: 100px; text-align: center; margin: 0 auto;}.all { background-color: #6699CC; width: 30%; height: 70px; line-height: 70px; border-right: 2px solid grey; display: inline; float: left; cursor: pointer;}.online { cursor: pointer; line-height: 70px; background-color: cadetblue; border-right: 2px solid grey; width: 30%; height: 70px; display: inline; float: left;}.offline { cursor: pointer; background-color: darkorange; line-height: 70px; width: 30%; height: 70px; display: inline; float: left;}#result { margin-top: 30px;}.item { width: 500px; height: 70px; margin: 5px auto; background-color: #666699; border-left: 4px solid red; color: whitesmoke; /*border: 2px solid red;*/}a { text-decoration: none;}img { width: 50px; height: 50px; margin-top: 10px; margin-left: 20px; margin-right: 21px;}span#gameName,span#views-block,span#state,span#follow-block { position: relative; bottom: 18px;}span#gameName,span#state,span#views-block { margin-right: 21px;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><div class="toggle-button"> <div class="all" onclick="displayAll()">All</div> <div class="online" onclick="displayOnline()">Online</div> <div class="offline" onclick="displayOffline()">Offline</div></div><div id="result"></div>I want dynamically add property in JSON object.I have read post1 and post2. But why I got undefined property? allStreamInfo[i]["prop"] = "value" isn't the way to add property to a object? In the debug window, there is Uncaught TypeError: Cannot set property 'logo' of undefined(…). I have check the API call,it goes well.It seems I don't define the prop,but isn't it the way to dynamically add a prop? 解决方案 As you are using $.ajax() which is an ansynchornous opertion in loop. When the get the result of ajax operation i will not have value with which it was initiated, So allStreamInfo[i] is undefined. You can use Closures, to maintain the value of i till the ajax operation is complete Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.for (var i = 0; i < 6; i++) { (function(j) { $.ajax({ url: "https://wind-bow.gomix.me/twitch-api/streams/" + allStreamInfo[j].user, jsonp: "callback", dataType: "jsonp", success: function(data) { allStreamInfo[j]["status"] = data.stream == null ? "offline" : "online"; } }); })(i);}Do read JavaScript closure inside loops – simple practical example 这篇关于迭代并执行$ .ajax opertaion时,数组元素未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-23 12:31