Javascript:在循环中使用array.slice()并且无法按预期工作

Lis*_*isa 2 javascript

任何人都可以帮我告诉我我的Javascript代码有什么问题吗?

var a = ["zero", "one", "two", "three"];
for (var i in a) {
  var sliced = a.slice(i + 1);
  console.log(sliced);
}
Run Code Online (Sandbox Code Playgroud)

控制台日志给出: ["one", "two", "three"],[],[],[]

但我的期望是: ["one", "two", "three"],["two", "three"],["three"],[]

那么,为什么我的代码不起作用?我该怎么编码?非常感谢.

Pra*_*lan 6

您需要将字符串解析为数字,因为for...in语句将获取对象属性string.所以在第二次迭代中,它会尝试a.slice('11')(string cocatenation '1' + 1==> '11')返回一个空数组.

var a = ["zero", "one", "two", "three"];
for (var i in a) {
  var sliced = a.slice(Number(i) + 1);
  console.log(sliced);
}
Run Code Online (Sandbox Code Playgroud)

因为它是一个数组,最好使用一个for循环使用计数器变量i,从开始1.

var a = ["zero", "one", "two", "three"];
for (var i = 1; i < a.length; i++) {
  var sliced = a.slice(i);
  console.log(sliced);
}
Run Code Online (Sandbox Code Playgroud)