📜  Lodash _.forEach() 方法

📅  最后修改于: 2022-05-13 01:56:20.213000             🧑  作者: Mango

Lodash _.forEach() 方法

_.forEach()方法迭代集合的元素并为每个元素调用 iteratee。

句法:

_.forEach( collection, [iteratee = _.identity] )

参数:此方法接受上面提到的两个参数,如下所述:

  • 集合:此参数保存要迭代的集合。
  • iteratee:它是每次迭代调用的函数。

返回值:此方法返回集合。

注意:这里使用 const _ = require('lodash') 将 lodash 库导入文件。

示例 1:

Javascript
// Requiring the lodash library  
const _ = require("lodash");  
  
// Use of _.forEach() method 
_.forEach(['c', 'cpp', 'java','python'], function(value) {
  console.log(value);
});


Javascript
// Requiring the lodash library  
const _ = require("lodash");  
  
// Use of _.forEach() method 
_.forEach({ 'x': 1, 'y': 2 }, function(value, key) {
  console.log(key);
});


输出:

'c'
'cpp'
'java'
'python'
['c', 'cpp', 'java','python']

示例 2:

Javascript

// Requiring the lodash library  
const _ = require("lodash");  
  
// Use of _.forEach() method 
_.forEach({ 'x': 1, 'y': 2 }, function(value, key) {
  console.log(key);
});

输出:

'x'
'y'
{ 'x': 1, 'y': 2 }

注意:这在普通 JavaScript 中不起作用,因为它需要安装库 lodash。

参考: https://lodash.com/docs/4.17.15#forEach