函数 returns 在控制台中未定义

function returns undefined in console

我有一个参数为字符串的函数。我期待在控制台中得到 reff,但由于某种原因我得到了 undefined。这是我的代码:

var _ref;
function foo(_ref='reff') {
  var bar = _ref.bar;
  return console.log(bar);
}
foo (_ref)

为什么这个日志 undefined 而不是 reff

你得到 undefined 因为你从 foo 返回 console.log 并且即使你修复了你的函数 console.log 仍然会吐出 undefined 因为 _ref 是一个字符串,而不是带有横线 属性.

的对象

所以你用 _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)

var _ref;
function foo(_ref='reff') {

  var bar = _ref;
return   console.log( bar);
}
foo (_ref)

请先生,附加的(.bar)有什么用属性