我们如何在 Javascript 中以函数式方式编写代码?
所以我最初做的是这样的
render () {
if (!this.props.mainListFetching && !this.props.mainListError) {
let testData = this.sortAmountPledgingMaximumOrMinimum(this.props.mainList, "maximum")
console.log(testData) //Coming out to be undefined
this.sortTypeTownOrCountry(this.props.mainList)
this.sortPercentHighestOrLeast(this.props.mainList)
}
这会调用以下函数
sortPercentHighestOrLeast = (data, type) => {
data.sort((a, b) => {
if (type == "maximum") {
return (
a["percentage.funded"] - b["percentage.funded"]
)
} else {
return (
b["percentage.funded"] - a["percentage.funded"]
)
}
})
console.log(data)
return data
}
我期望上述函数的结果将保存在我的 testData
变量中,但是当我 console.log
时,它是未定义的。
我的 console.log(data)
正在控制台中打印结果,确认函数正在执行并且数据不是未定义的?
[更新:]我也尝试过这个(因为 Js 是异步的)
let testData = this.sortAmountPledgingMaximumOrMinimum(this.props.mainList, "maximum", (data) => {
console.log("anything") //Doesn't log anything
})
最佳答案
假设 funded
是 percentage
的嵌套属性,您可以将条件检查向前移动一步,因为您会检查每个排序迭代。
sortPercentHighestOrLeast = (data, type) => data.sort(type => type === "maximum"
? (a, b) => a.percentage.funded - b.percentage.funded
: (a, b) => b.percentage.funded - a.percentage.funded
);
关于javascript - 如何在Js中以函数式的方式编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53243689/