var a = 10;

function Obj() {
  console.log(a);
  let a = 10;
}

Obj()





调用函数时,a的Obj值打印为未定义

最佳答案

在这种情况下,代码在第一个控制台上中断。由于a的范围在函数内,因此您在打印之前尚未定义它。

我举了一些例子向您展示了不同的初始化方案。



const derp = 10

const blerg = (derp) => {
 console.log('Checking case1: ', derp)
 //Reason: Here derp is the prop passed to the function and passed undefined to it.
}

const blerg2 = (derp) => {
 console.log('Checking case2: ', derp)
 //Reason: Here derp is the prop passed to the function
}

const blerg3 = () => {
 console.log('Checking case3: ', derp)
 // Throws Error
 //Reason: Here derp scope is within the function and not defined so far.
let derp = 20
console.log('Checking case4: ', derp)
// This line won't print because already code broke on the above console.
}

blerg()
blerg2(derp) // Passing the derp initialised on line 1
blerg3() // Passing nothing to the function

07-24 14:07