user3211495
user3211495

Reputation: 11

How to reference an array method within a function in Javascript

var myList = ["Hello There World", "meatball", "cookie monster"];

var BreakUpFirst = function (myList) {
document.write(myList[0].split(" "));
};

Hello I am new to JavaScript so please bear with me. Not sure what I am doing wrong here.

I am trying to break the first string in the myList array into its own array with 3 values. The split method works fine for me outside of the function, but I can't get it to work inside. I want to create BreakUpFirst as a new array and keep myList or any other array I pass through it as is.

Upvotes: 1

Views: 365

Answers (1)

citizenslave
citizenslave

Reputation: 1418

You're actually doing a couple of different things here. If you just want to assign the value of myList[0].split(" ") to var BreakUpFirst, then the solution suggested by @thefourtheye is ideal. Just assign the value directly:

var BreakUpFirst = myList[0].split(" ");

If you're trying to use a function that will always break up a string stored at the first element of an array and output it to the screen, then you need to make sure you pass in the array as a parameter. If you define your function:

 var BreakUpFirst = function(myList) {
     return myList[0].split(" ");
 }

 var myList = ["Hello There World", "meatball", "cookie monster"];

You need to make sure you invoke the function and pass in the parameter:

 var brokenString = BreakUpFirst(myList);
 alert(brokenString);

You will get an alert box with the brokenString array, "Hello","There","World"

Upvotes: 1

Related Questions