首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计算数组中包含没有空值的特定键的对象数量

计算数组中包含没有空值的特定键的对象数量
EN

Code Review用户
提问于 2019-02-24 13:00:23
回答 2查看 46关注 0票数 0

这是我的源代码:

代码语言:javascript
运行
复制
// start at zero
var count = 0;
// loop through the items
for(var i = 0; i < hours.length; i++) {
  // 1. check to see if the current item has a key called "description"
  // 2. check to see if the current item's "description" key isn't empty
  // NOTE: white-space only values aren't valid
  if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
    // increment the count (by one)
    count += 1;
  }
}
// return the count
return count;

删除注释时,代码如下所示:

代码语言:javascript
运行
复制
var count = 0;
for(var i = 0; i < hours.length; i++) {
  if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
    count += 1;
  }
}
return count;

这似乎相当昂贵(特别是对于较大的数组)。是否有更好(最好是更简洁)的方法来计算数组中包含没有空值的特定键的对象的数量?

信息:我不能使用jQuery或LoDash/下划线,所有方法都必须在浏览器中本地可用,并且具有良好的浏览器支持(IE8+)。

EN

回答 2

Code Review用户

回答已采纳

发布于 2019-02-25 00:34:32

使用String.replace意味着您需要跨出您正在测试的每个字符串中的每个字符。不仅如此,它还需要分配内存来保存产生的新字符串。

如果您测试一个非空白字符,它会快得多。这样,它只需要测试第一个非空白,它不需要额外的内存。

而且,Object.hasOwnProperty速度慢,因为它必须沿着prototype链向上工作才能得到答案,并且只有当您认为正在测试的对象具有包含正在测试的属性名称的原型链时,才应该使用它。

最后一点。这不是您提供的代码的一部分,但是为了提高性能,属性hour.description不应该只包含空格。设置该属性时,检查它(如hour.description = descriptionString.trim(); )

因此,如果您有未经过检查的描述字符串

代码语言:javascript
运行
复制
var i, count = 0;
for (i = 0; i < hours.length; i++) {
    count += hours[i].description && (/\S/).test(hours[i].description) ? 1 : 0;
}
return count;

如果已经对描述进行了审查,那么下面的说明将是最快的

代码语言:javascript
运行
复制
var i, count = 0;
for (i = 0; i < hours.length; i++) {
    count += hours[i].description ? 1 : 0;
}
return count;
票数 2
EN

Code Review用户

发布于 2019-02-24 15:37:09

我不是JS性能专家,但您可以尝试如下:

代码语言:javascript
运行
复制
var count = 0;
const numHours = hours.length;  // Don't denominate the length on each loop.
for(var i = 0; i < numHours; i++) {
  let description = hours[i].description;  // Don't denominate the description two times.
  // Just search for something that isn't a space character (yes, capital "S").
  if(description && (description.search(/\S/g) !== -1)) {
    count++;  // May be better too.
  }
}
return count;

而且,RegEx通常是昂贵的,你可以试着摆脱它们。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/214166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档