【发布时间】:2023-03-25 18:28:01
【问题描述】:
这是我的代码
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
devices = ['x', 'y', 'z'];
device;
constructor(public navCtrl: NavController) {
this.device = 'a';
for(let i = 0; i<this.devices.length; i++){
if(this.device == this.devices[i]){
console.log('Match');
} else {
console.log('No matches');
}
}
}
}
我在想,如果我的设备列表变得太长,那么匹配会明显变慢。所以想问问有没有更好更快更有效的方法来检查数组中是否存在值。
我想要实现的是出勤率。
我的应用会扫描 id,然后检查它是否在我的列表中。 如果匹配,我会将布尔值设置为 true(用于测试目的) 所说的布尔值将在我的列表中。 像这样的
device = {
name: '-K8d34fsd2',
attendance: true
};
这是我尝试过的
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
devices = [
{
id: 'qwerty123',
attendance: false
},
{
id: 'zxcvb123',
attendance: false
},
];
device;
constructor(public navCtrl: NavController) {
this.device = 'qwerty123';
// for(let i = 0; i<this.devices.length; i++){
// if(this.device == this.devices[i]){
// console.log('Match');
// } else {
// console.log('No matches');
// }
// }
if(this.devices.id.indexOf(this.device) > -1){
console.log('Match');
} else {
console.log('No matches');
}
}
}
【问题讨论】:
-
改用
Set,然后mySet.has就是O(1) -
你的意思是这样的js吗? var numbers = [4, 9, 16, 25, 29]; var first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; }
-
不,我的意思是使用实际的
Set。new Set(.... -
你的数组能以任何方式排序吗?在您需要搜索之前,是否已经可以对数组执行排序?搜索性能不仅与匹配功能有关,还与不匹配时的处理有关 - 例如二进制排序等。
-
@CertainPerformance 哦,我明白了,将对此进行更多研究。谢谢楼主!
标签: javascript arrays angular performance string-matching