Javascript use array in function

Как передать массив в функцию js

При объявлении (создании) функции в js мы можем в круглых скобках задать параметры этой функции. Параметры — это то, что мы планируем передавать внутрь нашей функции при её вызове. Те конкретные значения параметров, с которыми мы вызываем функцию, называют аргументами функции.

Аргументами функции могут выступать любые нужные нам данные, в том числе и массивы. В качестве примера рассмотрим функцию, которая принимает массив чисел и умножает каждое число на 2.

// объявляем функцию и задаем параметр array const multiplyByTwo = (array) =>  return array.map((number) => number * 2); >; // массив чисел, который мы хотим передать в функцию const numbers = [1, 2, 3, 4, 5]; // вызываем функцию и в качестве аргумента передаем в неё массив numbers console.log(multiplyByTwo(numbers)) // => [2, 4, 6, 8, 10] 

Пример функции myFunction с передачей массива myArray через метод apply :

function myFunction(a, b, c)  console.log(a + b + c); > const myArray = [1, 2, 3]; myFunction.apply(null, myArray); 

В данном примере мы создали функцию myFunction , которая принимает три аргумента и выводит их сумму в консоль. Затем мы создали массив myArray , содержащий три числа. И, наконец, мы вызвали функцию myFunction и передали ей массив myArray через метод apply . В результате в консоль будет выведено число 6 , которое является суммой элементов массива myArray .

Обратите внимание, что первый аргумент метода apply — это контекст, в котором будет вызвана функция. В данном примере мы передали значение null , что означает, что функция будет вызвана в глобальном контексте. Если бы мы хотели вызвать функцию в контексте какого-то объекта, мы бы передали этот объект в качестве первого аргумента метода apply .

Источник

Using an Array as Function Parameter in JavaScript

In Javascript, we often have data stored as arrays, and functions we want to call. Sometimes, the data in our arrays is exactly the data we want to pass to a function. Fortunately, there are ways in Javascript to use arrays as the input values for functions. Let’s look at how to use arrays as function parameters.

How to use arrays as function parameters

When we have a function we want to pass an array to, the most basic way to do it would be like this:

let numbers = [ 1, 2, 3 ] let myFunction = (x, y, z) =>   return x + y + z; >  // Returns 6 let getCalculation = myFunction(numbers[0], numbers[1], numbers[2]); 

Of course, this can be quite annoying, especially when working with functions which have very long lists of properties. As such, Javascript provides us with two ways to use arrays as function parameters in Javascript — apply() and the spread operator.

Passing arrays to functions with the spread operator

The modern, and easiest way to pass an array to a function is to use the spread operator. The spread operator ( . ) is simply added before the array. Using our previous example, it looks like this:

let numbers = [ 1, 2, 3 ] let myFunction = (x, y, z) =>   return x + y + z; >  // Returns 6 let getCalculation = myFunction(. numbers); 

We can also directly add the array into the function, without needing a variable. For example:

let myFunction = (x, y, z) =>   return x + y + z; >  // Returns 6 let getCalculation = myFunction(. [ 1, 2, 3 ]); 

Passing arrays to functions using apply()

The other way to do this, is to use apply() . If you’re unfamiliar with the main use case of apply() , check out my full guide on Javascript’s this object here.

Ultimately, apply() lets us take a function, and pass an array into it. The first attribute of apply() actually refers to the this object we want to use on the function. The second argument is an array of all the parameters for that function. That means you can define the structure of this as well as pass an array into the function itself.

This obviously has some specific benefits when compared to the spread ( . ) operator, so it may be more suitable depending on what you want to achieve. Using our previous example, we can pass an array into our function like so:

let myFunction = (x, y, z) =>   return x + y + z; >  // Returns 6 let getCalculation = myFunction.apply(>, [ 1, 2, 3 ]); 

Here, I am leaving the this object empty, so if we did use this in myFunction , it’d be an empty object — that’s what the first argument of apply() does. The second is our array [1, 2, 3] , referring to x , y , and z respectively.

More Tips and Tricks for Javascript

Источник

# Passing Arrays as Function Arguments

The ability to turn an array into a list of arguments is super handy with the Math functions.

# Example: Find the Largest Number

Let’s say you want to find the largest number using the Math.max() function.

const largest = Math.max(5, 7, 3, 4); console.log(largest); // 7 

But rarely, would you pass in individual values. More likely, you would want to find the maximum element in an array. So the question now is, how do you pass an array of values into a function that accepts individual arguments and NOT an array?

const numbers = [5, 7, 3]; // 🤮 Yuck! Math.max(numbers[0], numbers[1], numbers[2]); // ❌ And this won't work Math.max(numbers); // NaN 

Lucky for us, we can use ES6’s Spread operator!

const numbers = [5, 7, 3]; // 😍 Much Better! Math.max(. numbers); // 7 

What spread is doing here is taking the array element and expanding or unpacking it into a list of arguments for our variadic function.

const numbers = [5, 7, 3]; console.log(. numbers); // 5 7 3 

# Explaining spread in non-dev terms

If you find this spread-ing thing still confusing. Maybe let me try to explain it with Russian nesting dolls

