我正在为项目数组构建一个装饰器,如果对象数组适合的话,它就会被插入到定义的值范围内。
目前,我正在使用一些条件来检查范围,但我觉得代码不够干净。
有人对如何以更简洁和可扩展的方式编写此代码有任何建议吗?
当前设置示例...
thingsToSort.forEach(function(thing) {
if (thing > 1 || thing < 3) {
// set the item to 1
}
if (thing > 3 || thing < 5) {
// set to 3
}
})
注意:我确实在寻找一种更好的方法来循环此逻辑并确定对象是否落在范围内。
最佳答案
另一种实现。
- 创建了一个函数来表示范围,
Range
- 识别范围并采取适当措施的函数。
setcompareRange
注意函数 compareRange
中 some
方法的使用。由于只能在一个范围内找到一个数字,因此不会评估所有范围,直到完成匹配的范围遍历。
function Range(min, max){
this.min = min;
this.max = max;
}
var rangeArray = [ new Range(1,3), new Range(3,5)];
function compareRange(c,i,arr){
var result = rangeArray.some(x=> {
return setcompareRange(c, x.min, x.max)
});
}
function setcompareRange(thing, min, max){
if (thing > min && thing < max) {
// set the item to 1
console.log("set thing = " + thing + " in range = " + min);
return true;
}
}
var thingsToSort = [2,4];
thingsToSort.forEach(compareRange);
关于javascript - 遍历对象或数组以确定元素是否在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43595658/