Javascript вернуть массив функции

JavaScript How to Return Multiple Values? [Examples & Theory]

The easiest way to return multiple values in JavaScript is by returning an array of multiple elements.

Then, you can access the returned values like this:

let values = getVals() let first = values[0] let second = values[1]

If you were looking for a quick answer, then there you have it! But to write clean code, the above isn’t always the best way to return two values. Instead, you can return “labeled” values by returning an object.

This guide teaches you how to return multiple values in JavaScript in a couple of ways.

Returning Multiple Values in JavaScript

In JavaScript, you have probably written a bunch of functions that return a single value. For instance:

But what if you want to write a function that returns multiple values.

Solution 1: Return Multiple Values in an Array

A naive yet simple way to return multiple values is by returning the values in an array.

For example, let’s create a function that returns the sum and the product of two numbers:

Читайте также:  Java sun security util

Now, when you call this function, you need to store the returned array into a variable and then access the two values.

let results = sumMul(2, 5) let sum = results[0] let mul = results[1] console.log(sum, mul)

Also, thanks to the latest updates in JavaScript (ECMAScript 6), you can restructure the return value more intuitively.

So instead of storing the returned value into a variable and then one by one picking the values from it, you can use shorthand. Here is how:

let [sum, mul] = sumMul(2, 5) console.log(sum, mul)

This code looks already more understandable.

But there is another way to return multiple values, which is even more intuitive and maintainable.

Solution 2: Return Multiple Values in an Object

Instead of returning the values in an array, you can place them inside an object and label the values. This makes it easier and more intuitive to access.

Let’s re-write the sumMul function in the previous example to employ this strategy:

If you now call this function, there is a more intuitive way to access the returned values:

let result = sumMul(2, 5) let sum = result.sum let mul = result.mul console.log(sum, mul)

As you can see, now you can reference the return values by their name. This makes the code more readable and less error-prone. Now it’s harder to accidentally mess up with the values as they are labeled clearly.

Wrap Up

Today you learned how to return multiple values from a function in JavaScript.

To recap, there are two ways to do it:

  • Return an array of multiple values. This is the most obvious and straightforward way. However, it lacks readability as you need to refer to the returned values by index.
  • Return an object with “labeled” values. This approach requires slightly more code but is the most reliable. By labeling the return values, it’s hard to mess things up. This is because you can refer to the returned values by their names.

Источник

Возврат нескольких значений из метода в JavaScript

В этом посте мы обсудим, как вернуть несколько значений из метода в JavaScript.

1. Вернуть массив

Идея состоит в том, чтобы упаковать возвращаемые значения внутри массива и вернуть этот массив из метода. В следующем примере кода показано, как это реализовать:

В следующем коде используется присваивание деструктуризации распаковывать значения из массивов в соответствующие переменные.

2. Вернуть объект

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

Код можно упростить, используя присваивание деструктуризации:

Это все о возврате нескольких значений из метода в JavaScript.

Средний рейтинг 5 /5. Подсчет голосов: 22

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Returning Multiple Values from a Function

Summary: in this tutorial, you will learn to define JavaScript functions that return multiple values.

JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.

Returning multiple values from a function using an array

Suppose the following getNames() function retrieves the first name and last name from a database in the backend or from the result of a third-party API call and returns them as elements of an array:

function getNames( ) < // get names from the database or API let firstName = 'John', lastName = 'Doe'; // return as an array return [firstName, lastName]; >Code language: JavaScript (javascript)

The following shows how to get the return value from the getNames() function:

let names = getNames();Code language: JavaScript (javascript)

Because the names variable is an array, you can reference its elements using the square brackets, like this:

const firstName = names[0], lastName = names[1];Code language: JavaScript (javascript)

In ES6, you can use the destructuring assignment syntax to unpack values from an array more intuitively, like this:

const [firstName, lastName] = getNames();Code language: JavaScript (javascript)

In this code, the firstName and lastName variables will take the first and second elements of the return array.

Returning multiple values from an function using an object

