Lisa
Lisa

Reputation: 160

Javascript: use array.slice() in a loop and not work as expected

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.

Upvotes: 2

Views: 2507

Answers (4)

Kathir07
Kathir07

Reputation: 231

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

Upvotes: 0

guest271314
guest271314

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

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

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

Upvotes: 7

Ashish Kumar
Ashish Kumar

Reputation: 136

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

Upvotes: 0

Related Questions