【问题标题】:weird behavior of array slice method on javascriptjavascript上数组切片方法的奇怪行为
【发布时间】:2020-04-02 02:47:17
【问题描述】:

当在类中使用数组时,我发现了一个非常奇怪的行为......我一直试图弄清楚发生了什么,但我无法理解。所以这就是发生的事情。

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]

我尝试删除 bind 方法以查看这是否会影响行为,但它仍然给我相同的结果...

有人可以解释为什么会这样吗?

【问题讨论】:

    标签: javascript arrays oop methods slice


    【解决方案1】:

    你的代码错了,输入this.array.length -1

    this.length 为undefined

    从您的对话中我发现,您正在尝试继承 DOM Array

    尝试像这样继承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);
    

    【讨论】:

    • 是的,我知道第二个参数不是长度,但是我们仍然可以使用数组的长度来找到数组的最后一个索引+1 ...
    • 不,如果你通过 1, 3 --- 1 将被假定为索引,3 将被假定为位置,我在答案中引用了示例
    • 我的问题不是关于索引...我知道你在说什么。但我的索引是正确的。 array.slice(0,this.length) 给我完整的数组,因为 slice 方法不包含第二个参数,并且 array.slice(0,this.length-1) 给我没有最后一个元素的数组,因为它不包括最后一个索引上的项目。但我的问题是,当它在对象方法中使用时,它不能正常工作。
    • 知道了,我现在给出答案:)
    • 感谢您的回答,它有效!但现在我还有一个问题.. ` const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(0, this.length-2)); ` this 打印 ['ant', 'bison', 'camel'],那么“this”指向的是什么?...“this”不是指向调用该方法的数组吗?当我在对象中使用它时,为什么“this”指向我创建的对象?
    【解决方案2】:

    问题在于 slice 方法中的 'this' 关键字。它试图在“未定义”的对象上找到长度属性。同样未定义 - 1 结果为 NaN

    您的代码与以下代码相同:

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

    相反,试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多