Как вернуть значение из функции, использовать это значение, чтобы составить математическую формулу, и pu sh решение (ключ / значение) для массива объектов? - PullRequest
2 голосов
/ 13 апреля 2020

Это задача упражнения, которую мне нужно решить:

"1- Сначала создайте массив объектов, называемых данными, со следующими значениями:

  1. Principal- 2500, time- 1.8

  2. Principal- 1000, time- 5

  3. Principal- 3000, time- 1

  4. Principal- 2000, time- 3

  NB: Each individual object should have 'principal' and 'time' as keys.

2- Напишите функцию с именем "InterestCalculator", которая принимает массив в качестве одного аргумента и выполняет следующие действия:

  Determine the rate applicable using the conditions:

  If the principal is greater than or equal to 2500 and the time is greater than 1 and less than 3, then rate = 3

  If the principal is greater than or equal to 2500 and the time is greater than or equal to 3, then rate = 4

  If the principal is less than 2500 or the time is less than or equal to 1, then rate = 2

  Otherwise, rate = 1;

3- Рассчитывает проценты для каждого отдельного объекта по формуле: (принципал * ставка * время) / 100.

4- Функция должна возвращать массив объектов с именем «InterestData», и каждый отдельный объект должен иметь «принципал», «рейтинг», «время» и «интерес» в качестве ключей с соответствующими значениями. .

5- Записать массив 'InterestData' в консоль ДО вашего оператора возврата.

6- Наконец, вызовите / выполните функцию и передайте созданный вами массив 'data'.

Что я делал до сих пор: Я сделал массив с объектами с двумя свойствами (принципалом и временем) с их значениями. Затем я создал функцию, которая будет делать al oop в каждом объекте и вычислять ставку (которая еще не включена в объект), затем я хочу вернуть для каждого объекта значение ставки и вычислить формулу ((принципал * скорость * время) / 100) после этого я хочу создать новый массив, включающий эти два новых свойства (данные о процентах и ​​процентах) и их значения. Кто-нибудь может помочь мне решить эту проблему, объясняя с комментариями?

Вот мой код:

const Data = [
  {
    principal: 2500, //3
    time: 1.8
  },
  {
    principal: 1000, //1
    time: 5
  },
  {
    principal: 3000, //1
    time: 1
  },
  {
    principal: 2000, //2
    time: 3
  }
];

const interestCalculator = Data => {
  // here I create a forEach loop
  Data.forEach(individualData => {
    // here I start the rate with empty string
    let rate = "";

    //use if...else statement to return the rate for each indivual Object
    if (individualData.principal >= 2500 && individualData.time > 1 && individualData.time < 3) {
      rate = 3;
    } else if (individualData.principal <= 2500 || individualData.time <= 1) {
      rate = 2;
    } else {
      rate = 1;
    }

    return rate;
  });

  // stoped here and I need help to solve the challenge
};

Ответы [ 3 ]

5 голосов
/ 15 апреля 2020

Вы почти закончили, хороший подход до сих пор.

Во-первых, вы сказали бы "Я хочу создать новый массив, включающий эти два новых свойства" , затем вам следует взгляните на эти супер методы,

Эти методы противоположны друг другу. Таким образом, используя эти методы, вы можете deep-clone ваш массив следующим образом:

let newData = JSON.parse(JSON.stringify(Data));

Обратите внимание, что вы можете устанавливать новые свойства в JS объектах, таких как,

Object.property = value;

Теперь вам нужно установить свойство rate, затем выполнить

// set the property rate
individualData.rate = rate; 

Аналогично, вы можете установить и другие свойства. Кроме того, если вы хотите получить какое-либо свойство, вы можете просто сделать

console.log(Object.property);

Итак, вы можете рассчитать проценты следующим образом

// calculate the interest with the formula
individualData.interest = individualData.principal * individualData.rate * individualData.time / 100;

Мы почти закончили! Наконец, для записи результирующего массива объектов, return значение

return newData;

const Data = [
  {
    principal: 2500, //3
    time: 1.8
  },
  {
    principal: 1000, //1
    time: 5
  },
  {
    principal: 3000, //1
    time: 1
  },
  {
    principal: 2000, //2
    time: 3
  }
];

