JavaScript中会打印出undefined的情况汇总

您所在的位置:网站首页 前端打印object JavaScript中会打印出undefined的情况汇总

JavaScript中会打印出undefined的情况汇总

2023-09-10 08:21| 来源: 网络整理| 查看: 265

undefined,作为一种基本数据类型,在JavaScript中有时候不经意,就会打印输出它。这里,我做一个小小的总结:

变量声明了的但是未初始化

在声明变量的时候,如果没有初始化变量,即给变量赋值,那么打印出 undefined。

var a; console.log(a);//undefined 给变量赋值 undefined

直接给变量赋值一个undefined

var a = undefined; console.log(a);//undefined 变量声明提升返回 undefined

把打印语句写在了声明变量之前,由于变量声明提前,就算赋值了,也是 undefined

console.log(a);//undefined var a = 1; 使用 .访问对象中没有的属性

访问对象中的属性时,如果对象中没有对应的属性,会打印 undefined

var obj = {}; console.log(obj.name);//undefined 函数中定义了形参,但是执行函数时没有传入实参

在我们的函数中,如果定义了形参,但是你执行的时候没有传入实参时,会 undefined。 具体原因是因为a作为局部变量被声明提前了。

function test(a){ console.log(a); } test();//undefined 对象中的方法中的匿名函数的函数体为空

一个方法(函数)中如果它的函数体为空时,在调用时会返回 undefined

var obj = { testFun:function(){} }; console.log(obj.testFun());//undefined 打印函数的调用时,该函数的函数体为空

一个函数的函数体为空时,在打印它的调用时,打印出 undefined

function test(){}; console.log(test());//undefined 打印函数的调用时,函数体不为空

这里test()相当于1,先打印1,然后console.log()在打印函数时,默认会打印返回值,如果没有设定返回值,会返回 undefined。

function test(){ console.log(1); }; console.log(test());//1 undefined 函数作为返回值时,其返回值函数没有设置返回值

这里test()调用自身,然后再()调用内部的返回函数,打印出1,console.log()默认接受函数时会打印返回值,如果没有设定,会返回 undefined。

function test(){ return function(){ console.log(1); } } console.log(test()());// 1 undefined


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3