Javascript:当属性可能不存在时,在对象中使用或条件
我试图找到一种优雅的Javascript方法来执行以下操作:Javascript:当属性可能不存在时,在对象中使用或条件,javascript,performance,Javascript,Performance,我试图找到一种优雅的Javascript方法来执行以下操作: var c; if(obj[i].cost){ c = obj[i].cost.toFixed(2); }else{ c = null } arr.push(c); 实际上,我有5-10个这样的元素,我正试图找到一种更有效的编码方法。大概是这样的: arr.push(obj[i].cost.toFixed(2) || null) arr.push(obj[i].cost ? obj[i].cost.toFixed(2)
var c;
if(obj[i].cost){
c = obj[i].cost.toFixed(2);
}else{
c = null
}
arr.push(c);
实际上,我有5-10个这样的元素,我正试图找到一种更有效的编码方法。大概是这样的:
arr.push(obj[i].cost.toFixed(2) || null)
arr.push(obj[i].cost ? obj[i].cost.toFixed(2) : null)
arr.push((cost = obj[i].cost) && cost.toFixed(2) || null)
很好,但是没有成本
属性时会中断
是否有一种最低限度的代码方法可以做到这一点,而无需对每个属性执行详细的if/else
语句 这个怎么样
var nullCost = {
toFixed: function() { return null; }
};
var c = (obj[i].cost || nullCost).toFixed(2);
我建议使用
条件(三元)运算符
,如下所示:
arr.push(obj[i].cost.toFixed(2) || null)
arr.push(obj[i].cost ? obj[i].cost.toFixed(2) : null)
arr.push((cost = obj[i].cost) && cost.toFixed(2) || null)
有关
条件(三元)运算符的更多信息,请查看此项。我将执行以下操作:
arr.push(obj[i].cost.toFixed(2) || null)
arr.push(obj[i].cost ? obj[i].cost.toFixed(2) : null)
arr.push((cost = obj[i].cost) && cost.toFixed(2) || null)
既然您试图编写优雅的JS,我建议您研究一下CoffeeScript:
arr.push obj[i].cost?.toFixed(2)
看。从技术上讲,如果它不存在,您将得到未定义而不是null,但CoffeeScript通常允许您编写相当优雅的代码。如果您的代码在索引器中使用了i
,那么它很可能正在循环体中使用
var c; //initiate variable
c = obj[i].cost ? obj[i].cost.toFixed(2) : null; //ternary for if/else block
arr.push(c); //push value to array
var c;
if(obj[i].cost){
// ^^^
c = obj[i].cost.toFixed(2);
// ^^^
}else{
c = null
}
arr.push(c);
我将做出一个巨大的假设,所以请更正它,因为它很有可能是错误的。我将假设该用法大致如下:
var arr = [];
for (i in obj) {
var c;
if (obj[i].cost) {
c = obj[i].cost.toFixed(2);
} else {
c = null;
}
arr.push(c);
}
假设此结构相当准确,则可以将代码简化为更具功能的内容
您可以将键作为集合访问,然后使用数组方法将函数应用于整个集合,而不是迭代对象的键:
var arr,
obj;
//this is a utility. It would be nice to have Object.values,
//but it's not supported in enough browsers yet
function values(obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
}
//this function gets a cost from a particular value
//it's reusable and concise
function getCost(value) {
return value.cost
? value.cost.toFixed(2)
: null;
}
//get the data however you get it
obj = ...;
//this is where everything actually happens
arr = values(obj).map(getCost);
这比你最初写的要长。这不一定是坏事
程序员倾向于使用尽可能短的代码。我鼓励您努力获得最可读的代码。如果它可读,就很容易理解,如果它容易理解,就很容易调试
例如:您提供的代码将0
值转换为null
。这可能是一个bug,您应该写的是:
if (obj[i].cost != null) {
如果在代码中反复使用此代码段,则需要在多个位置修复同一代码段
如果你把这一小块逻辑抽象成一个简单的函数。您只需更正该错误一次,其余代码将使用固定版本。三元运算符比if/else短。三元语句有什么问题arr.push((obj[i].cost)?obj[i].cost.toFixed(2):null)
如果您真的想缩短它,请使用三元运算符,否则If/else是最干净的方法。啊,太好了。我没有想到在这里使用三元运算符,但这是非常干净的。这是合法的,我想我会更多地使用三元运算符!这当然不是通常意义上的“干净”(易于阅读),但它很酷,您需要根据规则添加足够的解释以及代码。只是更新了一些注释。对不起,我是个新手