I am trying to pass an array as an argument in a function
See the --> fiddle <--
From what I've tested it seems the function is reading the argument as a string rather than an array. How do I pass the array as an argument in the function?
HTML
<button id='arr1'>Click for Array 1</button>
<button id='arr2'>Click for Array 2</button><br/><br/>
<div id='mainstuff'>
<p>When you click button, text should be added</p>
</div>
jQuery
$(document).ready(function() {
var arr1 = ["one", "two", "three"];
var arr2 = ["eleven", "twelve", "thirteen", "fourteen"];
$('button').click(function() {
var myval = $(this).attr('id');
showstuff(myval);
});
function showstuff(myval) {
var x = "<p>The new text is " + myval[2] + "</p>";
$('#mainstuff').append(x);
}
});
EDIT: Fiddle has been updated to fix syntax errors.
-
You're passing a string, not an array. Can you clarify your question?Frédéric Hamidi– Frédéric Hamidi2013年06月10日 22:03:00 +00:00Commented Jun 10, 2013 at 22:03
-
I just noticed. I will update soon. ThanksSanya– Sanya2013年06月10日 22:05:04 +00:00Commented Jun 10, 2013 at 22:05
3 Answers 3
You shouldn't do this. Don't try to call variables dynamically, i.e. without knowing their names. You can do it at a push in some circumstances, but it's a bad idea.
The best solution here is to use an object and square bracket notation to get a value from the object dynamically:
var values = {
arr1: ["one", "two", "three"],
arr2: ["eleven", "twelve", "thirteen", "fourteen"]
}
$('button').click(function() {
var myval = this.id;
showstuff(values[myval]);
});
NB that I have changed $(this).attr('id') to this.id for much increased performance.
3 Comments
values object. Javascript objects and object access is generally fairly intuitive...You cannot pass in string values to be converted to objects directly. Instead store your arrays as a key-value pairs and then try to access them.
$(document).ready(function () {
var arrays = {
arr1 : ["one", "two", "three"],
arr2 : ["eleven", "twelve", "thirteen", "fourteen"]
};
$('button').click(function () {
var myval = $(this).attr('id');
showstuff(myval);
});
function showstuff(myval) {
var x = "<p>The new text is " + arrays[myVal][2] + "</p>;
$('#mainstuff').append(x);
}
});
2 Comments
arrays[myVal][2] with arrays[myVal][0][key] or arrays[myVal][1][key]You would have to store your array variables in a common object (or the window scope, which is bad practice) that you can retrieve later:
var commonObject = new Object();
commonObject.arr1 = ["one", "two", "three"];
commonObject.arr2 = ["eleven", "twelve", "thirteen", "fourteen"];
Then to retrieve that variable by string name:
var myval = $(this).attr('id');
showstuff(commonObject[myval]);
1 Comment
new Object() instead of the empty object literal {} nowadays, unless you have to support ancient, obscure browsers.