. So I like to think of the array as Russian nesting dolls. And what spread does is:

  1. It unpacks (spread) the nested dolls into individual dolls.
  2. And now you have all these individual dolls (arguments) to place nicely in your display case (function).

Not sure if this explanation helps? Leave a comment if it does, and I’ll start explaining programming concepts in fun ways like this 😆

# Passing Multiple Arrays as Function Arguments

Another superpower spread has is combining arrays.

const one = [1, 2, 3]; const two = [4, 5, 6]; const merged = [. one, . two]; // [ 1, 2, 3, 4, 5, 6 ] 

So we can use this superpower to pass multiple arrays as function arguments 💪

const one = [1, 2, 3]; const two = [4, 5, 6]; Math.max(. one, . two); // 6 

For those keeners, wondering if you can pass in 3 arrays. Well, you betcha! It’s like the energizer bunny, it keeps going and going and going . (This post is not sponsored by Energizer lol. But that can change, hit me up Energizer. Me want some sponsor money 😂)

const one = [1, 2, 3]; const two = [4, 5, 6]; const three = [2, 100, 2]; Math.max(. one, . two, . three); // 100 

# What is a variadic function?

So you may notice I use the term variadic functions. The computer science folks will have probably heard this term. But for the rest of the cool bees like myself 😝, it may not be so familiar. A variadic function is a function that accepts an infinite or variable number of arguments. And the Math.max() function is one of those variadic function.

Источник

Passing Array to Function in JavaScript

Scientech Easy

Similar to C/C++/Java, we can pass the entire array as a parameter to a function in JavaScript. This method of array passing is called call by reference in JavaScript.

To pass an array argument to a function, simply pass the name of an array (a reference to an array) without brackets.

For example, if we have declared an array marks as:

let hourlyTemp = new Array(30);

then function call statement:

passes array hourlyTemp to the function modifyArray(). JavaScript automatically passes arrays to functions using call-by-reference (or passed by reference).

Function Receiving an Array via Function Call

For a function to receive an array via a function call, you must specify a parameter in the function’s parameter list that will refer to the array in the function body.

Unlike other programming languages, JavaScript does not hand over any specific syntax for this purpose. JavaScript simply needs that the name of an array to be specified in the function parameter list.

For example, we can write the function definition for the function modifyArray as:

The above function definition indicates that modifyArray() receives an array of integers in parameter x (the argument supplied in the calling function must be an array).

When the called function uses the array name x, it points to the original array in the caller (array hourlyTemp).

Therefore, when the called function updates any array elements in its function body, it is updating the actual elements of the array in their original memory locations.

Passing Array to Function as Pass by Reference

1. Let’s create a JavaScript program in which we will pass an initialized array to a function. Then, we will multiply each array element by 5 and display it.

  
Output: Original array elements are: 20 10 25 15 35 40 Modified array elements: 100 50 125 75 175 200

In this example program, we have passed an array nums into modifyArray() as pass by reference. That is, the parameter nums is passed into modifyArray() function with reference to x. Inside the function the array elements are multiplied by 5 and displayed.

  
Output: Original array elements are: 10 20 30 40 50 Modified array elements are: 20 40 60 80 100

Passing Individual Array Element to Function as Pass by Value

Let’s create a JavaScript program in which we will pass the entire array as a pass by reference to the function in JavaScript. Then we will pass the individual array element to the function as a pass by value in JavaScript.

Program code 3:

  
Output: Original array: 10 20 30 40 50 Modified array: 40 80 120 160 200 nums[3] before modifyElement: 160 nums[3] after modifyElement: 480

Although the entire array is passed by reference, whereas individual numeric and boolean array elements are passed by value.

To pass an element of an array to a function, use the sub-scripted name of the element as an argument value in the function call.

In this tutorial, you learned an interesting topic “passing array to function in JavaScript” with many example programs. Hope that you will have understood how to pass an individual element of an array in JavaScript.
Thanks for reading.
Next ⇒ Arrays methods in JavaScript ⇐ Prev Next ⇒

Источник

Pass Array to a Function in JavaScript

Pass Array to a Function in JavaScript

  1. Use the apply() Method to Pass an Array to a Function in JavaScript
  2. Use the spread Operator to Pass an Array to a Function in JavaScript
  3. Use the arguments Object to Pass an Array to a Function in JavaScript

This tutorial aims to teach you the different ways of passing an array to a function using JavaScript. It highlights the apply() method, spread operator, arguments object, and the way to pass an entire array to a function as a parameter.

The apply() method executes a function with this value and gives arguments as an array or array-like object. It is used on a particular function that has to be passed.

In the apply() method, this value is the first parameter that calls to the function, and arguments are the second with the array of arguments to be passed.

Remember, if this value cannot be the original value seen by a function (if the method is a function in non-strict mode code). The global object will be null and undefined , while primitive values will be boxed.

ECMAScript 6 (ES6) provides an amazing operator named spread . It is written as . within the JavaScript code. This operator allows iterable, for instance, arrays. It is used to process all the array elements or an object.

On the other hand, the arguments object is an array-like (means the arguments have the length property) object that we can use within the function that has the arguments’ values.

Источник

Читайте также:  Javascript обязательные поля формы
Оцените статью