将箭头样式功能转换为“功能".风格 [英] Converting an Arrow Style function to "function" style
本文介绍了将箭头样式功能转换为“功能".风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的功能:
const jsonObject = {a: {b: 'c'}};
const x = 'a.b';
const properties = x.split('.');
const item = properties.reduce((obj, prop) => obj && obj[prop], jsonObject);
console.log(item); // prints 'c;
此函数动态遍历jsonObject并打印值.
This function, dynamically traverses the jsonObject and prints the value.
这很好用,但是这种声明方式不支持我的环境.因此,我想将其转换为函数样式声明,如下所示:
This works fine, but this style of declaration doesn't support my environment. So I wan trying to convert this to function style declaration something like this:
const item = properties.reduce(function(obj, prop){
if(obj && obj[prop]) return obj[prop];
});
但这似乎不起作用.其打印(项目)未定义.
But this doesn't seems to be working. Its printing (item) undefined.
推荐答案
工作片段
const jsonObject = {
a: {
b: 'c'
}
};
const x = 'a.b';
const properties = x.split('.');
const item = properties.reduce(function(obj, prop) {
return obj && obj[prop];
}, jsonObject);
console.log(item); // prints 'c;
说明
- 默认情况下,胖箭头(=>)返回任何写在右侧的内容(即,没有块作为主体)
- 在移植到函数表达式或声明时,我们需要显式使用
return
关键字.
这篇关于将箭头样式功能转换为“功能".风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文