Javascript 函数返回控制台中未定义的值
我有一个参数为string的函数。我本来希望在控制台中获得Javascript 函数返回控制台中未定义的值,javascript,html,function,console.log,Javascript,Html,Function,Console.log,我有一个参数为string的函数。我本来希望在控制台中获得reff,但由于某种原因,我得到了未定义的。这是我的密码: var\u ref; 函数foo(_ref='reff'){ var bar=_ref.bar; 返回控制台.log(bar); } foo(_-ref)由于从foo返回console.log,因此未定义,即使修复了函数,console.log仍会显示未定义,因为\u-ref是字符串,而不是具有bar属性的对象 因此,使用\u ref调用foo,此时未定义,当函数foo运行时,
reff
,但由于某种原因,我得到了未定义的。这是我的密码:
var\u ref;
函数foo(_ref='reff'){
var bar=_ref.bar;
返回控制台.log(bar);
}
foo(_-ref)
由于从foo
返回console.log
,因此未定义,即使修复了函数,console.log仍会显示未定义,因为\u-ref
是字符串,而不是具有bar属性的对象
因此,使用\u ref
调用foo
,此时未定义,当函数foo运行时,它会将其设置为字符串'reff'
,该字符串没有条形属性,因此日志记录未定义
因此,您在两种情况下都有未定义的,因为您从foo
返回console.log
,即使您修复了函数,console.log仍会显示未定义,因为\u ref
是一个字符串,而不是具有bar属性的对象
因此,使用\u ref
调用foo
,此时未定义,当函数foo运行时,它会将其设置为字符串'reff'
,该字符串没有条形属性,因此日志记录未定义
因此,您有两种场景中未定义的代码好的,我将逐行解释您的代码,让您了解它是如何运行的:
// you define a variable name _ref, its default value is `undefined`
var _ref;
// you define a function name `foo`
// the function has one argument name `_ref` (different with the first _ref)
// this argument has a default value = 'reff'
function foo(_ref = 'reff') { // since you called `foo` with undefined value, _ref will get its default value 'reff'
var bar = _ref.bar; // _ref is a string, so _ref.bar is undefined => bar is undefine
return console.log(bar); // log undefined
}
// you call the function `foo` with `_ref` (it is `undefined`)
foo(_ref)
好的,我将逐行解释您的代码,让您了解它是如何运行的:
// you define a variable name _ref, its default value is `undefined`
var _ref;
// you define a function name `foo`
// the function has one argument name `_ref` (different with the first _ref)
// this argument has a default value = 'reff'
function foo(_ref = 'reff') { // since you called `foo` with undefined value, _ref will get its default value 'reff'
var bar = _ref.bar; // _ref is a string, so _ref.bar is undefined => bar is undefine
return console.log(bar); // log undefined
}
// you call the function `foo` with `_ref` (it is `undefined`)
foo(_ref)
var\u ref;
函数foo(_ref='reff'){
变量条=_ref;
返回控制台.log(bar);
}
foo(_ref)
var\u ref;
函数foo(_ref='reff'){
变量条=_ref;
返回控制台.log(bar);
}
foo(_ref)
“我应该在控制台中获得'reff'”为什么。。?怎样。。?您正在将一个不存在的属性\u ref
分配给bar
,它的值是未定义的。此行的目的是什么var bar=\u ref.bar代码>?为什么不console.log(_ref)
?默认值是一个字符串,您可以引用它。属性栏?“我应该在控制台中获得'reff'”为什么。。?怎样。。?您正在将一个不存在的属性\u ref
分配给bar
,它的值是未定义的。此行的目的是什么var bar=\u ref.bar代码>?为什么不console.log(_ref)
?默认值是一个字符串,您可以引用它。财产酒吧?我猜,有人认为你在发帖前没有付出合理的努力。无论如何,如果答案有帮助的话,请接受:)我的猜测是,有人认为你在发帖前没有付出合理的努力。无论如何,如果答案有帮助,就接受它:)