I want to implement the split method with a function
This is what i am trying to achieve
var string = 'aa,bb,c';
var separator = ',';
var stringList = string.split(separator);
function splitString() {
console.log(stringList);
}
This returns this array
["aa", "bb", "c"]
I am trying to implement the same with a function but it returns an empty array [] and not ["aa", "bb", "c"]
I have created a jsbin for who can help out.
function split(string,separator) {
var cache = [];
var cachInt = 0;
var lastWord = '';
for (var i = 0; i < string.length; i++) {
if(string[i] === separator) {
cachInt++
lastWord = ''
}
else {
lastWord = lastWord + string[i];
cache[cachInt] == lastWord;
}
}
return cache;
}
function splitString() {
console.log(split('string, separator',','));
}
You do this:
Which should be, because you're not comparing, you're assigning:
While we're at it, there is room for improvement. Your version has the line mentioned above. That line gets run every iteration of
i. Thats not really needed, as you only want to perform a save on a split:This has a tiny issue: The last part of string often doesn't have the seperator, it's
a,b,cand nota,b,c,. We can fix that easily with a check after theforto see if you have anything remaining:This has the added feature that it works as a
rtrim()(wether you want that or not is up to you to fix).Also, if you don't need to support older IE versions, then don't use
var, uselet. If you want to know why, this question explains it well.Then, you're using a counter to remember which
cachIntto use. As we now only use it once per "cacheInt", eg once per word, we know that each addition is +1, and only happens once per word. We also don't really care about the index, we just want each word to be added once. So, you can docache[] = lastWord, or use push, which is slightly neater:cache.push(lastWord).By removing the use for this counter, you can also remove the
cachInt++and thelet/var cachIntat the beginning of the function, resulting in smaller code.Result of all of the above:
https://jsbin.com/mejayuv/1/edit?html,js,console,output