using .slice method on an array

有些话、适合烂在心里 提交于 2019-12-01 13:26:06

问题


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:


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.



来源:https://stackoverflow.com/questions/23259310/using-slice-method-on-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!