instanceof字符串在Google Apps脚本中的行为不如预期 [英] instanceof String not behaving as expected in Google Apps Script

查看:82
本文介绍了instanceof字符串在Google Apps脚本中的行为不如预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  function test_instanceof(){
var a =a;
Logger.log(''a'是'+((一个String的实例)?'':'not')+'a String');
var b = String(b);
Logger.log('String(b)is'+((b instanceof String)?'':'not')+'a String');
}

记录以下两条消息:

 a不是字符串
字符串(b)不是字符串

文档不支持ECMAScript的子集,尽管显然instanceof是一个有效的运算符,String是一个有效的类型,从
代码执行时没有例外。



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

解决方案

这是标准的EcmaScript 3.



您的代码正在执行JavaScript所期望的内容:请参阅在您的浏览器中运行的等效JavaScript

Instanceof检查原型链中的匹配构造函数。这对通过新建创建的对象很有用,但对字符串不是很有帮助。您实际需要的字符串是typeof,如浏览器中的此示例或等效的Apps脚本代码所示:

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


I wanted to check whether a variable in an Apps Script was a String, but found that instanceof wasn't returning true when the variable was in fact a string. The following test:

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');
}

Logs these two messages:

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

The docs aren't clear on the subset of ECMAScript that is supported, though apparently instanceof is a valid operator and String is a valid type, judging from the fact that the code executed without an exception.

What is the appropriate way to check the type of a variable?

解决方案

It's standard EcmaScript 3.

Your code is doing what JavaScript expects: see here for the equivalent JavaScript running in your browser.

Instanceof checks for a matching constructor in the prototype chain. That's good for objects created via 'new' but not very helpful for strings. What you actually want for String is typeof, as shown in this example in your browser or the equivalent Apps Script code:

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');
}

这篇关于instanceof字符串在Google Apps脚本中的行为不如预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