简体   繁体   中英

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) . 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. 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...

Can someone explain why this is happening?

you code is wrong, put this.array.length -1

this.length is undefined

From your conversation I found, you are trying to inherit DOM Array

Try to inherit Array like this

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. It is trying to find the length property on the object which is 'undefined'. Also undefined - 1 results in 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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