Javascript return function with arguments

Javascript: return function with predefined arguments

Solution 1: Passing arrays to functions is no different from passing any other type: However, your function is not necessary, since Javascript has a built-in function for concatenating array elements with a delimiter: Solution 2: You’re over complicating things — JavaScript arrays have a built-in method: EDIT: simpler still: the method: Solution 3: The easiest would be to use the built-in method: Anyway, your problem was in the for..in loop Instead of this: You should have: Because for. in gives back the index/key, not the actual element as does in other languages Also your call should be: or just Cheers Solution 4: Js argument can be any type and no limit to the number of argument, And default array obj has many build-in func; for example:Passing arrays as function arguments

Return array from function

—Solved by Elliot B. Thanks! May also take int account the other modifications.

Here is the result. Thanks, everyone, for the speedy answers! http://dl.dropbox.com/u/18785762/Rust/index.html

I’m writing a game in javascript, and I want to keep the files for matching block IDs to files in a seperate .js file from the map compiler, so that I can edit things easily. However, the IDs are stored in an array, and I can’t seem to get it to use the return function properly. Any help?

function drawmap() < var images = BlockID(); var level = [ "ssssssssssssssssssssss", "sgggggggggCCCCCdddddss", "ssssssssss sssssss" ]; var top = 100; var left = 100; var mytop = top; var myleft = left; for (y=0; ymytop += 13; myleft += 27; > mytop = top + (y+1)*13; myleft = left - (y+1)*27; > > 

There are a couple fixes to point out. First , images is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images to IDs . Second , you want to return an Object , not an Array . An object can be assigned property values akin to an associative array or hash — an array cannot. So we change the declaration of var IDs = new Array(); to var IDs = new Object(); .

Читайте также:  Bug report page php

After those changes your code will run fine, but it can be simplified further . You can use shorthand notation (i.e., Object Literal Property Value Shorthand) to create the object and return it immediately:

Your BlockID function uses the undefined variable images , which will lead to an error. Also, you should not use an Array here — JavaScripts key-value-maps are plain objects:

Taking in consideration that in JavaScript Array is object too this can be written as:

This code will display content of array in browser’s window

window.onload=function()< var s=""; var ar = BlockID(); //function return array for(el in ar)< s+=ar[el]+"
"; > document.body.innerHTML=s; >;

Javascript — Return array from function, I’m writing a game in javascript, and I want to keep the files for matching block IDs to files in a seperate .js file from the map compiler, so that I can edit things easily. However, the IDs are stored in an array, and I can’t seem to get it to use the return function properly. Any help? drawmap.js: Code samplevar IDs = new Array();images[‘s’] = «Images/Block_01.png»;images[‘g’] = «Images/Block_02.png»;images[‘C’] = «Images/Block_03.png»;images[‘d’] = «Images/Block_04.png»;Feedback

Javascript: return function with predefined arguments

and in some scope want to get something like this:

where my1 and my2 are defined somehow in this scope. So I should get a parameterless function b, which when called calls a with fixed parameters my1 and my2. Now, the question is, why this is not right, and which is 🙂

UPD: Ok, I had some callbacks in those params, now found out, how to process them all. What I missed was to apply the technique twice. Thank you.

Just make a function that returns a new function b:

Write a function that takes my1 and my2 and creates function b:

I’m not sure if I understood you correctly, but you can look at a concept called currying. It is possible to curry a function in Javascript such that you can obtain another function with some or all of the parameters preset.

You can look at an implementation here.

If you are using Prototype, you can obtain the function b this way.

now calling b() is the same as calling a(arg1, arg2)

Why is this not right? Are you getting an error? I tried to reproduce a working sample based one your description and what I have works so perhaps you could post a more detailed sample:

  

Edit

Based on your comment to another answer I updated my sample to show how you can wrap a function.

Edit 2

Ok so I replaced them with variables;-)

Javascript: return function with predefined arguments, Javascript: return function with predefined arguments. function a (p1, p2) < /* */ >where my1 and my2 are defined somehow in this scope. So I should get a parameterless function b, which when called calls a with fixed parameters my1 and my2. Now, the question is, why this is not right, and which is …

How to pass an array as argument to a function in javascript?

I’m trying to make helper functions to make use of the Google Analytics API, and I have a simple problem building strings. The scenario is, I have to apply a filter, and there may be n number of filters (a nominal amount, not more than 128 anyhow). I wanted to write a function which can take in the n strings and combine them with comma-separation in between.

I don’t know if the number of arguments can be variable in javascript, and if it can take arrays as arguments in javascript (I am a newbie to JS), but I see no difference as variables are simply var and there is no datatype anywhere in JS (I come from a C++/Java background and find it confusing as it is). So I tried passing an array as an argument to a function so that the no. of things I can work with can be dynamic, decided by the elements in the array.