const interestCalculator = Data => {
  // The following method is best to deep-clone an array!
  // Very important method for development purpose
  let newData = JSON.parse(JSON.stringify(Data));
  
  // here I create a forEach loop
  newData.forEach(individualData => {
    // here I start the rate with empty string
    // NO, rate is integer, so initiate it with a number, eg. 0
    let rate = 0;

    // use if...else statement to return the rate for each individual Object
    if (individualData.principal >= 2500 && individualData.time >= 3) {
      rate = 4;
    } else if (individualData.principal >= 2500 && individualData.time > 1 && individualData.time < 3) {
      rate = 3;
    } else if (individualData.principal < 2500 || individualData.time <= 1) {
      rate = 2;
    } else {
      rate = 1;
    }

    ///// I ADDED LINES HERE /////
    
    // set the property rate
    individualData.rate = rate; 
    
    // calculate the interest with the formula
    individualData.interest = individualData.principal * individualData.rate * individualData.time / 100; 
  });
  
  // return the Data array with rate and interest inserted to each objects
  return newData; // very important!
};

console.log('Original array', Data);

console.log('New array', interestCalculator(Data)); // log the returned value

РЕДАКТИРОВАТЬ: Я думаю, что вы забыли добавить второе условие для расчета ставки. Я добавил это в приведенном выше фрагменте. Кроме того, в вашем коде, вы бы опечатали, относительно последнего условия. individualData.principal < 2500 (меньше).

2 голосов
/ 15 апреля 2020

Поэтому я использовал map, чтобы изменить массив, и создал функцию, которая вычисляет rate (просто для хорошей практики), а также добавил пропущенный регистр в ставке (у вас нет ставки 4).

Я думаю, что это выглядит намного более читабельным, и нетрудно добавить ключи к объектам, просто попробуйте это: D

const data = [{
    principal: 2500, //3
    time: 1.8
  },
  {
    principal: 1000, //1
    time: 5
  },
  {
    principal: 3000, //1
    time: 1
  },
  {
    principal: 2000, //2
    time: 3
  }
];

function interestCalculator(data) {
  // deep copy the original array
  let newData = JSON.parse(JSON.stringify(data))
  newData.map(item => {
    item.rate = getRate(item.principal, item.time);
    item.interest = (item.principal * item.rate * item.time) / 100;
    return item;
  });
  console.log(newData);
  return newData;
};

function getRate(principal, time) {
  if (principal >= 2500) {
    if (time > 1 && time < 3)
      return 3;
    else if (time == 3) return 4;
  } else if (principal <= 2500 || time <= 1) {
    return 2;
  }
  return 1;

}

interestCalculator(data);
1 голос
/ 16 апреля 2020

Здесь я пытаюсь написать программу с соответствующей документацией. Вы можете прочитать это. Если у вас есть какие-либо вопросы, свяжитесь со мной.

const Data = [{principal: 2500,time: 1.8}, {principal: 1000,time: 5}, {principal: 3000,time: 1}, {principal: 2000,time: 3}];

const interestCalculator = (data) => {
    /**
     * Iterate through the data array using `Array.prototype.map()`
     * The map will visit every element of the array and after
     * performing it's job it returns a new array.
     *
     * Here we store our returning array into `interestData` array
     *
     */
    const interestData = data.map(item => {

        if (item.principal >= 2500 && (item.time > 1 && item.time < 3)) {
            /**
             * If the principal is greater than or equal to 2500
             * and the time is greater than 1 and less than 3,
             * then rate = 3
             */
            item.rate = 3;
        } else if (item.principal >= 2500 && item.time >= 3) {
            /**
             * If the principal is greater than or equal to 2500
             * and the time is greater than or equal to 3,
             * then rate = 4
             */
            item.rate = 4;
        } else if (item.principal < 2500 || item.time <= 1) {
            /**
             * If the principal is less than 2500
             * OR the time is less than or equal to 1,
             * then rate = 2
             */
            item.rate = 2;
        } else {
            item.rate = 1;
        }

        /**
         * Calculate the interest and insert it into the object
         * of array element
         *
         */
        item.interest = (item.principal * item.rate * item.time) / 100;

        return item;
    });

    /**
     * Console the calculated Data using `console.table()`
     * The console.table() will show you a beautiful tabular
     * form of your data.
     */
    // console.table(interestData);
    console.log(interestData); // For displaying into stackoverflow's snippet I use log instead of table.

    // Return the new array
    return interestData;
}

// Call the function for execution.
interestCalculator(Data);
.as-console-wrapper {min-height: 100% !important; top: 0;}

Вот как console.table() показывает на выходном терминале vscode. enter image description here

И это chrome вид консоли enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...