+ 5
Please help me with JavaScript .split() and .forEach()
. array = string.split().forEach() doesn't work, but array = string.split() array.forEach() works correctly. Can someone please help me understand why? I looked it up on Google but I couldn't find an answer. Example code: https://code.sololearn.com/W0aG20hKeZ4y/?ref=app
5 Answers
+ 5
arr = 'abc'.split('')
an array ['a','b','c'] is returned as result of split on string 'abc'
arr now equals to ['a','b','c']
arr.forEach(function(){})
you iterate on each element from the array but don't do anything inside the function so nothing happens
alert(arr)
this outputs a,b,c because the array still hasn't changed and still equals ['a','b','c']
arr = 'abc'.split('').forEach(function(){})
here you split the string and pass the array ['a','b','c'] to for each iterator
after split, this is basically what it is:
['a','b','c'].forEach(......)
BUT you also assign the return value to arr....
forEach does not return any value, therefore, as a result of assigning arr to something that does not have return value, arr is assigned undefined value
alert(arr)
undefined is outputted
to sum it up
your first arr.forEach(.....) doesn't do anything
your second arr.forEach(....) also doesn't do anything, bus as a result of assigning it to arr, it is being overwritten with undefined value
+ 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
forEach always returns undefined, it's an operation method using the array elements , since ur not doing anything it returns undefined due to overwriting of ur [a, b,c ] array to undefined
+ 3
var arr = 'abc'.split('')
arr.forEach(function(){})
alert(arr)
var arr1 = []; 'abc'.split('').forEach(function(item){
arr1.push(item);
});
alert(arr1);
don't know ur use case but since ur expecting something similar , hence proceed like above
+ 2
forEach() is really a tough one to tame for beginners, I learned of its powers and weaknesses when I was trying to break from the loop in between of array , and scratched my head for hours , didn't realize then it's not like ur everyday for loop.
read MDN docs carefully and get to know the popular iteration functions like forEach, map, reduce and write more test codes only then u ll get clarity
0
What is the output of this code?
var arr = new Array("a", "b", "c");
alert(arr[1]);