Javascript常见的DRY编程习语

时间:2013-07-08 20:50:42

标签: javascript

var veryLongObjectName = {};
// ...


if (!veryLongObjectName["verylongpropertyName"]) 
      veryLongObjectName["verylongpropertyName"] = 0;

if (veryLongObjectName["verylongpropertyName"]++) 
      console.log("I've seen it already");

我想通过改变最后两行来使上面的代码更简洁;我怎么能实现呢?

3 个答案:

答案 0 :(得分:2)

使用引用怎么样。

var veryLongObjectName = {};
var prop = veryLongObjectName["verylongpropertyName"];

if (!prop) 
    prop = 0;

if (prop++) 
    console.log("I've seen it already");

答案 1 :(得分:2)

如果他们打扰你,为什么不为你的物品和道具制作简易手柄:

var prop = 'longpropertyname';
var obj = longObjectName;
// do whatever you want with obj[prop]

答案 2 :(得分:1)

var veryLongObjectName = {};
var obj = veryLongObjectName;
var prop = "verylongpropertyName";

if (!obj[prop]) obj[prop] = 0;

if (obj[prop]++) console.log("I've seen it already");

或创建一个函数来处理你想要的事情:

function checkProp(obj, prop) {
    obj[prop] = obj[prop] || 0;
    if (obj[prop]++) console.log("I've seen it already");
}