JS 重写toFixed方法

JavaScript010

JS 重写toFixed方法,第1张

// 重写toFixed方法

Number.prototype.toFixed = function (n) {

  if (n >20 || n <0) {

      throw new RangeError('toFixed() digits argument must be between 0 and 20')

  }

  const number = this

  if (isNaN(number) || number >= Math.pow(10, 21)) {

      return number.toString()

  }

  if (typeof (n) == 'undefined' || n == 0) {

      return (Math.round(number)).toString()

  }

  let result = number.toString()

  const arr = result.split('.')

  // 整数的情况

  if (arr.length <2) {

      result += '.'

      for (let i = 0i <ni += 1) {

          result += '0'

      }

      return result

  }

  const integer = arr[0]

  const decimal = arr[1]

  if (decimal.length == n) {

      return result

  }

  if (decimal.length <n) {

      for (let i = 0i <n - decimal.lengthi += 1) {

          result += '0'

      }

      return result

  }

  result = integer + '.' + decimal.substr(0, n)

  const last = decimal.substr(n, 1)

  // 四舍五入,转换为整数再处理,避免浮点数精度的损失  正数+1 负数-1

  if (parseInt(last, 10) >= 5) {

      const x = Math.pow(10, n)

      result = (Math.round((parseFloat(result) * x)) + (parseFloat(result) >0 ? 1 : -1)) / x

      result = result.toFixed(n)

  }

  return result

}

js在构造函数里面原型重写就是prototype.xxx,xxx是用户自定义的函数名。

比如定义一个add方法,写法如下:

Number.prototype.add = function(num){return(this+num)}

prototype 是在 IE 4 及其以后版本引入的一个针对于某一类的对象的方法,当你用prototype编写一个类后,如果new一个新的对象,浏览器会自动把prototype中的内容替你附加在对象上。这样,通过利用prototype就可以在JavaScript中实现成员函数的定义,甚至是“继承”的效果。

当然可以啊:

<div id=test></div>

<script>

for(var i=0i<10i++){

var child=document.createElement("span")

child.innerHTML=i+1

test.appendChild(child)

}

</script>

关键在于每次重写的子元素都要重新生成,而不能够把同一个元素修改后添加,否则最终只有一个子元素被添加。