[英]Why am I getting an error when using split function of javascript?
I'm trying to split my string but not get proper output as per my expected.我正在尝试拆分我的字符串,但没有按照我的预期获得正确的 output。
Input输入
let name = "helloguys";
Output Output
h
he
hel
hell
hello
hellog
hellogu
helloguy
helloguys
let name = "mynameisprogrammer";
for (let index = 1; index <= name.length; index++) {
let finalData = name.split(name[index]);
console.log(finalData[0]);
}
You could use Array.map()
along with String.slice()
to split the string into the required values:您可以使用
Array.map()
和String.slice()
将字符串拆分为所需的值:
let name = "mynameisprogrammer"; let result = [...name].map((chr, idx) => name.slice(0, idx + 1)); console.log('Result:', result)
.as-console-wrapper { max-height: 100%;important; }
If you need this to be unicode aware, you might want to avoid using string substring / slice etc.如果你需要它是 unicode 感知的,你可能想避免使用字符串 substring / slice 等。
Instead convert to array, and split there.而是转换为数组,然后在那里拆分。
eg..例如..
let name = "mynameisprogrammer"; const nameA = [...name]; for (let ix = 1; ix <= nameA.length; ix += 1) console.log(nameA.slice(0, ix).join(''));
.as-console-wrapper { max-height: 100%;important; }
ps.附言。 To see what I mean by unicode aware, try using the name from the code above into some of the other answers.
要了解我所说的 unicode aware 是什么意思,请尝试将上面代码中的名称用于其他一些答案。
You can simply use a variable and keeping add value of current index and keep printing on each iteration, you don't need split here您可以简单地使用一个变量并保持当前索引的附加值并在每次迭代中保持打印,您不需要在此处拆分
let name = "helloguys"; function printName(name) { let temp = '' for (let index = 0; index < name.length; index++) { temp += name[index] console.log(temp); } } printName(name)
This is how you could do it.这就是你可以做到的。 I'm not sure if you wanted them to be object otherwise you could use
string.substring
我不确定你是否希望它们是 object 否则你可以使用
string.substring
let name = "mynameisprogrammer"; for (let index = 0; index < name.length; index++) { let finalData = name.split(""); console.log(finalData.slice(0,index+1).join("")); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.