您好,欢迎来到华佗健康网。
搜索
您的当前位置:首页【菜狗学前端】返回值undefined、null、-1区分总结

【菜狗学前端】返回值undefined、null、-1区分总结

来源:华佗健康网

下面就是console.log()输出的总结结果(我直接写了代码进行测试,感兴趣可以研究下代码)

PS:赋值为null(初始化变量)返回null或者赋值变量-1返回-1这种就不再列在总结里了。

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="h">hhh</div>
    <script>

        // 返回undefined
        console.log("——————————————-一、返回undefined-——————————-——————————————————————————");
        var x;
        console.log('1.变量声明但未被赋值时默认值为:' + x);

        var arr = [1, 2, 3]
        var arrRes = arr.find(function (item) {
            return item === 4
        })
        console.log('2.数组的find(function(){})方法没找到对应值时:' + arrRes);

        function fn(i) {
            console.log('3.函数调用时实参个数比形参少时多的部分形参值:' + i);
        }
        console.log('4.函数没有return返回值时:' + fn());

        var obj = {
            name: 'hhh'
        }
        console.log('5.获取对象中不存在的属性时:' + obj.sex);

        // 返回null
        console.log("——————————————-二、返回null-——————————-——————————————————————————");
        console.log('1.sessionStorage.getItem()方法没找到对应值时:' + sessionStorage.getItem('hhhh')); //null
        console.log('2.localStorage.getItem()方法没找到对应值时:' + localStorage.getItem('hhhh')); //null
        var ele = document.getElementById('hh')
        console.log('3.document.getElementxxx/document.querySelectorxxx不存在对应节点时:' + ele);//null

        // 返回-1(大多关于index)
        console.log("——————————————-三、返回-1(都关于获取数组索引/下标)-——————————-——————————————————————————");
        console.log('1.数组的indexOf()方法没找到对应值索引时' + arr.indexOf(4));
        console.log('2.数组的lastIndexOf()方法没找到对应值索引时' + arr.lastIndexOf(4));
        var findIndexRes = arr.findIndex(function (item) {
            return item === 4
        })
        console.log('3.数组的findIndex(function(){})方法没找到对应值索引时' + findIndexRes);

    </script>
</body>

</html>

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.com 版权所有 湘ICP备2023021991号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务