1

I keep getting an error in the console that .split is not a function. Here is my code:

function addEnds(list) {

        var array = new Array();
        array = list.split(',');

        console.log(array);
    }

Basically, I want the list to equal a series of number separated by a comma, example: 1,2,3,4,5, and am trying to put those into an array. I've researched about using .split but for some reason, I'm just not getting it.

6
  • can you show how you are calling your function. split is a string method, are you calling your function like addEnds("1,2,3,4,5") ? Commented Mar 30, 2018 at 2:30
  • It’s a problem with what you’re passing as list, but you haven’t shown that. Also, you don’t need to initialize the array like that. split() will make a new array. Commented Mar 30, 2018 at 2:31
  • for now just in the console i'm typing addEnds(2,3,5,8,0); or any other random series of numbers. Commented Mar 30, 2018 at 2:32
  • 2
    well, that's not a string ... you could try function addEnds(...list) { return list; } - or function addEnds() { return Array.from(arguments)); or even function addEnds() { return Array.prototype.slice.call(arguments);} ... those three all do the same thing on older and older browsers Commented Mar 30, 2018 at 2:32
  • 1
    It looks like the result is already split if you can call it that way. Try addEnds(‘2,3,5,8,0’) Commented Mar 30, 2018 at 2:34

2 Answers 2

1

The function shared is working absolutely fine. Just ensure that the argument that you are passing is a string.

Please follow the below fiddle:

https://jsfiddle.net/6pennzrb/

function addEnds(list) {
    var array = new Array();
    array = list.split(',');
    console.log(array);
}
addEnds("1,2,3,4,5")

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

const stringToArray = ([...list], delimeter = ',') => list.filter(el => el != delimeter)
const result = stringToArray('1,2,3,4,5')
console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.