对数组索引进行有效性检查,以避免越界异常的出现。
示例代码如下:
function getElementByIndex(index, arr) {
if (index < 0 || index >= arr.length) {
throw new Error("Index out of range");
}
return arr[index];
}
describe("getElementByIndex", () => {
it("should return the element at the specified index", () => {
expect(getElementByIndex(3, [1, 2, 3, 4])).toBe(4);
});
it("should throw an error if the index is out of range", () => {
expect(() => getElementByIndex(5, [1, 2, 3, 4])).toThrow(
"Index out of range"
);
expect(() => getElementByIndex(-1, [1, 2, 3, 4])).toThrow(
"Index out of range"
);
});
});
在以上示例代码中,函数getElementByIndex
用于获取数组中指定索引处的元素。在传入的索引为负数或大于等于数组长度时,函数会抛出一个错误,提醒用户索引越界。
在Jest测试中,我们分别测试了能够正常获取元素的情况和抛出异常的情况,以保证函数能够正确的处理数组索引。