JavaScript中如何判断属性是否存在,并与php比较
在PHP中判断数组元素是否存在,我们经常用到的函数是isset
、array_key_exists
及empty
,下面举几个例子
$a = array(1,2,3,'a'=>4,'b'=>5,'null'=>null); var_dump(array_key_exists('2',$a)); //bool(true) var_dump(isset($a['c'])); //bool(false) var_dump(isset($a['null']));//bool(false),因为该元素值为null var_dump(empty($a['c'])); //bool(true) var_dump(empty($a['null']));//bool(true)
写惯PHP的人,在接解JavaScript后,对其中的对象或数组元素的检测,有时候一下子转不过弯来,归根结底,是因为两门语言有着很大的不同。
在JavaScript语言中,既有对象又有数组,这根PHP语言不同,PHP语言的数组非常强大,它既有JS语言数组的特点又有JS对象的部分特点。这就造成如果生搬硬套PHP语言,那么写JS代码就非常困难。
JavaScript可以通过in运算符(PHP中可没有该运算符)、hasOwnProperty()和propertyIsEnumerable()方法来完成PHP中类似工作。
in运算符的左侧是属性名(字符串),右侧是对象。如果对象的自有属性或继承属性中包含这个属性则返回true。
对象的hasOwnProperty()方法用来检测给定的名字是否是对象的自有属性。对于继承属性它将返回false:
var o = {x:1}; console.log('x' in o); //=>true: "x"是o的属性 console.log('y' in o); //=>false: 'y'不是o的属性 console.log('toString' in o); //=>true: o继承toString属性 o.hasOwnProperty('x'); //=>true: o有一个自有属性x o.hasOwnProperty('y'); //=>false: o中不存在属性y o.hasOwnProperty('toString'); //=>true: toString是继承属性,而非自己的 //前面举的都是对象的例子,数组是一种特殊对象,它也可以这样判断 var a = [11,22,33,44,55]; console.log(4 in a); //true,对应元素55 console.log('4' in a); //true,不区分类型 console.log(a.hasOwnProperty(4));//true console.log(a.hasOwnProperty('4'));//true console.log(a.hasOwnProperty('toString'));//false
propertyIsEnumerable()在hasOwnProperty()上更进一步,它要求属性必须是可枚举的。比如toString
Object.prototype.propertyIsEnumerable('toString'); //false,不可枚举
除了使用in运算符外,另一种更简便的方法是使用!==
判断一个属性是否是undefined:
var o = {x:1}; console.log(o.x!==undefined); //true,o中的确有属性x console.log(o.y!==undefined); //false,o中没有该属性 console.log(o.toString!==undefined); //true,o有继承属性toString
然而有一种场景只能使用in运算符而不能使用上述属性访问的方式。in可以区分不存在的属性和存在但值为undefined的属性。例如,下面的代码:
var o = {x:undefined}; //属性被显示赋值为undefined o.x !== undefined; //false,属性存在,但值为undefined o.y !== undefined; //true,属性不存在 'x' in o; //true,属性存在 'y' in o; //false,属性不存在 delete o.x; //删除了属性x x in o; //false,属性不再存在
注意,上述代码中使用的是!==
运算符,而不是!=
。!==
可以区分undefined和null。这个区分跟PHP语言中的array_key_exists与isset非常相似。有时当然也不必作这种区分。
//如果o中含有属性x,且x的值不是null或undefined,o.x乘以2 if(o.x!=null) o.x *= 2; //如果o中含有属性x,且x的值不能转换为false,o.x乘以2 //如果x是undefined、null、false、""、0或NaN,则它保持不变 if (o.x) o.x *= 2;
本文中的PHP代码是在ThinkPHP中完成,下面演示如何在ThinkPHP使用

- 忙时收藏,闲时看,用时想找您不好找,轻轻一点收藏到您的空间