【问题标题】:run console one time inside map function using javascript / node js [closed]使用javascript / node js在map函数中运行一次控制台[关闭]
【发布时间】:2021-08-21 23:47:56
【问题描述】:

我有一个数组,我想将它的变量存储在文件中,因为我在 map 函数之外声明了文件

let object = [
  {
    id: '01',
    name: 'Subject',
    'Data.type': 'maths',
  },
  {
    id: '02',
    name: null,
    'Data.type': 'science',
  },
  {
    id: '04',
    name: 'language',
    'Data.type': 'node',
  },
  {
    id: '05',
    name: null,
    'Data.type': 'node',
  },{
    id: '01',
    name: 'Subject',
    'Data.type': 'maths',
  },
  {
    id: '02',
    name: 'Subject',
    'Data.type': 'science',
  },
  {
    id: '04',
    name: null,
    'Data.type': 'node',
  },
  {
    id: '05',
    name: null,
    'Data.type': 'node',
  }
];
let names=[];
object.map((value) => {
  if(typeof value.name === "string"){
  names.push(value.name);
  console.log(names);
  }
//some code here
//code here
// use of names to perform some task
})

值是这样打印的

["subject"]

["subject",
 "language"]

["subject",
 "language",
 "subject"]

["subject",
 "language",
 "subject",
 "subject"]

有没有可能它应该只在 map 函数中运行 1 次,其中包含完全加载的值,所以我可以在 map 函数中执行任务

files= ["subject",
 "language",
 "subject",
 "subject"]

【问题讨论】:

  • 是的 - let names = object.map((value) => { ... }) 然后 console.log(names);
  • 为什么不把console.log移到map之外呢?还有为什么是map 而不是forEach
  • 嗨@GuerricP,因为我需要其他键值来执行某些任务,这就是我使用地图功能的原因

标签: javascript node.js arrays object nodes


【解决方案1】:

Array.prototype.map():

array.map 的目的是创建一个新数组,其中每个元素都更改为原始元素通过所提供函数的结果。

例如,

var a = [1, 2, 3];

function times2(n) {
  return n * 2;
}

var b = a.map(times2);
console.log(b); // Will log [2, 4, 5]

Array.prototype.forEach():

还有函数array.forEach。这样做的目的是运行一个函数,将数组的每个元素按顺序作为输入。

例如,

a = [1, 2, 3];

a.forEach(console.log); // Will log: "1", then "2", then "3".

您的解决方案:

您希望对数组的每个元素运行一个函数。

您的函数应该将一个元素作为输入,并将其推送到另一个现有数组。

您应该等到每个元素都添加到新数组中才记录它。

例如,

let names = [];

function addToNames(element) {
  if (typeof element.name === "string") {
    names.push(element.name);
  }
}

object.forEach(addToNames);
console.log(names);
// Now that names array is complete, you can do whatever you need with it.

另一个选项,使用箭头函数,

let names = [];

object.forEach(element => {
  if (typeof element.name === "string") {
    names.push(element.name);
  }
});
console.log(names);
// Now that names array is complete, you can do whatever you need with it.

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多