Underscore.JS - 范围方法



语法

_.range([start], stop, [step])

范围方法创建整数列表。我们可以使用传入的参数来配置此列表。start 默认值为 0,指定列表的第一个元素,stop 指定以递增顺序创建元素的范围,元素使用 step 递增。step 默认值为 1。列表不包含 stop。

示例

var _ = require('underscore');

//Example 1: create an array of 5 elements
result = _.range(5);
console.log(result)

//Example 2: create an array of 5 elements from 5 to 10
result = _.range(5, 11);
console.log(result)

//Example 3: create an array of elements from 0 to 20(exclusive) with step 5
result = _.range(0, 20, 5);
console.log(result)

//Example 4: create an array of 5 negative elements
result = _.range(0, -5, -1);
console.log(result)

//Example 5: create an empty array
result = _.range(0);
console.log(result)

将以上程序保存在 tester.js 中。运行以下命令来执行此程序。

命令

\>node tester.js

输出

[ 0, 1, 2, 3, 4 ]
[ 5, 6, 7, 8, 9, 10 ]
[ 0, 5, 10, 15 ]
[ 0, -1, -2, -3, -4 ]
[]
underscorejs_processing_array.htm
广告
© . All rights reserved.