简体   繁体   English

有人可以解释这个 JavaScript 代码是如何工作的吗?

[英]Can someone explain how this JavaScript code works?

I dont get it... why he used obj in this function, can someone explain what it doing.我不明白......为什么他在这个 function 中使用obj ,有人可以解释它在做什么。

 const yourArray = [37, 32,97,35,76,62] function equalizeArray(arr) { let obj = {}, max = 1 arr.forEach(el => { if (obj.hasOwnProperty(el)) { obj[el] = obj[el] + 1; if (obj[el] > max) { max = obj[el]; } } else{ obj[el] = 1 } }) return arr.length - max } console.log(equalizeArray(yourArray));

From what I gather, the function's purpose is to count the maximum number of same values in an array, and then subtract that maximum number ( max ) from the array's length and return that.据我所知,该函数的目的是计算数组中相同值的最大数量,然后从数组的长度中减去该最大数量( max )并返回。

The function uses an object obj to store array values as keys, and their repetition count as values to those keys. function 使用 object obj将数组值存储为键,并将它们的重复计数作为这些键的值。

The variable max keeps track of the maximum repetition, if any key has a value bigger than max it gets reassigned.变量max跟踪最大重复次数,如果任何键的值大于max ,它将被重新分配。

And then function returns array.length - max .然后 function 返回array.length - max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM