How can I pass an array as arguments to a function? [duplicate] - javascript

This question already has answers here:
Passing an array as a function parameter in JavaScript
(12 answers)
Closed 6 years ago.
if(a == 1){
parameter = ['1','true','a'];
}else{
parameter = ['2','false','b'];
}
function run(a,b,c){
}
How can I pass an array as arguments to the function run? I tried JSON.Stingify but it doesn't work as I'm still seeing the array bracket in my console.log()

You can use javascript apply():
run.apply(this, parameter);

Here are two options.
Call the function directly.
if(a == 1){
run('1', 'true', 'a');
}else{
run('2', 'false', 'b');
}
Or use Function.prototype.apply to call the function with an array as arguments.
if(a == 1){
parameter = ['1','true','a'];
}else{
parameter = ['2','false','b'];
}
run.apply(null, parameter);

Just do it like this:
http://codepen.io/anon/pen/xGaWNr
Code
x = ['2','false','b'];
var run = function (x0,x1,x2) {
document.write (x0+'<br>');
document.write (x1+'<br>');
document.write (x2+'<br>');
}
run(x[0],x[1],x[2]);
Output
2
false
b

Related

JavaScript Closures calculate sum [duplicate]

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
"add" function that works with different combinations of chaining/arguments
(4 answers)
Puzzle: JS Function that returns itself until there are no arguments
(5 answers)
Variadic curried sum function
(19 answers)
Closed 1 year ago.
I just started learning closures in JavaScript and I'm trying to understand a basic problem.
For example, I'm trying to implement the sum method: sum(1)(4)(5)
const sum = (a) => {
return (b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
}
When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?
Thanks
Every time you call your function like:
sum(1)(10)
you are returning the inner function:
(b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
Because type of b === 'number' and you are returning sum(a+b) that calls
again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:
sum(1)(10)()
The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.

Check if value exists in array javascript [duplicate]

This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.

This Javascript if statement won't run when using not operator? [duplicate]

This question already has answers here:
Is there a “not in” operator in JavaScript for checking object properties?
(6 answers)
Closed 5 years ago.
I'm trying to return an object with each letter from a string as a key, and each key's value being the amount of times that letter appears.
The if statement doesn't seem to execute, I think it's a problem with the not operator because I can get it to execute if I remove it and put the letter in the object so that it evaluates to true.
function multipleLetterCount(str){
var countObj = {};
for(var i = 0; i < str.length; i++){
//Why won't this if statement run???
if(!str[i] in countObj){
countObj[str[i]] = 1;
} else {
countObj[str[i]]++;
}
}
return countObj;
}
multipleLetterCount("aaa")
It returns {a: NaN}
You need to wrap your condition with the negation operator (!)
if(!(str[i] in countObj))
Or even better, invert your condition:
if (str[i] in countObj) {
countObj[str[i]]++;
} else {
countObj[str[i]] = 1;
}

common function that accept all argument in javaScript [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 6 years ago.
often time I have this pattern problem in javascript. I have an add function
function add(a, b){
return a + b;
}
then I can do add(1,2) //3
but what if I want to pass in any length of arguments?
I can't do freely add(1,2,3,4). or add(something,something,something). If I want I have to write another add function that accept 4 and 3 arguments.
I know I can use loop them up by loop but how to pass any number of argument to a function in js?
you can use arguments property .
function add(){
var sum=0;
for (var key in arguments)
sum=sum+arguments[key];
return sum;
}
console.log(add(1,2,3,7));
You can loop over arguments and add values
ES6
function add(){
return Array.from(arguments).reduce((p,c)=>p+= !isNaN(c)? +c : 0, 0)
}
console.log(add(1,2,3,4,5))
console.log(add(1,2,3,'a', 7))
ES5
function add(){
return [].slice.call(arguments).reduce(function(p,c){
p+= !isNaN(c)? +c : 0;
return p;
}, 0)
}
console.log(add(1,2,3,4,5))
console.log(add(1,2,3,'a', 7))

How do I use a variable with a boolean value as a condition in an IF statement in JavaScript? [duplicate]

This question already has answers here:
Is `if (condition = value)` the correct syntax for comparison?
(5 answers)
Closed 8 years ago.
How do I use a variable with a boolean value as a condition in an IF statement in JavaScript?
patt1 = new RegExp ("time");
var searchResult = (patt1.test("what time is it" )); // search for the word time in the string
// and return true or false
If (searchResult = true) // what is the right syntax for the condition?
{
document.write("Word is in the statement");
document.write("<br />");
}
Simply use the value directly and Javascript will determine if it's truthy or not.
if (searchResult) {
// It's truthy
...
}
The problem in your original sample is you are using searchResult = true. This is not a simple conditional check but is instead an assignment which results in a value which is then checked as a conditional. It's roughly the equivalent of saying the following
searchResult = true;
if (true) {
...
}
In Javascript the = operator can be used in a number of ways
= this is used for assignment
== this is used for equality checking with coercion
=== this is used for strict equality checking
if (searchResult == true) {
...
}
This is a test.
Short version:
if (searchResult) {
...
}
if (searchResult) is the same as if(searchResult == true)
if (!searchResult) is the same as if(searchResult == false)

Categories

Resources