Can any one help tell me what's wrong with my Javascript code?
var a = ["zero", "one", "two", "three"];
for (var i in a) {
var sliced = a.slice(i + 1);
console.log(sliced);
}
Can any one help tell me what's wrong with my Javascript code?
var a = ["zero", "one", "two", "three"];
for (var i in a) {
var sliced = a.slice(i + 1);
console.log(sliced);
}
the console log gives: ["one", "two", "three"],[],[],[]
but what I expected is: ["one", "two", "three"],["two", "three"],["three"],[]
So, why my code not work? And how should I code? Thanks a lot.
Share Improve this question edited Jan 24, 2017 at 6:03 Rajesh 25k5 gold badges50 silver badges83 bronze badges asked Jan 24, 2017 at 5:59 LisaLisa 1603 silver badges11 bronze badges 7-
Why do you use
for..in
loop? – guest271314 Commented Jan 24, 2017 at 6:04 -
Tip: log
i + 1
to confirm it’s really1
,2
,3
, etc. – Sebastian Simon Commented Jan 24, 2017 at 6:05 -
2
@Rajesh The iteration variable in
for..in
is always a string. – Sebastian Simon Commented Jan 24, 2017 at 6:07 -
@Rajesh Not sure why OP uses
for..in
, where current element of iterable property is a string, not a number? – guest271314 Commented Jan 24, 2017 at 6:10 - @guest271314 I guess OP is playing with different tools to learn. I have added a caveat in your answer. If not required, please revert the edit – Rajesh Commented Jan 24, 2017 at 6:14
4 Answers
Reset to default 7You need to parse the string to number since for...in
statement fetches object property which would be string
. So in the second iteration, it would try to do a.slice('11')
(string cocatenation '1' + 1
==> '11'
) which returns an empty array.
var a = ["zero", "one", "two", "three"];
for (var i in a) {
var sliced = a.slice(Number(i) + 1);
console.log(sliced);
}
Since it's an array it's better to use a for loop with a counter variable i
which starts from 1
.
var a = ["zero", "one", "two", "three"];
for (var i = 1; i < a.length; i++) {
var sliced = a.slice(i);
console.log(sliced);
}
Use for
loop to iterate arrays
var a = ["zero", "one", "two", "three"];
for (var i = 0; i < a.length; i++) {
var sliced = a.slice(i + 1);
console.log(sliced);
}
This will solve the problem :
why were you trying to do
i+1
?
var a = ["zero", "one", "two", "three"];
for (var i in a) {
var sliced = a.slice(i);
console.log(sliced);
}
var a = ["zero", "one", "two", "three"];
var i = 0;
while (i = a.length) {
console.log(a);
a.shift();
}