在数组上使用.slice方法 [英] using .slice method on an array

查看:104
本文介绍了在数组上使用.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([]);       




为什么不至少切片果冻因为切片以
3开头?0的截止如何使其变为空?

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"]);  




如果截止索引超出了数组中当前存在的范围,
这意味着从slice创建的新数组将包含所有
索引从3开始直到数组结束?

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];  




会不会永远不定义我f
数组中不存在起始索引?

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



  });


推荐答案

Array.slice() 是切片的上限。

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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