JavaScript上的数组切片方法的怪异行为

问题描述 投票:0回答:1

当在类中使用数组时,我发现数组的行为很奇怪。我一直在试图弄清楚正在发生什么,但是我无法解决问题。这就是发生的事情。

class wtf{
  constructor(){
    this.array=[0,2,3];
    this.fn=this.fn.bind(this);
  }
  fn(){
    console.log(this.array.slice(0,this.length));// will print [0,2,3]
    console.log(this.array.slice(0,this.length-1));// will print an empty array
  }
}
const k=new wtf();
k.fn();

当我尝试使用this.array.slice(0,this.length)来获取整个数组时,它的工作效果很好。它会给我完整的阵列。但是,当我尝试使用this.array.slice(0,this.length-1)获取不包括最后一个元素的数组时,它将给我一个空数组,而不是我想要的。看来只有在对象方法中编写它时才会发生。因为它可以正常工作。

const array=[0,2,3];
console.log(array.slice(0,this.length-1)); // will print [0,2]
javascript arrays oop methods slice
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.