If you want to assign a name to each returned value to make it more readable and easier to maintain, you can use an object:

function getNames( ) < // get names from the database or API let firstName = 'John', lastName = 'Doe'; // return values return < 'firstName': firstName, 'lastName': lastName >; >Code language: JavaScript (javascript)

Since the names of the properties are the same as the variables, you can shorten it using the object literal syntax extensions in ES6 as follows:

function getNames( ) < // get names from the database or API let firstName = 'John', lastName = 'Doe'; return < firstName, lastName >; > Code language: JavaScript (javascript)

And you can get the return value as an object like this:

let names = getNames(); let firstName = names.firstName, lastName = names.lastName;Code language: JavaScript (javascript)

If you want to unpack properties from an object, you can use the object destructuring syntax as follows:

let < firstName, lastName >= getNames();Code language: JavaScript (javascript)

Summary

  • JavaScript doesn’t support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.
  • Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Источник

Как функцией в JS возвратить массив (объект)?

eca28a6df3494898a52a44f25dbbd7a5.jpg

Как функцией в JS возвратить массив (объект)?
Пробую возвратить — не получается. Вот код:

$(document).ready( function() < console.log(getStreets('Вовчинець') ); >); function getStreets(city) < $.post( 'export/getStreets.php', < misto_selo_key: city >) .done( function( data ) < var availableTags = data.split(","); var availableTagsArr = []; availableTags.forEach(function (street_name) < parts = street_name.split("&"); availableTagsArr.push(); >); console.log(availableTagsArr); return availableTagsArr; >); >

tratotui

Что вы собственно ждете, когда функция getStreets ничего не возвращает — это раз. А второй момент — это то, что загрузка данных может наступить после события ready

Ребята, не в асинхронности дело, а в том что return срабатывает для $.post метода ( спасибо тебе tratotui), а не для getStreets(city), так как он находиться внутри метода.
Я поборол эту проблему следующим путем: перед $.post методом создал массив пустой, после неасинхронного запроса возвращаю массив внутри функции getStreets. Собственно всё. Очень благодарен за помощь!

pavel_salauyou

никак это ajax, как вариант можно передавать callback функцию, например,

getStreets('Вовчинець', function(response) < console.log(response); >) а в методе done вызывать её function getStreets(city, callback) < // . .done( function( data ) < // . callback(availableTagsArr); >

TekVanDo

$.post — асинхронный метод — и данные в колбэк done приходят позже чем срабатывает console.log (первый), т.ч. в данном конкретно примере вернуть нельзя. Слушайте событие или используйте промисы.

Войдите, чтобы написать ответ

Как из коллекции, получить Input в котором произошло изменение?

Источник

Как вывести массив из функции JavaScript?

Мне нужно иметь в одном массиве значения с нескольких XML-страниц, т.е. функция должна проходить по page1.xml, page2.xml, page3.xml.

Подскажите, друзья знатоки, в чем моя ошибка. Поправьте руки. Спасибо.

my_func('http://site.ru/page1.xml'); console.info( array ); // undefined

bingo347

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

abyrkov

Я думаю, создать на эту тему статью/репозиторий, что бы можно было со спокойной совестью отдавать им. А не объяснять в стопицотый раз

dmitry_luzanov

abyrkov

abyrkov

Ваш код в третей функции исполняется во второй(которую мы вызываем), в первой ни array, ни return array доступен не будет. Более того, если сделать так:

Будет возвращать пустой массив!
В чем же дело? Вы отправляете запрос на сервер, а код исполняется дальше. То есть третья функция может быть вызвана в любой момент — когда придет ответ от сервера. Можно использовать сихронный вариант, но это плохая идея.
Решения, как всегда, два: callback и Promise.
Решение с callback:

function(callback) < func(function() < var array = new Array(); callback(array); >) > // Использование func(function(array) < console.log(array); >);
function() < return new Promise(function(resolve) < func(function() < var array = new Array(); resolve(array); >); >); > // Использование func().then(function(array) < console.log(array) >);

Источник

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