javascript - JS箭头函数作为对象方法的语法
问题描述
第一次在这里提问。
我通过@CertainPerformance 发现了这个有用的函数,用于按 ID 递归查找嵌套项。
const findItemNested = (arr, itemId, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
);
我无法弄清楚使此函数成为“util”对象上的方法的语法。以下语法不起作用:
var util = {
const findItemNested = (arr, itemId, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
);
}
据我所知,语法需要是这样的:
var util = {
findItemNested: function (arr, itemId, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
);
}
但是这种语法当然行不通。我尝试将箭头函数语法转换为普通函数语法,如下所示(请注意,我已经更改了箭头函数所需的括号,以将对象文字返回为花括号,以匹配对象上的方法所需的语法)。
var util = {
findItemNested: function (arr, itemId, nestingKey) => {
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
}
}
但是,虽然没有编译或运行时错误,但此语法会导致函数返回 undefined 而不是找到存在的嵌套项。
我可以让这个函数工作的唯一方法是将它设置为一个全局可用的函数,并在我的 script.js 文件中使用@CertainPerformance 的原始语法。
有没有办法让这个函数进入我的 var util?提前致谢。
解决方案
您正在使用 es6 箭头函数和function
关键字。如果您希望它在对象内工作,最好的方法是保持您的代码相同,但删除箭头。您的第二行应如下所示:
findItemNested: function (arr, itemId, nestingKey){
推荐阅读
- powershell - 将 cmd 错误捕获到当前目录中的文件?
- swift - 在 SceneKit 中缩放粒子系统
- c# - Azure 函数无法读取应用设置和连接字符串
- php - PHP 的 simplexml 可以在请求中包含 POST 数据吗?
- twitter-bootstrap - Bootstrap 4 使输入在焦点上变得比容器列更宽
- mysql - 如何在使用 Perl 将重复数据添加到 MySQL DB 时隐藏系统生成的错误消息?
- python - 如何将预加载的张量流常量加载到模型中
- c# - ASP.NET MVC 5 在项目之间共享包
- r - 转置数据帧
- java - XML 文本元素空白