简体   繁体   中英

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM