尝试遵循此答案中的指南时遇到 ScriptProperties 错误(https://stackoverflow.com/a/77856464/29032043)
我可以正常运行 onOpen 和 logEverything,但尝试运行 addView 时出现以下错误:
错误 类型错误:无法解构“未定义”的属性“查看器”,因为它未定义。 addView @Code.gs:11
我当前的代码如下,我按照指示遵循“查看者”的编辑脚本属性说明。我是否需要添加额外的脚本属性或在代码本身中为其添加定义?
const PROP_SERVICE = PropertiesService.getScriptProperties();
const onOpen = () => {
const email = Session.getActiveUser().getEmail(),
date = new Date().toLocaleString(),
viewers = JSON.parse(PROP_SERVICE.getProperty('viewers')),
user = email.split('@')[0];
addView({viewers, user, email, date});
};
const addView = ({viewers, user, email, date}) => {
if (viewers[user]) {
viewers[user].count++;
} else {
viewers[user] = {
count : 1,
visits : [],
email
};
}
viewers[user].visits.push(date);
console.log(`Added view for ${user}`);
saveView(viewers);
};
const saveView = viewers => {
PROP_SERVICE.setProperty('viewers', JSON.stringify(viewers));
console.log('view saved');
};
const logEverything = () => {
const viewers = JSON.parse(PROP_SERVICE.getProperty('viewers'));
for (user in viewers) {
console.log(`User ${user} has visited ${viewers[user].count} time/s with email ${viewers[user].email}.`);
console.log(viewers[user].visits);
}
};
我尝试在 addView 块中的“查看者”周围添加引号。还尝试定义用户或设置默认值。结果没有变化,仍然发回错误消息说未定义。
任何帮助将不胜感激 - 我对此很陌生!
不存在
viewers
的属性值存在并且可能影响以下代码的实例,因为它会 return null
。
为了使事情正常工作,需要设置代码以使用
setProperty()
方法设置属性。
function onOpen(){
let email = Session.getActiveUser().getEmail(),
date = new Date().toLocaleString(),
viewers = JSON.parse(PROP_SERVICE.getProperty('viewers')),
user = email.split('@')[0];
// If the property viewers does not exist it create the property.
if(!PROP_SERVICE.getProperty('viewers')){
viewers = PROP_SERVICE.setProperty('viewers', {});
}
addView({viewers, user, email, date});
};
示例输出:
10:46:53 PM Info User sample has visited 1 time/s with email [email protected].
10:46:53 PM Info [ '1/3/2025, 10:39:54 PM' ]
10:46:53 PM Info User sample2 has visited 2 time/s with email [email protected].
10:46:53 PM Info [ '1/3/2025, 10:46:15 PM', '1/3/2025, 10:46:50 PM' ]
注意: 要完成此工作,应将文档作为编辑者发送。
参考: