+ 5
Why output 3?
//Challenge from Mar Sab: var a = "donald".split("d"); console.log(a.length); https://code.sololearn.com/WoGrt3LR18wS/?ref=app
4 Respuestas
+ 4
The split() string method creates an array of length N+1 with N being the number of occurrences in the calling string of the delimiter passed to split() .
"d" occurs twice in "donald", hence the resulting array will have a length of (2)+1 = 3
and a return value of ["", "onal", ""], an array of 3 elements.
First element is everything before the 1st "d". Second element is everything between 1st and 2nd "d". Third element is every after 2nd "d".
Try experimenting with other strings to understand better how .split() works:
var a = "quackdonaldquack".split("d");
console.log(a);.
// ["quack", "onal", "quack"]
+ 2
var a = "donald".split("d");
console.log(a.length);
a stores this:
[
"",
"onal",
""
]
which has the length 3.
split makes a list every time the string you give it appears the list extends by 1.
+ 2
a.split("d") = ["", "onal", ""]
+ 1
Poskolky razdelitel "d" stoit v nachale i v konche, tam obrazovivaetsya pystaya stroka!
["", "onal", ""]