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.