Iterating through a string or an array in js. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Iterating through a string or an array in js.

How to use a for loop for iterating through an array or a string in js.

24th Dec 2019, 3:47 AM
Yash
Yash - avatar
9 ответов
+ 1
The way I do it is by splitting the string and then use for each. Example: let myStr = "ABCD".split(''); Object.values(myStr).forEach((v)=>{ console.log(v); });
24th Dec 2019, 4:18 AM
SoundInfinity
SoundInfinity - avatar
+ 1
SoundInfinity can't we use for loop like we do in python
24th Dec 2019, 5:36 AM
Yash
Yash - avatar
+ 1
Yash yes you can use for loops to iterate through strings and array, just like in python. How have you tried iterating ? Post your attempt here.
24th Dec 2019, 5:53 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
Aymane Boukrouh well I am just a beginner in js, and I know for loop syntax that they teach in sl only. So in other words I am clueless about the syntax used for iterating through arrays etc Can u help please
24th Dec 2019, 1:42 PM
Yash
Yash - avatar
0
Yash I did it on my own, so I am really not sure, if it also could be done just like in Python. Also, my previous code wasn't 100% correct, but I fixed it.
24th Dec 2019, 5:42 AM
SoundInfinity
SoundInfinity - avatar
0
Yash can you show me your attempt first ? I just want to see how you tried it, so I can tell you where your mistake is.
24th Dec 2019, 1:47 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
0
Yash read this, it contains different ways to iterate throught an array (including almost-python syntax for the first one, which is what I was talking about): https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript&ved=2ahUKEwiPqMCjt87mAhWCBWMBHYJLCa4QFjAAegQIBxAB&usg=AOvVaw0jjh5QNKHY-VWoU6If9-c8 And by the way, even if you are a beginner, it does not mean you can't use search engines. The link I shared was the first result I got after searching on google writing exactly what you asked, so please try to search next time, especially for simple things like these. Thanks for understanding!
24th Dec 2019, 1:56 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
0
Can't you just use for of? const str = 'Yea!' for (let item of str) { document.write(item + ' | ') }
25th Dec 2019, 5:02 PM
Йордан Петров
Йордан Петров - avatar