javascript - For 循环变量自动递增
问题描述
我创建了一个 for 循环并在其中运行 Javascript(jquery) 代码。但不知何故,for循环变量会自动递增。
for (var i=0; i<len; i++) { //len=2
console.log(i); // outputs 0 and 1 as expected
$.ajax({
url:'execute.php',
method:'GET',
data:{
link: items[i]
},
success:function(data){
console.log(i); //outputs 2 and 2. It sould be 0 and 1
$("#div1").html(data);
var item = $(".sticky-item-title .title").html();
$("#product-"+ i).html(item);
},
error:function(data){
alert('error' + data);
}
});
}
$.ajax 之前的 console.log 按预期显示 0 和 1(我在 len 中有 2 个项目)。但是成功函数中的console.log显示为2和2。为什么以及在哪里增加。我试过这段代码
for (var i=0; i<len; i++) {
var s=i;
$.ajax({
url:'execute.php',
method:'GET',
data:{
link: items[s]
},
success:function(data){
console.log(s); //outputs 1 and 1. It should be 0 and 1
$("#div1").html(data);
var item = $(".sticky-item-title .title").html();
$("#product-"+ s).html(item);
},
error:function(data){
alert('error' + data);
}
});
}
这里变量 s 显示 1 和 1 而不是 0 和 1。
我在这里做错了什么。提前致谢
解决方案
当你var
用来定义一个变量时,你只声明了一个变量,它在每个循环中被覆盖。在循环之后的异步回调中,变量就是最后一次迭代的值。您可以通过使用let
或定义自调用函数,将迭代值作为参数传递来规避此问题。
for (let i = 0; i < array.length; i++) { ... }
或者
for (var i = 0; i < array.length; i++) {
(function(i) {
...
})(i);
}
推荐阅读
- python - requests.post 超时在 Python 中不起作用
- excel - 用于创建 excel 数据透视图的 Python 库
- mongodb - MongoDB 4.2 将聚合管道更新与数组过滤器结合起来
- robotframework - 使用 Python 在机器人框架中使用“SapGuiLibrary.Doubleclick 元素”
- c# - EmguCV:使用多个相同相机的问题
- r - 找出一个函数是否在另一个函数R中
- python - 使用变音符号解码 cp1252 标准输出
- c# - 从视图模型中操作视图对象是 Prism 项目的标准吗?
- android - 在 PlayStore 中按名称或包名称搜索 Android 应用时不显示
- javascript - JS / React Carousel with useEffect & Hooks - 水平滚动到轮播中的标签?