例如,我有这个多维数组:
MyArray[('A', 40, true), ('B', 20, false), ('C', 55, true), ('D', 17, true)]
我想实现一个自定义的 min() 和 max() 原型(prototype)来获取 min 和 max ,其中只有这些是“true”......有什么技巧吗?我陷入困境,因为我正在考虑 .map() 来提取某个属性,但如何检查是否启用了由于 true/false 属性而提取的属性。
<小时/>准确地说,我做到了:
var MyArray = [];
MyArray.push( {
name: 'A',
valueA: 40,
valueB: 36,
enabled: true
});
MyArray.push( {
name: 'B',
valueA: 20,
valueB: 18,
enabled: false
});
MyArray.push( {
name: 'C',
valueA: 55,
valueB: 75,
enabled: true
});
.
.
.
这就是为什么我要寻找状态为 true 的最大值和最小值,排除那些为 false 的...
我尝试实现:
Array.minElement = function(array, prop) {
return Math.min.apply(Math,
array.filter(function(arr) { return arr['enabled']; })
.map(function(arr) { return arr[prop]; })
);
}
Array.maxElement = function(array, prop) {
return Math.max.apply(Math,
array.filter(function(arr) { return arr['enabled']; })
.map(function(arr) { return arr[prop]; })
);
}
所以我应该调用 Array.minElement(MyArray, 'valueA') 来获取最小值,但看起来它不起作用......并且它应该返回最小值......
我在这里做错了什么?...
非常感谢 干杯 路易吉
最佳答案
如果 MyArray
看起来像:
var MyArray = [['A', 40, true], ['B', 20, false], ['C', 55, true], ['D', 17, true]]
我会结合使用 filter
和 map
来获取数组,然后应用 Math
方法:
Math.max.apply(Math,
MyArray.filter(function(arr) { return arr[2]; })
.map(function(arr) { return arr[1]; })
); // => 55
关于Javascript自定义数组原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772323/