gpt4 book ai didi

google-apps-script - instanceof 字符串在 Google Apps 脚本中的行为不符合预期

转载 作者:行者123 更新时间:2023-12-02 05:54:48 24 4
gpt4 key购买 nike

我想检查 Apps 脚本中的变量是否是字符串,但发现当变量实际上是字符串时,instanceof 没有返回 true。测试如下:

function test_instanceof() {
var a = "a";
Logger.log('"a" is ' + ((a instanceof String) ? '' : 'not ') + 'a String');
var b = String("b");
Logger.log('String("b") is ' + ((b instanceof String) ? '' : 'not ') + 'a String');
}

记录这两条消息:

"a" is not a String
String("b") is not a String

文档并不清楚所支持的 ECMAScript 子集,但显然,instanceof 是一个有效的运算符,并且 String 是一个有效的类型,从以下事实来看:代码执行时没有异常。

检查变量类型的适当方法是什么?

最佳答案

这是标准的 EcmaScript 3。

您的代码正在执行 JavaScript 所期望的操作:请参阅此处的 equivalent JavaScript running in your browser

Instanceof 检查原型(prototype)链中是否有匹配的构造函数。这对于通过“new”创建的对象很有用,但对于字符串则不太有帮助。对于 String,您真正想要的是 typeof,如 this example in your browser 所示。或等效的 Apps 脚本代码:

function test_instanceof() {
var a = "a";
Logger.log('"a" is ' + ((typeof a == 'string') ? '' : 'not ') + 'a String');
var b = String("b");
Logger.log('String("b") is ' + ((typeof b == 'string') ? '' : 'not ') + 'a String');
}

关于google-apps-script - instanceof 字符串在 Google Apps 脚本中的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571923/

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