1.JS做题总结

知识点一:js-Hosting

1.找出下面的错误

function functions(flag) {
    if (flag) {
      function getValue() { return 'a'; }
    } else {
      function getValue() { return 'b'; }
    }
    return getValue();
}

这段代码错在哪呢?

答:无论flag是true还是false,getvalue返回的值都是 b  ,等效于getValue()的方法被重写了

考点是函数声明和函数表达式的区别,

函数声明无论在哪里定义,该函数都可以被调用

函数表达式的值是在JS运行时确定,并且在表达式赋值完成后,该函数才能调用

正确 的改法是

function functions(flag) {
    var getValue=null;
    if (flag) {
      getValue=function() { return 'a'; }
    } else {
      getValue=function() { return 'b'; }
    }

    return getValue();
}
View Code

js-Hosting知识点的具体指示参考这个博客:https://www.jianshu.com/p/81918cb4837f

知识点二:计时器setInterval()用法

实现一个打点计时器,要求
1、从 start 到 end(包含 start 和 end),每隔 100 毫秒 console.log 一个数字,每次数字增幅为 1
2、返回的对象中需要包含一个 cancel 方法,用于停止定时操作
3、第一个数需要立即输出

function count(start, end) {
    console.log(start++);
    var timer = setInterval (function (){
        if(start<=end){
            console.log(start++);
        }else{
            clearInterval(timer);
        }
    },100);
    return {
        cancel : function(){
            clearInterval(timer);
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/zoulingjin/p/9682297.html