You need to enable JavaScript to run this app. JS使用函数给对象键赋值时返回函数本身而非返回值如何解决
优惠活动
大模型
产品
解决方案
定价
更多

JS使用函数给对象键赋值时返回函数本身而非返回值如何解决

问题原因

你当前直接把箭头函数赋值给了SORT属性,因此属性存储的是函数对象本身,而非函数执行后的返回值。

解决方案

方案1:使用立即执行函数表达式(IIFE)

在函数定义完成后立刻执行,直接将返回值赋值给SORT属性,修改后的代码如下:

statementPdfs.push ({
    NAME: currFile.getName(), 
    ID: currFile.getId(), 
    BLOB: currFile.getBlob(), 
    MIME_TYPE: currFile.getBlob().getContentType(),
    URL: currFile.getUrl(),
    SORT:  (() => {
        let dates = currFile.getName().match(/(\w+)\s(\d+)/);
        return (dates[2]+ 
            (dateNums[dates[1].toUpperCase()] < 10
                ? "0"+dateNums[dates[1].toUpperCase()]
                : dateNums[dates[1].toUpperCase()]
            )
        );
    })()
});

方案2:提前计算SORT值后赋值

提前把排序值计算逻辑抽出来,计算完成后再给对象属性赋值,代码可读性更高,也方便后续调试修改,同时增加了匹配失败的兜底逻辑避免报错:

const fileName = currFile.getName();
const dates = fileName.match(/(\w+)\s(\d+)/) || [];
let sortVal = '000000'; // 匹配失败时的默认兜底值
if (dates[1] && dates[2]) {
  const monthUpper = dates[1].toUpperCase();
  const monthStr = dateNums[monthUpper] < 10 ? `0${dateNums[monthUpper]}` : dateNums[monthUpper];
  sortVal = dates[2] + monthStr;
}

statementPdfs.push ({
    NAME: fileName, 
    ID: currFile.getId(), 
    BLOB: currFile.getBlob(), 
    MIME_TYPE: currFile.getBlob().getContentType(),
    URL: currFile.getUrl(),
    SORT: sortVal
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 10:27:03