gpt4 book ai didi

带有实例方法的 Javascript Array.prototype.map 函数

转载 作者:行者123 更新时间:2023-11-30 08:32:02 26 4
gpt4 key购买 nike

我想知道是否可以将实例方法传递给 Array.prototype.map 函数。

例如,我基本上想要这个功能而不必制作一个单独的函数

function Node(n) {
this.val = n;
}
Node.prototype.isBig = function() {
return this.val > 5;
}

var myArray = [
new Node(1), new Node(2), new Node(3),
new Node(7), new Node(8), new Node(9)
];

console.log(myArray);

var result = myArray.map(function(node) {
return node.isBig();
});

console.log(result);

在 java 中我可以做 .map(Node::isBig)。我可以做些什么来更改 map 参数,这样我就不必创建函数了吗?

如果你不能用 vanilla js 解决,我也愿意接受 lodash 的解决方案。

最佳答案

我认为如果不创建新函数就不能严格做到这一点,但可以通过binding 避免函数表达式和声明|一些值(value)的现有功能。

例如,您可以使用 Function.prototype.call使用适当的 this 值调用 Node.prototype.isBig

var result = myArray.map(Function.prototype.call.bind(Node.prototype.isBig));

还有一个建议 bind operator ,我认为这将允许

var result = myArray.map(::Node.prototype.isBig.call);

请注意附加参数(索引和数组)将传递给 isBig 方法。

function Node(n) {
this.val = n;
}
Node.prototype.isBig = function() {
return this.val > 5;
};
var myArray = [
new Node(1), new Node(2), new Node(3),
new Node(7), new Node(8), new Node(9)
];
var result = myArray.map(Function.prototype.call.bind(Node.prototype.isBig));
document.write(JSON.stringify(result));

而在ES6中,可以考虑使用arrow functions :

var result = myArray.map(node => node.isBig());

关于带有实例方法的 Javascript Array.prototype.map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228710/

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