gpt4 book ai didi

javascript - 关于javascript函数valueOf\toString和 'curry'函数在Chrome、Firefox和node环境中的行为不同

转载 作者:行者123 更新时间:2023-12-03 02:59:08 26 4
gpt4 key购买 nike

我写了一个函数:

function add(){
let arr = [];
arr = arr.concat(Array.prototype.slice.apply(arguments))
let fun = function(){
arr = arr.concat(Array.prototype.slice.apply(arguments))
return fun
}
fun.toString = function(){
console.log(222)
return arr.reduce(function(total, num){
return total+num
}, 0)
}
return fun
}
console.log(add(1,2)(2,3)(3))

这是在 Chrome 中: enter image description here

两个问题:

  1. 第一行为什么是 'f 11' ,而不是 '11'

  2. 为什么先输出'f 11',而不是'222',我认为应该先执行类型转换,然后在控制台输出计算结果。

另一个奇怪的事情是,在 Firefox 中的结果是相同的代码: enter image description here

Node 环境下的结果: enter image description here

我不明白为什么,在FF和node中,似乎没有执行计算操作。

请帮助我...非常感谢!

最佳答案

首先你可以美化一下整个代码:

function add(..arr){
function fun(...args){
arr.push(...args);
return fun
}

fun.toString = function(){
return arr.reduce((total, num) => total + num)
};
return fun;
}

正如您所注意到的,记录函数完全取决于环境。 Firefox 和 Node 返回函数的代码,而 Chrome 则执行以下操作:

out( "f" + add.toString())

因此我们的 toString 函数被调用并记录了一些内容。为了在不同环境之间保持一致的行为,我们可以显式调用 toString:

console.log(add(1)(2)(3).toString());

由此可以推断:

console.log("" + add(1)(2));

关于javascript - 关于javascript函数valueOf\toString和 'curry'函数在Chrome、Firefox和node环境中的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47489109/

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