I want to pass multiple values as a parameter to a single variable in js. how can I access these value from this variable as the parameter?
the code below is just to show you what I'm trying to achieve.
function getsum(a,b)
{
// do something
}
getsum((0,-1),-1);// for now I use parentheses (0,-1).
please help how can I pass multiple values?
You could use an array and then access the elements of the array:
function getsum(a,b)
{
// First element
firstElement = a[0];
// Second element
secondElement = a[1];
// do something
}
getsum([0,-1],-1);
use either object or array to acquire this
function getsum(a,b)
{
console.log("a,b",a,b)
// do something
}
getsum({val0:0,val1:-1},-1);
function getsum(a,b)
{
console.log("a,b",a,b)
// do something
}
getsum([0,-1],-1);
You can't. (0,-1) makes use of the comma operator. It evaluates as -1. The 0 never reaches the function.
Use an array or object instead.
Related
How can I store the output of a filter() function in an array or string to later use in another function?
jQuery('.marca').change(function(){
var regex = new RegExp(/^2x\d$/);
if(jQuery(this).find('input').prop("checked")) {
jQuery(this).nextAll().filter(function() {
// I would like to save the output from this .filter
// function to use to make a string of classes to pass to the next function.
console.log(this.className.match(regex)); //output below
return this.className.match(regex);
})
.show();
} else {
jQuery(this).nextAll().hide();
}
});
I use the above code to check the classes of a form with checkboxes and display a "subclass" only if the previous button was checked.
I use regex and filter() to find and display the next set of classes and I want to pass the resulted classes in the next jQuery selector to avoid manually adding them.
Hope I'm making some sense. Here is a fiddle with the entire code for a better understanding - https://jsfiddle.net/srjjj/brtp8x2h/9/
I have tried to simply add the result in a variable, but it won't store the entire set of values but only the last one (.2x4).
Here is the above console.log output and I guess the reason it's not working is because this is not an array of arrays but 4 different arrays but I'm not sure what to do next and how to save all of them in a variable.
console.log output
Have you tried declaring an array outside of the filter function and then pushing values in that array?
var matched = [];
jQuery(this).nextAll().filter(function () {
matched.push(yourFilteredElement);
});
Can anybody explain the flow of the code? I need to know how the function 'isEven' gets the 'x' value
$(document).ready(function(){
var array = [1,2,3,4,5];
function isEven(x){ //checks if a value is even
console.log(x)
return x % 2 == 0;
}
var newArray = array.filter(isEven); //uses a callback to check if an element is even
console.log(newArray);
});
As stated in the comment in your code, you are passing a callback, so here the current item processed in .filter() will be automatically passed to this callback function, or in other words isEven function will be called with the current item from .find() call.
As you can see in the MDN Reference for .find():
callback
Function to execute on each value in the array, taking three
arguments:
element The current element being processed in the array.
So writing:
array.filter(isEven);
Is equivalent to writing:
array.filter(function(item){
isEven(item);
});
The solution is in this line
var newArray = array.filter(isEven); //uses a callback to check if an element is even
Here you are calling the method "filter" on the array. Filter takes a method that returns true or false, and calls it on each of the array element, passing the element itself. That line could be implemented like this
let newArray;
for(let x: array){
if(isEven(x)){
newArray.push(x);
}
}
The filter() function on an array takes a function as it's input. In this case that input function is the isEven function. The filter function then iterates over the array and runs the isEven function over each of the elements. It then filters out any elements in the array for which the function returned false.
Note that in the parentheses of the filter function you do not specify any arguments to the isEven function. That is because filter does this for you.
Your code is equivalent to:
var newArray = [1, 2, 3, 4, 5].filter(x => x % 2 == 0);
The x value is taken in your first array. See the doc.
filter is a function defined in the Array API, it receives as a parameter a "this" which in your case is the variable "array" and a callback that would be "isEven", inside that "this" is the values of your array, it just need to go through it and call each one to your function.
Read this
array.filter will automatically take this as its argument if not passed, when it is getting looped. Check here for more details.
So, in case of your array this values corresponds to the elements 1,2,3,4,5
If a thisArg parameter is provided to filter, it will be used as the
callback's this value. Otherwise, the value undefined will be used as
its this value. The this value ultimately observable by callback is
determined according to the usual rules for determining the this seen
by a function.
The data I have stored is in a 2d Array.
One element of looks like below. (not an assignment operator)
someObjArray[5] === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]
For the particular above variable I want to filter on userId
I am attempting to do so like this.
var test = stuArray[5].filter(function(item) {
return item['userId'];
});
Resulting in:
test === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]
Where the desired results are
test === ["foobar1234",...]
I have also tried using a dot operator with the same results.
I don't think filter is what you're looking for here.
The function (non-anonymous in your case but you can also use anonymous functions) that you are passing into your filter method needs to return a true or a false. This is how the method "filters" your array - it gives you back an array whose elements pass the filter, or return true when passed as arguments into filter's function.
Note that this does not change the original array.
What you should use instead is the very similar map() function.
Note that map(), just like filter(), does not change the original array.
You can do it like this:
var someObjArray = [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"}];
console.log(someObjArray.map(s => s.userId));
Online demo (jsFiddle)
I have a couple of these and think (know) that I'm doing something wrong (or could be simpler).
html:
<div class='item-to-select' data-global-id='55'>some</div>
var l=$(this).map(function(){
t=new Object();
t.global_id=$(this).data('global-id');
return t;
}).get();
var list=l[0]; // want to remove this
How would I remove this intermediary object? Or a better way
thx
If you mean that you don't want to have to define the l variable just so you can use it once in setting up your list variable you can do this:
var list = $(this).map(function(){
return {
global_id : $(this).data('global-id')
};
}).get()[0]; // note the [0] directly after .get()
The return from any function that returns an array (or array-like object) doesn't have to be assigned to a variable before you can use it. So:
var temp = someFuncReturnsArray();
console.log(temp[0]);
// can be replaced by
console.log(someFuncReturnsArray()[0]);
Of course if you need to do further processing on the returned array you need to put it in a variable. E.g., if you need to test its length, or if the function could possibly return null in some situations, etc. In the example above if an empty array was returned then obviously [0] will be undefined.
But if you only need the return value once you can just use it directly.
Note that I've removed the t variable from your code too. When creating an empty object it is considered good practice to say obj = {} rather than saying obj = new Object(). But you can create an object with properties in one step if the property values are already known. In the case of your function the t object you create isn't manipulated in any way other than adding a single property to it before you return it, so you can simply return an object literal directly instead of doing it in three steps.
The jQuery .get() method accepts an index.
So, you can write :
var list=$(this).map(function(){
t=new Object();
t.global_id=$(this).data('global-id');
return t;
}).get(0);
I have an array, and I want to pass it as a parameter in a function such as:
function something(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i].value);
}
}
I'm getting that arrayP[0] is undefined, which might be true as inside the function I never wrote what kind of array arrayP is. So,
Is is possible to pass arrays as parameters?
If so, which are the requirements inside the function?
Just remove the .value, like this:
function(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i]); //no .value here
}
}
Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.
JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.
It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]?