js written test questions compare version number function

Implement a function and pass in (v1, v2) If v1>v2 return 1 v1<v2 return 0 otherwise return 0
compareVersion('1.1', '1.1.0'), 0
compareVersion('13.37', '1.2'), 1
compareVersion('0.1', '1.1.1'). -1

function compareVersion(v1, v2) {
    
    
  const v1Arr = v1.split(".")
  const v2Arr = v2.split(".")

  const maxLength = Math.max(v1Arr.length, v2Arr.length)
  while (v1Arr.length < maxLength) {
    
    
    v1Arr.push("0")
  }
  while (v2Arr.length < maxLength) {
    
    
    v2Arr.push("0")
  }
  for (let i = 0; i < maxLength; i++) {
    
    
    const num1 = parseInt(v1Arr[i])
    const num2 = parseInt(v2Arr[i])
    if (num1 > num2) {
    
    
      return 1
    } else if (num1 < num2) {
    
    
      return -1
    } else {
    
    
      return 0
    }
  }
}

console.log(compareVersion('1.1', '1.1.0'), compareVersion('13.37', '1.2'), compareVersion('0.1', '1.1.1'))

Guess you like

Origin blog.csdn.net/weixin_45959525/article/details/123064223