Mods:随意解释一下这个问题。 我想要做的是判断给定 dynamic 属性的数组中的所有值是否相同,如果true,则返回它。
我使用 underscore.js 在 3 行内实现了这一点,但是,我希望这可以被简化/缩短:
var val = this.children[0]["myProperty"];
var same = _.all(this.children, child => child["myProperty"] === val);
return same ? val : null;
这样如果:
this.children = [{"myProperty":null},{"myProperty":2},{"myProperty":1},{"myProperty":1}];
.. .返回null
this.children = [{"myProperty":1},{"myProperty":1},{"myProperty":1},{"myProperty":1}];
.. .returns 1
注意“myProperty”的值是个位数整数或 null
最佳答案
具有动态属性:
var prop = "myProperty";
//vanilla JS
return this.children.map(o => o[prop]).reduce((acc, v) => acc === v? v: null);
//and underscore
return _.reduce(_.pluck(this.children, prop), (acc, v) => acc === v? v: null);
关于JavaScript 函数比较数组中的值并返回它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37926048/