For little snippets like that you can just post them here in backticks / code fences (link), like this:
function convertStringToArray(string) {
var stringToProcess = "1,2,3,4,5";
return array;
}
A couple of things to be aware of…
The convertStringToArray function accepts an argument called string. So you might run it like this: convertStringToArray('1 2 3 4 5')
and want it to return [1,2,3,4,5]
.
That means you don’t need to set another variable inside the function called stringToProcess. Instead, what you need to do is take the variable string
that is passed in as the argument and do something to it so it becomes the array you want.
In the little snippet I wrote, I mentioned array
as a thing to be returned, but I never actually set that variable anywhere. So you can either set the array variable to something based on whatever you do to the string variable, or you can skip the array variable all together and just return the method that manipulates the string. (That’s a little wordy - sorry if it’s not clear).
Now, what you do to the string is the key to this task. In javascript, different data types have different methods which can be called on them. Essentially these are mini-functions built in to the data type. For example, arrays have a method called .reverse()
, which means if I do this [1,2,3,4,5].reverse()
it returns [5,4,3,2,1]
.
You want a string method that will handle your '1 2 3 4 5'
string.
You can find string methods here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
If MDN is a little too hard to handle (it’s not for the faint-hearted!), you can see a more beginner friendly version of these docs here: http://www.w3schools.com/js/js_string_methods.asp