gpt4 book ai didi

javascript - 访问不存在的属性的安全方法

转载 作者:行者123 更新时间:2023-12-01 01:02:32 25 4
gpt4 key购买 nike

我使用带有 JavaScript 代码的 Google Apps 脚本,运行 UrlFetchApp,从 Stripe API 提取数据以检索发票。然后,该脚本将 API 中的数据更新到 Google 表格模板中。

我遇到的问题是,如果 API 在客户的特定行上没有数据,则会破坏脚本。 API 将缺少数据存储为 NULL,例如,当客户的发票上没有折扣时,"discount": null

当脚本到达没有数据的行时,NULL 响应会中断脚本并停止运行。我想要做的是返回一个值,指定没有数据(例如:返回数字 0 表示没有折扣),并让脚本继续运行其余的代码行。

我的代码:

function getInvoiceObj() 
{
var apiKey, content, options, response, secret, url;

secret = "rk_live_xxxxxxxxxxxxxxxxxx";
apiKey = "xxxxxxxxxxxxxxxxx";

url = "https://api.stripe.com/v1/invoices/in_xxxxxxxxxxxxx?expand[]=charge&expand[]=customer";

options = {
"method" : "GET",
"headers": {
"Authorization": "Bearer " + secret
},
"muteHttpExceptions":true
};

response = UrlFetchApp.fetch(url, options);

//Push data to Sheet from invoice. **Writes over existing Sheet data**
content = JSON.parse(response.getContentText());
var sheet = SpreadsheetApp.getActiveSheet();

/* Customer Discount */

sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);
}

最佳答案

您可能正在寻找if

if(content.discount===null)
sheet.getRange(21,2).setValue([0]);
else
sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);

也许?:

sheet.getRange(21,2).setValue([
content.discount===null?0:content.discount.coupon.percent_off
]);

关于javascript - 访问不存在的属性的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55929046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com