2

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.

7
  • Why do you use for..in loop? Commented Jan 24, 2017 at 6:04
  • Tip: log i + 1 to confirm it’s really 1, 2, 3, etc. Commented Jan 24, 2017 at 6:05
  • 2
    @Rajesh The iteration variable in for..in is always a string. 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? 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 Commented Jan 24, 2017 at 6:14

4 Answers 4

7

You 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);
}

Sign up to request clarification or add additional context in comments.

1 Comment

@Lisa : glad to help you
1

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);
}

Comments

0

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);
}

1 Comment

Please refer question for desired output and you will see the purpose of i+1
0

var a = ["zero", "one", "two", "three"];
var i = 0;
while (i = a.length) {
   console.log(a);
   a.shift();
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.