+ 4
JS: Not sure what to title this, but it i think the description will make sense...
So I got an array: var carId = [12, 27, 44, 31] and then I got a string: var str = "Test_x_done", How can I make an ARRAY with the carId, and str.. so that I get a new variable like this? var myArray = ["Text_12_done", "Test_27_done"...] ? This is the code I started, but then I got stuck: https://code.sololearn.com/WqCwJBd1Ub5V/#js
12 ответов
+ 1
Arvind Singh Rawat Sure, there are other ways to do... but OP needs to have a good understanding of basics (array, string...) before learning more advanced features (and why not using regular expression for the 1st argument of replace() method ;P) and to understand why its code doesn't work ^^
+ 1
You logic is good, you're juste misusing the carId array inside your loop:
str += "Test_"+carId[cI]+"_done" + "<br>";
(without the bracketed indice notation you access the whole array, not the "cI"th element ^^)
Anyway, output to console doesn't requires (and doesn't support html tags, but you could use "\n" new line char -- except in website code playground :( sadly)
+ 1
visph using that method, try console.log(str[0]).
that returns: “T” for some reason.
but it should return
“Test_12_done”.
+ 1
More Generic Solution
Could use replace() method of string to replace the _x_ value with the desired number, but make sure replace() method replaces all the occurrences of the desired string.
const myArr = []
for ( let id in carId)
{
arr.push(str.replace('_x_',`_${carId[id]}_`));
}
console.log(myArr);
0
strings acts like array: each char can be accessed with its index...
console.log(str[0]) output 'T', because it's the letter at index 0.
console.log(str) output 'Test_12_done', because you give the full string as argument.
I'd said you misuse the cardId array, but not seen (or did you edit your code since?) that you misuse string also ^^
0
visph I edited the code.
0
:D
Right, you take it now? you must use str, not str[0] ;)
0
visph str is supposed to be an array. Or maybe i need to create a new array variable.
But why i did str[0], was to see if it was working, to see id it was an array.
if I did str[0], and it returned “Test_12_done”, then I know that it’s an array and that I can acces its ... umm.. yeah.
0
El Cha I’m not sure.
Start a new discussion so everyone can see it.
0
Ok thanks
0
Thanks for z help everyone.
I was just watching a video about for() loops and it flipped a switch for me.
Finally figred it out.
Of course, I’ve figred it out a while ago when you guys answered, but i wanted to understand the codes, some of them i wasn’t understanding (but still worked and served the purpose), but this time I figured out in a way I could understand...
https://code.sololearn.com/WqCwJBd1Ub5V/?ref=app
Thx!