here is my javascript code:
var my_array = new Array();
my_array[0] = "a";
my_array[0] = "b";
my_array[0] = "c";
print_array(my_array);
function print_array(arr)
{
alert(arr);
}
But it doesn't work, because I can't pass the array to the function. So, how can I pass an entire array to javascript function?
EDIT:
Nevermind. I found the solution.
Hidden cause this is bad practice and passes the array as a string:
If someone will need to pass an array to the function, first use this: JSON.stringify() and javascript will be able to parse an array.
8 Answers 8
The problem is you are assigning each element to index 0, so they are overwriting each other.
// should be
my_array[0] = "a";
my_array[1] = "b";
my_array[2] = "c";
// alternatively, if you don't want to track the index
my_array.push("a");
my_array.push("b");
my_array.push("c");
The rest of the code looks fine. You can pass whole arrays, or any object for that matter to a function in exactly the manner you have shown in your code.
When you alert it, javascript will concatenate the array into a comma separated string for easy viewing.
6 Comments
my_array.push("a", "b", "c")Try this code instead:
function print_array(arr)
{
alert(arr);
}
var my_array = new Array();
my_array[0] = "a";
my_array[1] = "b";
my_array[2] = "c";
print_array(my_array);
You should define a function before you can call it as a good programming practice.
Also note the order of your elements that are being assigned, you're putting everything on 0, and they should be on 1, 2 etc.
3 Comments
var myFunc = function(){ alert(123) }To extend Billy Moon's answer
You can define your array like this:
my_array = ["a", "b", "c"];
And like this:
my_array = [];
my_array[0] = "a";
// ...
Comments
var my_array = ["a", "b", "c"];
// or a popular way to define (mainly string) arrays:
var my_array = "abc".split("");
print_array(my_array);
function print_array(arr) {
alert(arr);
}
2 Comments
a = "123".split("");console.log(a[0]+a[2]) gives 13?var my_array = ["a","b","c"];
function print_array(arr)
{
alert(arr);
}
print_array(my_array);
1 Comment
Note this
function FollowMouse()
{
var len = arguments.length;
if(len == 0) return;
//
for(var i=0; i< len; i++)
{
arguments[i].style.top = event.clientY+"px";
arguments[i].style.left = event.clientX+"px";
}
};
//---------------------------
html page
<body onmousemove="FollowMouse(d1,d2,d3)">
<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>
</body>
can call function with any Args
<body onmousemove="FollowMouse(d1,d2)">
or
<body onmousemove="FollowMouse(d1)">
Comments
var f=d=>
d.forEach(k=>
alert(k)
);
let a=[1,2];
f(a);