function 里面取不到参数

<script>
    let step = 10, //步长
        index = 0, //图片数
        flag = -1, //方向系数
        dis = 0, //移动距离
        width = 400, //图片宽度
        num = 5; //图片数
    const pics = ['../one.jpg', '../two.jpg', '../three.jpg', '../four.jpg', '../five.jpg'];
    let wrapper = document.querySelector('.wrapper');
    let menu = document.querySelector('.menu');
    //加载图片
    pics.forEach(val => {
        let img = document.createElement('img');
        let smallImg = document.createElement('img');
        img.src = val;
        smallImg.src = val;
        wrapper.appendChild(img);
        menu.appendChild(smallImg);
    });

    //自动添加后排图片
    function addPic() {
        pics.forEach(val => {
            let img = document.createElement('img');
            img.src = val;
            wrapper.appendChild(img);
        });
    }
    //获取style
    function getStyle(ele, cssname) {
        if (window.getComputedStyle) {
            return window.getComputedStyle(ele)[cssname];
        } else {
            return ele.currentStyle[cssname];
        }
    }
    //移动
    function pace() {
        let curPos = parseInt(getStyle(wrapper, 'left'));
        console.log('pace');
        console.log(to);
        console.log(curPos);
        wrapper.style.left = curPos + flag * step + 'px';
        dis += flag * step;
        //移动到图片最后一步
        if (Math.abs(to - dis) < step) {
            wrapper.style.left = to + 'px';
            dis = to;
            index++;
            clearInterval(pacer);
            // setTimeout(() => {
            //     timer = setInterval(pace, 100);
            // }, 2000);
        } else {
            wrapper.style.left = curPos + flag * step + 'px';
            dis += flag * step;
        }
    }
    //移动一张图
    function move(direction) {
        let to = -width * index; // 目标位置
        //判断方向 -1-left 1-right
        flag = direction === 1 ? 1 : -1;
        console.log(to);
        console.log(dis);
        pacer = setInterval(pace, 100);
    }

    //自动
    function auto() {
        addPic();
        index++;
        move(flag);
    }
    auto();
</script>

浏览器一直提示
Uncaught ReferenceError: to is not defined at pace

可是to不是在move()里面定义了吗?

我也不知道哪里出现了问题,求大佬们指教?

阅读 3k
4 个回答

应该是作用域的问题,move跟pace是在同一作用域被声明的,而pace中的变量只能在本作用域或向上查找,

emmmm,建议读一下es6文档里关于let, const和var的区别。

通常const声明一个只读的常量,let声明的变量仅在块级作用域内有效。可以看看es6的变量声明规则http://es6.ruanyifeng.com/#do...

let a = '123'
function move(direction) {
    let to = 'xxx' // to == 'xxx'
    console.log(to) // xxx
    console.log(a) // 123
}
function A(){
    console.log(to) // undefined
    console.log(a) // 123
}
console.log(to) // undefined
console.log(a) // 123

let 只有在定义的范围内可用,范围大概是{}框起来的部分

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题