You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Array.from方法返回含undefined的数组而非1-7,求原因

为什么你的abcd数组是[undefined *7]而不是1到7?

嘿,这个问题其实很常见,核心原因就一个:你的回调函数没有返回值!

让我拆解一下细节:

  • Array.from()的第二个参数是一个映射函数,它的作用就是给新数组的每个元素赋值——你必须从这个函数里返回你想要的元素值,不然函数会默认返回undefined。
  • 看你的原代码:
    let abcd= Array.from({length:7},(curr,i)=> { 
      console.log(curr,i); 
      i+1; // 这里只是计算了i+1,但根本没把这个结果返回出去!
    }) 
    
    你在回调里写了i+1,但没有用return关键字把这个值返回给Array.from(),所以这个映射函数每次执行都默认返回undefined,最后生成的数组自然就是7个undefined了。

修正后的代码

只需要补上return就行,甚至可以简化写法:

// 写法1:保留console的显式return版本
let abcd= Array.from({length:7},(curr,i)=> { 
  console.log(curr,i); 
  return i+1; 
}) 

// 写法2:箭头函数省略大括号,自动返回表达式结果
let abcd= Array.from({length:7},(curr,i)=> i+1) 

这样运行后,abcd就会是[1,2,3,4,5,6,7]啦~

补充个小技巧:curr参数在这里其实没用到,你可以把它换成下划线(_)来表示这个参数是占位用的,代码可读性会更好:

let abcd= Array.from({length:7},(_,i)=> i+1) 

内容的提问来源于stack exchange,提问作者Eitanos30

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:11:26