简体   繁体   English

javascript上数组切片方法的奇怪行为

[英]weird behavior of array slice method on javascript

I found a very weird behavior of array when it's used within a class... I've been trying to figure out what's going on, but I couldn't wrap my head around.在类中使用数组时,我发现它的一个非常奇怪的行为......我一直试图弄清楚发生了什么,但我无法理解。 So this is what happened.所以这就是发生的事情。

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

It works totally fine when I try to get the entire array using this.array.slice(0,this.length) .当我尝试使用this.array.slice(0,this.length)获取整个数组时,它完全正常。 It will give me the full array.它会给我完整的数组。 But then when I try to use this.array.slice(0,this.length-1) to get an array not including the last element, it will give me an empty array instead of what I wanted.但是当我尝试使用this.array.slice(0,this.length-1)来获取一个不包括最后一个元素的数组时,它会给我一个空数组而不是我想要的。 It seems it only happens when it's written within an object method.似乎只有在对象方法中编写它时才会发生。 Because it works fine normally.因为它正常工作。

const array=[0,2,3];
console.log(array.slice(0,this.length-1)); // will print [0,2]

I tried to delete bind method to see if this is affecting the behavior, but it still gives me the same result...我试图删除bind方法以查看这是否会影响行为,但它仍然给我相同的结果......

Can someone explain why this is happening?有人可以解释为什么会这样吗?

you code is wrong, put this.array.length -1你代码错了,把this.array.length -1

this.length is undefined this.length undefined

From your conversation I found, you are trying to inherit DOM Array从你的谈话中我发现,你正在尝试继承 DOM Array

Try to inherit Array like this尝试像这样继承 Array

class MyArray extends Array {
   constructor(props){
    super();
    for(var i=0;i<arguments.length;i++) this.push(arguments[i]);
   }
}

const k=new MyArray(5,6,7,8);
console.log(k.length);

the issue is with 'this' keyword inside the slice method.问题在于切片方法中的“this”关键字。 It is trying to find the length property on the object which is 'undefined'.它试图在“未定义”的对象上找到长度属性。 Also undefined - 1 results in NaN同样未定义 - 1 结果为 NaN

your code is the same as following code:您的代码与以下代码相同:

class wtf{
  constructor(){
    this.array=[0,2,3];
  }
  fn(){
   let length = this.array.length
    console.log(this.array.slice(0,undefined));// undefined because length is not defined on the object
    console.log(this.array.slice(0,NaN));// NaN because undefined-1 is NaN
  }
}
const k=new wtf();
k.fn();

Instead, Try this:相反,试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM