本文介绍了在数组上使用.slice方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习JavaScript Koan的数组部分,我不完全理解为什么这些答案是正确的。我在下面添加了我的假设,如果有人可以澄清/让我知道我是不是错了:

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





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





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





  });


推荐答案

是切片的上限。

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

将其视为 array.slice(lowestIndex,highestIndex)

当您从索引3切换到索引100时,有一个项目(在您的情况下)具有索引> = 3且< 100,所以你得到一个项目的数组。当您尝试从索引3到索引0获取切片时,不能有任何符合条件index> = 3和< 0,所以你得到一个空数组。

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.

- 编辑 -

此外, array.slice()永远不应该返回undefined。这是使用它的优势之一。如果数组中没有匹配的值,则只返回一个空数组。即使您说 var a = new Array()并且不向其添加任何值,也请调用 a.slice(0,1)只会给你一个空数组。从数组边界外部切片也将返回一个空数组。 a.slice(250)将返回 [] a [250] 将是未定义的。

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.

这篇关于在数组上使用.slice方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:47