专项练习27

目录

一、选择题

    1、以下js表达式返回false的是()

    2、如果要在10秒后调用checkState,下列哪行代码是正确的

二、编程题

    1、移除数组 arr 中的所有值与 item 相等的元素。不要直接修改数组 arr,结果返回新的数组


一、选择题

1、以下js表达式返回false的是()

A、1==true

B、“”==false

C、false==null

D、null==undefined

正确答案:C

解析:

(1)选项

A选项:1==true,会将true转换为1

B选项:"" == false,会将false转换为+0,再将""转换为0

C选项:false == null,会将false转换为+0,比较"+0 == null"时发现没有规则可应用

D选项:null==undefined,undefined值是派生自null值

<script>
    console.log(1==true);//true
    console.log(""==false);//true
    console.log(false==null);//false
    console.log(null==undefined);//true
</script>

(2)null与undefined

<script>
    console.log(null == false);//false
    console.log(null == true);//false
    console.log(undefined == false);//false
    console.log(undefined == true);//false
    console.log(undefined == null);//true
    console.log(undefined == undefined);//true
    console.log(null == null);//true
</script>

(3)关于==的比较规则大体有一下几点:

①操作数为数字与字符串时,将字符串转换为数字,再比较值

②操作数为布尔和非布尔时,现将布尔转换为数字,再比较值

③普通类型(布尔/字符串/数字)和对象类型(数组、对象等)比较时,现将对象类型进行 toString() 的转换,如果操作数有布尔类型,则现将布尔类型转换为数字,然后在进行对象的转换,再比较值

④null和undefined,关于它们更多的是记住规则:(1)null == undefined (2)null与undefined不能进行类型转换(换句话说不能进行类型转换,那么怎么能进行同其他类型的比较呢?那自然就是false了)

⑤Nan == Nan //false

(4)最权威的解释如下

ECMAScript 语言规范 - ECMA-262 Edition 5.1 (ecma-international.org)


2、如果要在10秒后调用checkState,下列哪行代码是正确的

A、window.setTimeout(checkState, 10);

B、window.setTimeout(checkState, 10000);

C、window.setTimeout(checkState(), 10);

D、window.setTimeout(checkState(), 10000);

正确答案:B        你的答案:D

解析:

(1)参数解释

①第二个参数单位ms

②第一个参数为没有括号函数名时, 则经过延时时间后执行该函数

③第一个参数为带括号函数名时,会立即执行函数,然后将返回的参数作为第一个参数 。除非给这个带括号的函数名加上引号

(2)不同的调用情况

<script>
    function checkState() {
        alert("被调用了");
    }
    // window.setTimeout(checkState, 10);//立即被调用
    // window.setTimeout(checkState(), 10); //立即被调用 
    // window.setTimeout(checkState, 10000); // 10s后被调用 
    // window.setTimeout(checkState(), 10000); //立即被调用
    // window.setTimeout("checkState()", 10000);// 10s后被调用 注意和上一个的区别 有引号 
</script>

二、编程题

1、移除数组 arr 中的所有值与 item 相等的元素。不要直接修改数组 arr,结果返回新的数组

示例:输入[1, 2, 3, 4, 2], 2        输出[1, 3, 4]

解析:

(1)forEach()循环arr数组

<script>
    let arr = [1,2,3,4,2]
    let item = 2
    function remove(arr, item) {
        let newArr = []
        arr.forEach(e=>{
            if(e!==item){
                newArr.push(e)
            }
        })
        return newArr
    }
    console.log(remove(arr, item));
</script>

(2)filter()过滤器

<script>
    let arr = [1,2,3,4,2]
    let item = 2
    function remove(arr, item) {
        let newArr = arr.filter(i=>{
            return i!==item
        })
        return newArr
    }
    console.log(remove(arr, item));
</script>

猜你喜欢

转载自blog.csdn.net/qq_51478745/article/details/131696234