Return javascript не работает

Почему «return» не возвращает значение?

Код выше определенно находит необходимый Cell (так как console.log() выводит то, что необходимо). Но вот return это значение не возвращает. Для меня остается непонятным, почему код ниже работает как надо, а этот код работать не хочет. Прошу объяснить.

Кстати, хотелось бы добавить. Мне необходимо, чтобы, когда нужный элемент найден, он тут же возвращался бы, не заставляя цикл доходить до конца (заведомо известно, что найден может быть только один элемент). Тут дело в том, что поиск будет производится по довольно большому количеству элементов, и лишние проверки тут ни к чему. Поэтому как только элемент найден — нужно его сразу вернуть. А Debug-Console в Chrome показывает мне, что даже после того, как элемент найден и return сработал, цикл продолжает выполняться в поисках других элементов, что в корне неверно, ведь return должен не только вернуть значение, но и прекратить выполнение блока, в котором он находится (насколько мне известно).

1 ответ 1

Вы используете метод map , который возвращает новый массив, где каждый элемент является результатом вызова функции, которую вы передает в качестве параметра

На простом примере

Что происходит в этом коде: мы передаем map функцию n => n * 2 , это значит, что мы пройдет по нашему массиву циклом, умножим каждый элемент массива на 2 и из результатов создадим новый массив, который будет записан в переменную doubleNums

Поэтому ваш код работает не так как вы ожидаете, он не вернет вам нужную ячейку, а просто вызовет функцию для каждого элемента вашего массива.

В вашем случае лучше использовать метод filter , который так же вызывает функцию для каждого элемента, но в новом массиве будут только те элементы, при которых функция, которую мы передали как аргумент в filter , вернула true

Читайте также:  Как настроить смоант пасито

На простом примере

На вашем примере

UPDATE

Если хотите оптимизировать кода, то тогда воспользуйтесь циклом

Источник

javascript function return not working

I have a problem returning a variable in my function, the below script works fine:

Bet when I try the following I get a message box with the message «undefined»:

This is really bugging me, I just can’t seem to see what I’ve done wrong.

7 Answers 7

There are two things you should know:

1: the JSON thing is asynchronous, so the function call to sessionStatus could already be done when the JSON is still being fetched. The following would work:

2: even when it would be synchronous, you are only giving a return value from the inner function, so the sessionStatus would return nothing. Check out this code (not related to your JSON thing):

Both return 2. Hopefully this explains a bit.

Your function sessionStatus() doesn’t return anything, hence the alert says undefined .

All the function does is set thing up for the AJAX call to happen once the page loads — nothing actually happens within sessionStatus() that could be returned.

The code in function(status) < . >doesn’t get run until the AJAX call to the server returns a value, and that AJAX call doesn’t get sent until the page loads.

You ought to read up on what $.getJSON() and $(document).ready() actually do, because you’re going to continue to get confusing behaviour until you understand them properly.

Your sessionStatus() function never returns anything. It sets a function to run later, and that function returns something, but that’s not anything to do with sessionStatus()

Читайте также:  Кнопочный филипс как настроить звук

You’re returning a value when the document ready event is done. Where is your value supposed to go? The jQuery object doesn’t know what to do with it.

The function sessionStatus just sets up the event listener for $(document).ready() and then returns without returning a value. That’s the undefined you see.

Later when $(document).ready() fires it calls the ajax which if it succeeds returns the status, but nothing is receiving that status.

Your function is being called asynchronously — actually after two asynchronous calls, made via .ready() and .getJSON(). In such a case there is no available return value, instead you have to use a callback, as in the above, to process the response.

Though I should note that the function passed to getJSON in the above already is a callback. You could change that function definition to just be «sessionStatusCallback» and it would call the above callback once the JSON was ready, and you could continue to process there. Or. continue your processing in the current callback (it’s a matter of style whether to use a function reference or declare the anonymous function right there in the .getJSON() call)

Functions should never be included in a jQuery(document).ready function. Separate them, so you don´t have side effects you don´t want to have. How do you want to call the session status? And witch function should get the return value?

Источник

Оцените статью