using .slice method on an array

2019-02-20 23:16发布

I'm practicing the array section of JavaScript Koan and I'm not fully understanding why these answers are correct. I added my assumptions below if someone could please clarify/let me know if I'm wrong :

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(3, 0)).toEqual([]);       

Why wouldn't it at least slice "jelly" since the slice begins with 3? How does the cut off of 0 make it empty instead?

    expect(array.slice(3, 100)).toEqual(["jelly"]);  

If the cut off index goes beyond what currently exists in the array, does this mean that a new array created from slice would contain all indexes starting at 3 until the end of the array?

    expect(array.slice(5, 1)).toEqual([undefined];  

Will it always be undefined if the starting index doesn't exist in the array?

  });

1条回答
贼婆χ
2楼-- · 2019-02-20 23:47

The second argument to Array.slice() is the upper bound of the slice.

Think of it as array.slice(lowestIndex, highestIndex).

When you slice from index 3 to index 100, there is one item (in your case) that has index >= 3 and < 100, so you get an array with that one item. When you try to take a slice from index 3 to index 0, there can't be any items that meet the conditions index >= 3 and < 0, so you get an empty array.

--EDIT--

Also, array.slice() should never return undefined. That's one of the advantages of using it. If there are no matching values in the array, you just get back an empty array. Even if you say var a = new Array() and don't add any values to it, calling a.slice(0,1) will just give you an empty array back. Slicing from outside of the array bounds will just return an empty array also. a.slice(250) will return [] whereas a[250] will be undefined.

查看更多
登录 后发表回答