can anyone, please, tell me why this code does not work?
var newbie = [];
for ( var c of "greetings"){
var newbie += c;
};
I am trying to put characters of "greetings" to an array newbie.
can anyone, please, tell me why this code does not work?
var newbie = [];
for ( var c of "greetings"){
var newbie += c;
};
I am trying to put characters of "greetings" to an array newbie.
Your code does not work because you need to use push()
for adding an element to the last index of the array.
var newbie = [];
for ( var c of "greetings"){
newbie.push(c);
};
console.log(newbie);
Alternatively, you can use split()
as a short hand to get that same output:
var text = 'greetings';
var res = text.split('');
console.log(res);
You can't use +=
to add elements to array. You need to use Array.prototype.push
Note: Don't use var
or let
to declare arrays and objects. Use const
.
Reason: We usually don't reassign the arrays and objects using =
operator. We generally modify them. So to prevent them from reassigning use const
. In a special case when you know that you need to change object's value using =
then you may use let
const newbie = [];
for (let c of "greetings"){
newbie.push(c);
};
console.log(newbie)
You can also use split()
to convert string into array.
let str = "greetings";
const newbie = str.split('');
console.log(newbie)
In the loop avoid this statement var newbie += c;
and use newbie.push(c)
.
Reason : A var
newbie has already been created as a global variable , you need not create it again in the loop. Use the existing newbie array