【问题标题】:want to use and operator with or at the same time想和或同时使用和运算符
【发布时间】:2015-04-20 23:55:12
【问题描述】:
var obj5 = {a:200, b:200, c:true};
var dataT = 'string' || 'number' || 'boolean' ;
obj5.notType = function(){
for (var p in this){
if(typeof(this[p]) == dataT){
alert("have datatype");}
}
};
obj5.notType(); // doesn't show alert
这里我需要检查所有对象属性数据是否是有效的数据类型,但我无法做到。谁能帮帮我?
【问题讨论】:
标签:
javascript
function
object
operators
type-conversion
【解决方案1】:
if(typeof(this[p]) == 'string'
|| typeof(this[p]) == 'number'
|| typeof(this[p]) == 'boolean')
{
alert("have datatype");
}
【解决方案2】:
您不能在计算表达式的结果上将表达式分配给变量。
'string' || 'number' || 'boolean' ; 的计算结果为 'string',因此您始终测试该值是否为字符串。
将您的数据类型名称存储在数组中。然后用indexOf看看有没有匹配。
var dataT = ['string', 'number', 'boolean'] ;
和
if ( dataT.indexOf(typeof this[p]) > -1 ) {