var veryLongObjectName = {};
// ...
if (!veryLongObjectName["verylongpropertyName"])
veryLongObjectName["verylongpropertyName"] = 0;
if (veryLongObjectName["verylongpropertyName"]++)
console.log("I've seen it already");
我想通过改变最后两行来使上面的代码更简洁;我怎么能实现呢?
答案 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");
}