javascript - 将数组从函数中推送到另一个函数中

标签 javascript arrays function

我对嵌套函数有疑问

如何获取包含 [1, 2, 3] 的 b 数组:

function someFunc() {
  const a = [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
  const b = []
  
  function someOtherFunc() {
    a.forEach(i => {
      b.push(i.id)
    })
  }
  return b
}

console.log(someFunc())

最佳答案

您得到一个空数组,因为 someOtherFunc 函数未执行。

function someFunc() {
  const a = [{ id: 1}, { id: 2 }, { id: 3 }];
  let b = [];
  
  someOtherFunc();
  
  function someOtherFunc() {
    a.forEach(i => {
      b.push(i.id)
    })
  }
  return b
}

console.log(someFunc())

或者更快的解决方案,使用Array#map

function someFunc() {
  console.log([{ id: 1 }, { id: 2 }, { id: 3 }].map(v => v.id));
}

someFunc();

关于javascript - 将数组从函数中推送到另一个函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774419/

相关文章:

function - PowerShell 函数来求一个数 : 的平方

Javascript 函数仅在有警报时才有效

javascript - nodemon 监视目录以进行更改

php - 具有相应输入值的复选框数组

php - PHP 数组键可以有别名吗?

arrays - 如何将可变长度数组常量作为参数传递?

JavaScript 函数() 和函数()

javascript - 我怎样才能获得 fb :chat-invite using facebooks javascript sdk or xfbml 的功能

javascript - Scrapy Scraper 无法正确抓取图像

javascript - 如何使用 REST API 获取列表中多个人或组列的标题