gpt4 book ai didi

Lodash Wrapper 对象上的 Javascript 划分

转载 作者:行者123 更新时间:2023-11-29 21:21:19 28 4
gpt4 key购买 nike

我最近升级到 Lodash 3.10.1我注意到了一些奇怪的事情。

假设我有一个数字数组,我想得到数组中的最大值然后减半:

var series = [ 6, 8, 2 ];

var highestTotal = _.chain(series)
.max();

console.log('highestTotal is ', highestTotal);

var halved = highestTotal / 2;

console.log('halved is ', halved);

我原以为这会引发错误,因为 highestTotal 是一个 Lodash 包装器。 IE。我本来认为有必要这样做:

var halved = highestTotal.value() / 2;

让它发挥作用。但它不是!这是怎么回事?

Jsfiddle 是 here .

最佳答案

这是因为 lodash 包装器对象公开了一个 .valueOf 方法(别名是 .value),当需要一个原始值时(例如在一个算术运算)。

From the MDN :

function myNumberType(n) {
this.number = n;
}

myNumberType.prototype.valueOf = function() {
return this.number;
};

myObj = new myNumberType(4);
myObj + 3; // 7

关于Lodash Wrapper 对象上的 Javascript 划分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38478886/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com