我正在尝试遍历数组,并为for循环分配变量。所以像这样:
function Person(name, status){ this.name = name; this.status = status; } var status = []; var array = ["bill","bob","carl","ton"]; function exAjax(function(){ for(var i = 0; i < array.length; i++){ var name = array[i]; console.log(name); =====> this gives the correct name $.ajax({ url: xxxxxxx, success: function(data){ if(data.stream === null){ var person = new Person(name, "dead"); console.log(name); =====> return undefined until the last person status.push(person); } } }) name = ""; } })
我遇到的问题是名称没有进入成功功能。我以为js会继续向上查找该变量,如果它在当前作用域中不存在?如果尝试console.log name,我将无法为name变量定义!示波器大师我在做什么错?
您可以使用.queue(),$.map()以保持范围name。此外,改变status阵列的具有属性的对象status,其中值是一个数组,以防止可能出现的冲突this.status的Person对象。
.queue()
$.map()
name
status
this.status
Person
请注意,您也可以连接.promise(/* queueName */)在执行任务.then()时,在所有排队的功能queueName,IEG,"status"一直呼吁,queueName .length是0。
.promise(/* queueName */)
.then()
queueName
"status"
.length
0
function Person(name, status){ this.name = name; this.status = status; } var blob = new Blob(['{"stream":null}'], {type:"application/json"}); var url = URL.createObjectURL(blob); // change `status` array reference, e.g., to `arr` var arr = {status:[]}; var array = ["bill","bob","carl","ton"]; $(arr).queue("status", $.map(array, function(curr) { return function(next) { var name = curr; // do asynchronous stuff $.ajax({url:url, dataType:"json"}) .then(function(data) { if(data.stream == null){ var person = new Person(name, "dead"); console.log(name, person); arr.status.push(person); } }) .then(next) // call next function in `"status"` queue } })) .dequeue("status") .promise("status") // do stuff when all functions in `"status"` queue have completed, // `"status"` queue `.length` is `0` .then(function() { // `this` : `arr` as jQuery object // `this[0].status`: array containing objects pushed to `arr.status` console.log(this[0].status); // $(this).prop("status"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
jsfiddle https://jsfiddle.net/nnayjckc/2/
您也可以使用$.when(),.apply(),$.map(),返回相同的结果
$.when()
.apply()
function Person(name, status) { this.name = name; this.status = status; } var blob = new Blob(['{"stream":null}'], { type: "application/json" }); var url = URL.createObjectURL(blob); // change `status` array reference, e.g., to `arr` var arr = { status: [] }; var array = ["bill", "bob", "carl", "ton"]; $.when.apply($, $.map(array, function(curr) { var name = curr; return $.ajax({ url: url, dataType: "json" }) .then(function(data) { if (data.stream == null) { var person = new Person(name, "dead"); console.log(name, person); arr.status.push(person); } }) })) .then(function() { console.log(arr.status) }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
jsfiddle https://jsfiddle.net/nnayjckc/3/