检查JavaScript中是否存在属性 [英] Checking existence of properties in JavaScript

查看:115
本文介绍了检查JavaScript中是否存在属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript新手,对鸭子打字概念有点困惑。据我所知,我理解这个概念。但这导致了我思想中的奇怪后果。我将用以下示例解释:

I'm new to JavaScript and a little bit confused with the duck typing concept. As far as I can tell, I understood the concept. But that leads to a strange consequence in my thoughts. I will explain with the following example:

我目前正在使用jQuery Mobile开发移动网络应用程序。有时我会为画布捕获 vmousedown 事件。我对触摸的压力很感兴趣。我找到了 Touch.webkitForce 属性。

I'm currently working on a mobile web app with jQuery Mobile. At one point I capture the vmousedown event for a canvas. I'm interested in the pressure of the touch. I found the Touch.webkitForce property.

$('#canvas').live('vmousedown', function(e){
    console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
}

使用远程调试。但在Opera Firefly中测试时会抛出异常,因为 originalEvent 属性不是触摸事件,而是点击事件。

This works fine when using the Remote Debugging for Chrome. But throws an exception when testing in Opera Firefly, because the originalEvent property is no touch event, but a click event.

因此,每当我访问不属于我权限的对象的属性时,我是否必须检查存在并输入?

So every time I access a property of an object which is not under my authority, do I have to check existence and type?

if( e.originalEvent &&
    e.originalEvent.originalEvent &&
    e.originalEvent.originalEvent.touches && 
    e.originalEvent.originalEvent.touches[0] && 
    e.originalEvent.originalEvent.touches[0].webkitForce) {

    console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
}

请有人为我澄清一下吗?

Can please someone clarify that for me?

推荐答案


因此,每当我访问不属于我权限的对象的属性时,我是否必须检查存在并键入?

So every time I access a property of an object which is not under my authority, do I have to check existence and type?

是的,你必须一次检查整个路径,或者你可以自动化它:

Yes you will have to check the whole path, once at a time, or you can automate it:

function deepObject(o, s) {
    var ss = s.split(".");

    while( o && ss.length ) {
        o = o[ss.shift()];
    }

    return o;
}

var isOk = deepObject(e, "originalEvent.originalEvent.touches.0.webkitForce");

if ( isOk ) {
    // isOk is e.originalEvent.originalEvent.touches.0.webkitForce;
}






测试用例:

var o = {
  a: {
    b: {
      c: {
        d: {
          e: {
          }
        }
      }
    }
  }
}

var a = deepObject(o, "a.b.c");
var b = deepObject(a, "d");

console.log(a); // {"d": {"e": {}}}
console.log(b); // {"e": {}}
console.log(deepObject(o, "1.2.3.3")); // undefined

这篇关于检查JavaScript中是否存在属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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