Underscore.JS - each 方法



語法

_.each(list, iteratee, [context]) 

each 方法迭代給定的元素列表,呼叫繫結到 context 物件(如果傳遞了此引數)的 iteratee 函式。Iteratee 會使用三個引數呼叫:(element, index, list)。對於 JavaScript 物件,iteratee 的物件將為 (value, key, list)。出於鏈化的目的,它將返回該列表。

示例

var _ = require('underscore');

var list = '';

//Example 1. access each number of array
_.each([1, 2, 3], function(x) { list += x + ' ' });
console.log(list);

list = ''

//Example 2. access each key-value of object
_.each({one: 1, two: 2, three: 3}, function(value, key) { list += key + ':' + value + ' ' });
console.log(list);

將上述程式儲存在 tester.js 中。執行以下命令來執行此程式。

命令

\>node tester.js

輸出

1 2 3
one:1 two:2 three:3
underscorejs_iterating_collection.htm
廣告
© . All rights reserved.