我对嵌套函数有疑问
如何获取包含 [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/