This question already has answers here:
JavaScript Function Context Incorrect
(3 answers)
Closed 7 years ago.
I have a variable a that can be either an object or an array of objects. I have an array array.
I want to append a to array, so I thought of using either Array.prototype.push.call or Array.prototype.push.apply with a ternary operator as follows:
var a = "hello"; // or var a = ["hello", "world"];
var array = [];
var append = ($.isArray(a)) ? Array.prototype.push.apply : Array.prototype.push.call;
append(array, a); // Uncaught TypeError: undefined is not a function
($ being jQuery)
I'm new to JavaScript and I guess there is a good reason why this doesn't work but I couldn't find it. Can't apply or call be assigned to a variable? (They are not real functions?) Or is something missing on the call to append()?
Note: I know I could do this with if/else but I'd rather like to understand why I can't assign these methods to a variable and call it.
Minor additional question: I want to do this because I get a from a JSON API and if I understand correctly, JSON can't contain arrays of one single object. Although I feel that what I'm trying to do must be very common, I also couldn't find how other developers deal with this. Is there a better way than testing whether a is an array or not and use apply() or not accordingly?
This happens because call and apply are instance methods. They are critical to the context object this.
Eventually you should execute append.call(Array.prototype.push, array, a) because call or apply need function push to be passed as this
You don't need any if, just use concat
var array = [];
var a = "hello"; // or var a = ["hello", "world"]
array = array.concat(a);
Related
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 months ago.
There is a way to pass a string in a function to other function and this string is a reference to an object in this other function?
function fun1 (structure){
obj = [{"header":{"orderNumber": a, "item": 1}}, {"header":{"orderNumber": b, "item": 1}}]
newObj = obj[0].structure
console.log(newObj)
//first call a
//second call 1
}
//first call
function fun2(){
structure = 'header.orderNumber'
fun1(structure)
}
//second call
fun2(){
structure = 'header.item'
fun1(structure)
}
What I want is a dynamic way to access an object by creating a string.
For example in the block of code obj.header.item.description and this is valid. I would like to pass a string in this string somehow make a reference to the object so I can get the value.
One way you could accomplish this would be by storing all of the object references in a Map (MDN) structure where the key is a string and the value is the object reference in question.
I should say that even though I don't know your exact use case, this is what you would call a "stringly typed" solution which is generally not the best idea.
This question already has answers here:
Is it possible to send a variable number of arguments to a JavaScript function?
(12 answers)
Closed 3 years ago.
I'm new to programming and for the moment I'm learning JavaScript using a combination of online courses. One challenge I'm working on is to use a function to return a random string from an array. That part itself was easy, but it seems like I need to be able to create the array from the input I give when I call the function. As an example, if I were to create a function like this:
function namePicker(names);
And I then called the function and gave it this input:
namePicker("Billy","Timmy","Johnny");
then I should be able to use the input to create an array of these names. However, when I tried to work this into the code for the random name picker, only the first name I gave would return to me.
What am I doing wrong here? Here's the full code I've been working on:
function lunchClubLottery(names) {
var lunchClub = [names];
var randomNumber=Math.floor(Math.random()*lunchClub.length);
return lunchClub[randomNumber];
}
The rest parameter syntax (...) can be used to create an array of all (or some of) the arguments supplied to a function.
function lunchClubLottery(...names) {
var i = Math.floor(Math.random()*names.length)
return names[i]
}
const name = lunchClubLottery("Billy","Timmy","Johnny")
console.log(name)
Or if you want to go old-school, you can use the arguments object (if you are not using a fat arrow function).
Here I convert the array-like arguments object to an Array using slice and call.
function lunchClubLottery() {
const names = Array.prototype.slice.call(arguments)
var i = Math.floor(Math.random()*names.length)
return names[i]
}
const name = lunchClubLottery("Billy","Timmy","Johnny")
console.log(name)
This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 5 years ago.
I would like to call a function, lets say test_func that accepts variable number of arguments. (like this function http://locutus.io/php/array/array_intersect_assoc/)
Please note I would like to avoid modifying the receiver function! All the answers so far require modifying the receiver function, just as the linked "possible dupes". I would like to programmatically generate the argument list itself. (eg pass variable number of objects)
I do not know in advance how many arguments I will have. How can I generate a variable length argument with objects?
var v1 = {test:1};
var v2 = {test2:2};
var obj_arr = [v1,v2];
console.log(test_func (obj_arr.join(",")));
//in my case this should be the equivalent of test_func (v1,v2);
function test_func (object_arg) {
return(arguments.length);
}
//should return 2!
If you're in an ES5 environment you can use arguments:
function test() {
var param1 = arguments[0];
var param2 = arguments[1];
// arguments is array like, you can iterate over it with a loop
}
If you are in an ES6 environment you can either use the rest operator as suggested by Suren or also use the arguments variant as above - depending on the convention of you're team.
This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();
This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 10 years ago.
I have a javascript issue.
If I have an object array objAr, the object consists of id,name.
If I was to access objAr[0].id it returns the id value of the first object. What would happen if the object is dynamic and therefore I do not know what it consists of, is there a way to dynamically call the Object attribute?
Currently I am creating another array
var theArr = new Array("id", "name");
and call:
objAr[0].theArr[0] instead of objAr[0].id.
Is there a way to do this better using Javascript?
With Javascript you can call all of the attributes in an object without knowing the keys.
See below:
for(key in objAr[0]) {
console.log(objAr[0][key]);
}
If you just wanted the first attribute you could run:
for(key in objAr[0]) {
var attFirst = objAr[0][key];
break;
}
Additionally for the JS array you could have used square brackets.
var theArr = ["id", "name"];
hope that helps
In javascript you can always use the "array notation" in place of the "dot notation"
So these 2 lines are the same
objAr[0].id
objAr[0]["id"]