Kri*_* Ku 6 javascript arguments lodash
有没有办法将参数传递给lodash _.result
,对于这种情况,第二个属性是方法名称?或者有替代方法(最好是lodash)这样做吗?
用法示例可能是这样的:
var object = {
'cheese': 'crumpets',
'stuff': function( arg1 ) {
return arg1 ? 'nonsense' : 'balderdash';
}
};
_.result(object, 'cheese');
// => 'crumpets'
_.result(object, 'stuff', true);
// => 'nonsense'
_.result(object, 'stuff');
// => 'balderdash'
Run Code Online (Sandbox Code Playgroud)
谢谢.
我查看了lodash _.result函数的源代码,没有对此的支持。您可以为此实现自己的函数,并使用 _ 扩展 lodash。混合。
function myResult(object, path, defaultValue) {
result = object == null ? undefined : object[path];
if (result === undefined) {
result = defaultValue;
}
return _.isFunction(result)
? result.apply(object, Array.prototype.slice.call( arguments, 2 ))
: result;
}
// add our function to lodash
_.mixin({ myResult: myResult})
_.myResult(object, 'cheese');
// "crumpets"
_.myResult(object, 'stuff', true);
// "nonsense"
_.myResult(object, 'stuff');
// "balderdash"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1313 次 |
最近记录: |