这个JS函数在做什么?

huangapple go评论57阅读模式
英文:

What is this JS function doing?

问题

我正在转换一个开源项目中的 array utilities 文件,将其从 JavaScript 转换为 TypeScript。大部分函数都很容易转换,但我不太明白这个函数在做什么。

/**
 * 根据对象条目的数字属性值对数组进行排序。null 条目将被视为 0。
 * 数组条目必须是对象。
 * @param {object[]} arr
 * @param {string} prop - 要排序的数字属性。
 */
export const propSort = (arr, prop) => {

	arr.sort((a, b) => {
		return (a[prop] || 0) - (b[prop] || 0);
	});

}

我有一个关于函数应该执行的描述,如上所示。但我不理解这个语法。显然,prop 应该是一个字符串。但如果是这样,ab 究竟是什么?如何使用字符串从数组中获取值?在将这个函数转换为 TypeScript 时是否存在任何问题?

英文:

I'm working on converting an array utilities file from js to typescript on an open source project. It's been pretty easy to convert most functions, but I'm not understanding what this one is doing.

/**
 * sort array by numeric by numeric property values
 * of object entries. null entries are treated as 0.
 * array entries must be objects.
 * @param {object[]} arr
 * @param {string} prop - numeric property to sort on.
 */
export const propSort = (arr,prop) => {

	arr.sort( (a,b)=>{
		return ( a[prop] || 0 ) - ( b[prop] || 0 );
	});

}

I have a description for what the function is supposed to be doing, as is listed above the function. But I don't understand the syntax. Apparently prop is supposed to be a string. But if that's the case, what exactly are a, b? How do you get the value out of an array using a string? And are there any pitfalls in converting this function to typescript?

答案1

得分: 2

这个函数本质上是围绕着数组的.sort()方法的一个包装器。如果你传递给.sort()一个回调函数,它将把这个回调函数传递给它用于排序目的的两个元素。然后,你的回调函数返回一个值,以确定这两个元素中的哪一个应该在前面,通过返回一个正值(ab之后)、负值(ab之前)或零(它们相等,它们的相对顺序无关紧要)。

propSort()函数只是运行.sort()并返回结果,但它传递给.sort()一个回调函数。回调函数的想法是arr的每个元素都是一个对象,并且你想根据每个对象都有的属性来对每个对象进行排序。

英文:

This function is essentially a wrapper around the .sort() method of arrays. If you pass .sort() a callback, it will pass that call back the two elements it is comparing for sorting purposes. Your callback then returns a value to determine which of the two elements should come first by returning a positive value (a comes after b), negative value (a comes before b), or zero (they are equal and their relative order doesn't matter).

The propSort() function just runs .sort() and returns the result, but passes .sort() a callback function. The idea of the callback function is that every element of arr is an object and you want to sort each object by a property that every object has.

huangapple
  • 本文由 发表于 2023年5月29日 12:24:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定