Показать сообщение отдельно
  #2 (permalink)  
Старый 17.02.2020, 19:44
Профессор
Отправить личное сообщение для Nexus Посмотреть профиль Найти все сообщения от Nexus
 
Регистрация: 04.12.2012
Сообщений: 3,726

(() => {
    const arrayNumbers = [-5, 0, 5, 10, 15, 20, 25, 30, 35];
    const n = 23.45
    const res = arrayNumbers[arrayNumbers.reduce(function (res, value, index) {
        return (value = Math.abs(n - value)) < res.value ? {index, value} : res;
    }, {index: null, value: Infinity}).index];

    alert(res);
})();


upd.
(() => {
    const n = prompt('Enter the number', 11.38) || 23.45;
    const arrayNumbers = [-5, 0, 5, 10, 15, 20, 25, 30, 35];
    const res = arrayNumbers[arrayNumbers.reduce(function (res, distance, index) {
        return (distance = Math.abs(n - distance)) < res.distance ? {index, distance} : res;
    }, {index: 0, distance: Infinity}).index];

    alert(`n = ${n}; res = ${res}`);
})();

Последний раз редактировалось Nexus, 17.02.2020 в 19:58.
Ответить с цитированием