I have a JS object with a variable number of parameters. Is there a way to see what parameters have been passed this particular time?
The example:
function getElement() {
var scope = document;
this.by = function(data){
if (data.id) scope = scope.getElementById(data.id);
if (data.tag) scope = scope.getElementsByTagName(data.tag);
return scope;
}
}
And I run it like so
var x = new getElement();
vad div = x.by({id : "chosenID"});
gets the div with the id chosenID
or
var x = new getElement();
vad inputs = x.by({id : "chosenID", tag : "input"});
gets all the inputs
in the div with the id chosenID
;
I want to know if I passed one or two parameters, and which ones.
Thanks!
ps: I appreciate your time in helping me out, but please do not sugget jQuery or other JS framework as this is for learning purposes only. Much obliged, Sorin.
values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.
getOwnPropertyNames() The Object. getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
Use a for … in
loop to iterate over the passed object's parameters, like:
var prop;
for (prop in data) {
if (data.hasOwnProperty(prop)) {
// do something with data[prop]
}
}
Don't forget to check the property with hasOwnProperty
.
Using object iteration (key in data
) and array-combining... you can return a number of elements... although the object iteration is rendered pretty useless by by the switch statement.
function getElement() {
var scope = document;
this.by = function(data){
var key;
var ret=[];
for (key in data) {
if(data.hasOwnProperty(key)) {
switch(key) {
case "id":
ret=ret.concat(scope.getElementById(data[key]));
break;
case "tag":
ret=ret.concat(scope.getElementsByTagName(data[key]));
break;
default:
throw new Error("Unknown property "+key);
}
}
}
return ret;
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With