gpt4 book ai didi

javascript - 如何从某个属性最小的数组中选择一个对象?

转载 作者:行者123 更新时间:2023-11-30 18:32:55 26 4
gpt4 key购买 nike

我刚开始了解 Coffescript,发现需要从特定属性最小的数组中选择一个对象。我在下面列出了我的基本代码:

class Point
constructor: (@x, @y, @z) ->

addedTogether: ->
@x+@y+@z

class PointCollection
constructor: ->
@points = []

add: (point) ->
@points.push(point)

minimalPoint: ->
// need to return point with lowest addedTogether value

samplePoints = new PointCollection()
samplePoints.add(new Point(1,2,3))
samplePoints.add(new Point(2,3,4))
samplePoints.add(new Point(3,4,5))
samplePoints.add(new Point(4,5,6))
samplePoints.add(new Point(5,6,7))
samplePoints.add(new Point(1,1,1))

lowestValuePoint = samplePoints.minimalPoint()

我显然可以在普通的旧 javascript 中使用如下函数来做到这一点:

function findPointWithLowestScore(points) {
var lowestScoringPoint = points[0];

for (var i = 0; i < points.length; i++) {

lowestScoringPoint = (points[i].addedTogether() < lowestScoringPoint.addedTogether()) ? points[i] : lowestScoringPoint;
}
return lowestScoringPoint;
}

但是是否有更好、更简洁、符合 CoffeeScript 风格的方式来做到这一点?

最佳答案

尝试这样的事情:

class Point
constructor: (@x, @y, @z) ->

addedTogether: ->
@x+@y+@z

class PointCollection
constructor: ->
@points = []

add: (point) ->
@points.push(point)

minimalPoint: ->
tmp = @points.slice 0 # duplicate array
tmp.sort (a, b) -> a.addedTogether() - b.addedTogether() # Sort from lowest to highest
tmp[0] # Return the first element

samplePoints = new PointCollection()
samplePoints.add(new Point(1,2,3))
samplePoints.add(new Point(2,3,4))
samplePoints.add(new Point(3,4,5))
samplePoints.add(new Point(4,5,6))
samplePoints.add(new Point(5,6,7))
samplePoints.add(new Point(1,1,1))

lowestValuePoint = samplePoints.minimalPoint()

关于javascript - 如何从某个属性最小的数组中选择一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9094807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com