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
这里我需要检查所有对象属性数据是否为有效数据类型,但我无法实现。有人可以帮帮我吗?
答案 0 :(得分:1)
您无法在评估表达式的结果上为变量指定表达式。
'string' || 'number' || 'boolean' ;
评估为'string'
,因此您始终要测试该值是否为字符串。
将数据类型名称存储在数组中。然后使用indexOf
查看是否匹配。
var dataT = ['string', 'number', 'boolean'] ;
和
if ( dataT.indexOf(typeof this[p]) > -1 ) {
答案 1 :(得分:0)
if(typeof(this[p]) == 'string'
|| typeof(this[p]) == 'number'
|| typeof(this[p]) == 'boolean')
{
alert("have datatype");
}