Converting an Arrow Style function to “function” style

≡放荡痞女 提交于 2021-02-05 06:36:43

问题


I have a function like this:

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;

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.


回答1:


Working Snippet

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;

Explanation

  1. Fat arrow (=>) returns anything written on the right side by default (i.e. without a block as a body)
  2. While porting to a function expression or declaration, we need to explicitly use the return keyword.



回答2:


const item = properties.reduce((obj, prop) => obj && obj[prop], jsonObject);

Is similar to

const item = properties.reduce(function(obj, prop){
   return obj && obj[prop];
}, jsonObject);

Read more about .reduce and its arguments here




回答3:


Yes, the correct translation would be:

function(obj, prop) {
    return obj && obj[prop];
}



回答4:


In your code:

const item = properties.reduce(function(obj, prop){
  if(obj && obj[prop]) return obj[prop];
});

You are never passing the jsonObject in as the second parameter to the function, so .reduce doesn't know what to enumerate on. The correct way of doing it is:

const item = properties.reduce(function(obj, prop){
  if(obj && obj[prop]) return obj[prop];
}, jsonObject);



回答5:


An awesome online tool BabelJs

It can help you with converting your ES6 to ES5 without much effort. However I recommend understanding how its doing the conversion

   'use strict';

    var jsonObject = { a: { b: 'c' } };
    var x = 'a.b';
    var properties = x.split('.');

    var item = properties.reduce(function (obj, prop) {
      return obj && obj[prop];
    }, jsonObject);

    console.log(item);



回答6:


You may add a default value for preventing a not given property in the object.

const item = properties.reduce(function (obj, prop){
        return (obj || {})[prop];
    }, jsonObject);


来源:https://stackoverflow.com/questions/49074757/converting-an-arrow-style-function-to-function-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!