最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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 really 1, 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
 |  Show 2 more ments

4 Answers 4

Reset to default 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);
}

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

发布评论

评论列表(0)

  1. 暂无评论