When I started searching for solutions, I came across this page. After that I recently came across this thread which also refers the same link and the format they have provided does me no good.

For the sake of clarity, let me provide the function definition I’ve written.

/** * Utility method to build a comma-ed string from an array of strings * for the multiple-condition requests to the GA API */ function buildString(strArray)

And this is how I call it:

buildString.apply(this,[desc(visits),source]) 

where desc(visits) and source are both strings, so I assumed I’m sending an array of strings. Strangely, both this and null in the apply() call to the buildString function give me «0,1» as the return value.

Please tell me where I’m going wrong. Am I passing the array in a wrong manner? Or is my function definition wrong? Or is there some other simpler way to achieve what I’m trying?

Passing arrays to functions is no different from passing any other type:

var string = buildString([desc(visits), source]); 

However, your function is not necessary, since Javascript has a built-in function for concatenating array elements with a delimiter:

var string = someArray.join(','); 

You’re over complicating things — JavaScript arrays have a built-in join method:

EDIT: simpler still: the toString method:

[ desc( visits ), source ].toString(); 

The easiest would be to use the built-in join method:

Anyway, your problem was in the for..in loop

Because for. in gives back the index/key, not the actual element as foreach does in other languages

buildString.call(this,[desc(visits),source]) or just buildString([desc(visits),source])

Js argument can be any type and no limit to the number of argument,

But it is recommanded use 3-4 arguments at most, if there are more args, you can pass it as an object or array.

You don’t need to worry about the type of args, js will do the job.

var func1 = function(a) < console.log(a); >func1('good'); func1(1); func1(['good', 'a', 1]); func1(); 

You can even define a function with three arguments, but only pass one is ok!

var func2 = function(a, b, c) < console.log(a); >func2(1); func2(1, 'good'); func2(1, 'good', 'night', 4); 

And default array obj has many build-in func; for example:

var arr = ['good', 'night', 'foo', 'bar']; //define any thing in a array str = arr.join(','); //you may get 'good,night,foo,bar' var arr1 = str.split(','); // you may get ['good', 'night', 'foo', 'bar']; 

How to pass an array as argument to a function in, Passing arrays to functions is no different from passing any other type: var string = buildString ( [desc (visits), source]); However, your function is not necessary, since Javascript has a built-in function for concatenating array elements with a delimiter: var string = someArray.join (‘,’); Share.

How to pass arrays as function arguments in JavaScript?

Passing arrays as function arguments

In olden days if we need to pass arrays as function arguments then apply() and null should be used. The use of null makes a code unclean . So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread operator we don’t need to use apply() function. Lets’ discuss it in a nutshell.

Example

In the following example, we have used null and apply() to pass an array as a function argument. This is an obsolete method. This method is replaced by a modern method in which spread operator is used.

     
Output

If we observe the following example, apply () function and null weren’t used, instead of those ES6 spread operator is used. The use of spread operator makes the code urbane and there is no need to use useless null value.

Example
     
Output

How to pass arrays as function arguments in JavaScript?, Passing arrays as function arguments. In olden days if we need to pass arrays as function arguments then apply () and null should be used. The use of null makes a code unclean. So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread …

Источник

return

Оператор return завершает выполнение текущей функции и возвращает её значение.

Интерактивный пример

Синтаксис

Выражение, значение которого будет возвращено. Если не указано, вместо него возвращается undefined .

Описание

При вызове оператора return в функции её выполнение прекращается. Указанное значение возвращается в место вызова функции. Например, приведённая ниже функция возвращает возведённое в квадрат значение своего аргумента, x (где x – это число):

function square(x)  return x * x; > var demo = square(3); // значение demo будет равняться 9 

Если возвращаемое значение не указано, вместо него возвращается undefined .

Следующие выражения всегда прерывают выполнение функции:

return; return true; return false; return x; return x + y / 3; 

Автоматическая расстановка точек с запятыми

На выражение return влияет автоматическая расстановка точек с запятыми (ASI). Разрыв строки не допускается между ключевым словом return и выражением.

В консоли появится предупреждение «unreachable code after return statement».

Примечание: Начиная с Gecko 40, предупреждение в консоли появляется, если обнаружен недостижимый код после return .

Для того, чтобы избежать данной проблемы (предотвратить ASI), можно использовать скобки:

Примеры

Прерывание функции

Функция немедленно останавливается в точке, где вызывается return .

function counter()  for (var count = 1; ; count++)  // бесконечный цикл console.log(count + "A"); // до 5 if (count === 5)  return; > console.log(count + "B"); // до 4 > console.log(count + "C"); // никогда не появляется > counter(); // Выводит: // 1A // 1B // 2A // 2B // 3A // 3B // 4A // 4B // 5A 

Возвращение функции

function magic(x)  return function calc(x)  return x * 42 >; > var answer = magic(); answer(1337); // 56154 

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 17 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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