Lodash _.result() 默认值

Lodash _.result() default value

为什么 lodash result 方法 return 在这种情况下不是默认值?

Arguments object (Object): The object to query.

key (string): The key of the property to resolve.

[defaultValue] (*): The value returned if the property value resolves to undefined.

var result = _.result({ foo: 1 }, 'bar', 'default');

console.log(typeof _.result({ foo: 1 }, 'bar') === 'undefined') // true

console.log(result); // expected: 'default'

http://jsfiddle.net/dbvs5ney/

尝试使用较新的 lodash 版本,如果您不需要特别使用 2.2.1 版本。

好像是3.0.0版本才加的default参数
比较 _.result 实现:
3.0.0 lodash.js

function result(object, key, defaultValue) {
  var value = object == null ? undefined : object[key];
  if (typeof value == 'undefined') {
    value = defaultValue;
  }
  return isFunction(value) ? value.call(object) : value;
}

2.2.1 lodash.js:

function result(object, property) {
  if (object) {
    var value = object[property];
    return isFunction(value) ? object[property]() : value;
  }
}