我的for循环不起作用,我也不知道为什么 [英] my for loop doesn't work and I don't know why

查看:168
本文介绍了我的for循环不起作用,我也不知道为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(document).onload(function(){
    for (var i = 0; i <max; i++) {
        if(pi[i]===undefined||pi[i]===null||pi[i]==0){
            pi[i]=1;
        }
    }
});
alert('hello');

我已经安装了jQuery,并且所有变量都已在代码中更早地设置,但是for循环之后的任何内容都无法正常工作,例如alert('hello').如果有人可以看到与此有关的问题,请告诉我.

I have jQuery installed and all the variables are set earlier on in the code, but anything after the for loop doesn't work such as the alert('hello'). If anyone cans see something wrong with this please tell me.

编辑

var max=438;
localStorage.setItem('max', max);
var pi=[];
pi=JSON.parse(localStorage.getItem('pi'));
var i=localStorage.getItem('i');
var url1=Math.floor((Math.random() * max) + 1);
var url2=Math.floor((Math.random() * max) + 1);
if(url1==url2){

url2=url2+2;
if(url2>max){
    url2=url2-max;
}
}
document.getElementById('imgimg1').src='../img/'+url1+'.gif';
document.getElementById('imgimg2').src='../img/'+url2+'.gif';
var v1=url1-1;
var v2=url2-1;
function vote1() {
    pi[v1]=pi[v1]+(pi[v2]/pi[v1]);
    localStorage.setItem('pi',JSON.stringify(pi));
    location.reload();
}
function vote2() {
    pi[v2]=pi[v2]+(pi[v1]/pi[v2]);
    localStorage.setItem('pi',JSON.stringify(pi));
    location.reload();
}
$(document).load(function(){
    for (var i = 0; i <max; i++) {
        if(pi[i]===undefined||pi[i]===null||pi[i]==0){
            pi[i]=1;
        }
    }
});
alert(pi);

这是完整的代码

推荐答案

尝试一下:

/* assuming this */
var max = 4; // for example
var pi = [0, 0, 0, 0];
/* end assuming this */

$(document).ready(function() {
    for (var i = 0; i < max; i++) {
        if(pi && pi[i] && pi[i] < 0) {
            pi[i] = -1;
        } else {
            pi[i] = 1;
        }
    }
    alert(JSON.stringify(pi));
});

它应该写'[1、1、1、1]'

关于整个代码,为什么在准备好文档后需要循环?

Regarding your entire code, why do you need to loop after document ready ?

为什么不这样初始化pi:

var max=438;
localStorage.setItem('max', max);
var pi=[];
pi=JSON.parse(localStorage.getItem('pi'));
for(var i = 0; i < max; i++) {
    pi[i] = 1;
}
[...]

这篇关于我的for循环不起作用,我也不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