前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPS JS宏——Number对象

WPS JS宏——Number对象

作者头像
xyj
发布2022-12-01 11:36:43
1.5K0
发布2022-12-01 11:36:43
举报
文章被收录于专栏:VBA 学习VBA 学习VBA 学习
操作系统:Linux version 4.4.131.D001.64.190906 (YHKYLIN-OS@Kylin)
WPS版本:WPS Office 2019 WPS表格(11.8.2.10533)

js是面向对象弱类型的编程语言,在VBA中熟悉的Integer、Long、Single、Double这些数值类型,在js不需要明确的去声明就可以使用,如果一定要声明,只能是声明为统一的Number对象。

从最大值Number.MAX_SAFE_INTEGER和最小值Number.MIN_SAFE_INTEGER上看,应该和VBA的Double类型是一样的。

Number作为一种对象,就会有相应的属性和方法,这个和VBA的类是一样的概念,在js里使用对象相比VBA里创建类来使用就方便了许多。

Number有2种方法声明,使用new关键字声明:

function testNewNumber() {
  var i = new Number(3.1415926) 
  
  Debug.Print("type i: " + typeof(i) + " " + i.toString()) 
  Debug.Print("toLocaleString i: " + i.toLocaleString()) // 本地格式字符串 
  Debug.Print("toFixed i: " + i.toFixed(3)) // 四舍五入 
  Debug.Print("toExponential i: " + i.toExponential(3)) // 指数计数法 
  Debug.Print("toPrecision i: " + i.toPrecision(1)) // 超过num位后采用指数计数法 
  Debug.Print("valueOf i: " + i.valueOf()) 
  Debug.Print("constructor i: " + i.constructor()) 
}

输出:

type i: object 3.1415926
toLocaleString i: 3.142
toFixed i: 3.142
toExponential i: 3.142e+0
toPrecision i: 3
valueOf i: 3.1415926
constructor i: 0

不使用new:

function testNumber() {
  var i = Number(3.1415926) 
  
  Debug.Print("type i: " + typeof(i) + " " + i.toString()) 
  Debug.Print("toLocaleString i: " + i.toLocaleString()) // 本地格式字符串 
  Debug.Print("toFixed i: " + i.toFixed(3)) // 四舍五入 
  Debug.Print("toExponential i: " + i.toExponential(3)) // 指数计数法 
  Debug.Print("toPrecision i: " + i.toPrecision(1)) // 超过num位后采用指数计数法 
  Debug.Print("valueOf i: " + i.valueOf()) 
  Debug.Print("constructor i: " + i.constructor()) 
}

输出:

type i: number 3.1415926
toLocaleString i: 3.142
toFixed i: 3.142
toExponential i: 3.142e+0
toPrecision i: 3
valueOf i: 3.1415926
constructor i: 0

2种方法都可以调用对象的方法和属性,没有发现什么不同之处!

在VBA里类可以自定义属性和方法,在js中也是一样,Number作为一种对象,也可以自定义属性和方法,使用起来也非常的简单方便:

function testNumberprototype() {   
  var i = new Number(3.1415926) 
  
  Debug.Print("i: " + i.toString()) 
  
  Number.prototype.double = function() { 
    return 2 * this 
  } 
  i = i.double() 
  Debug.Print("after double: "+ i.toString()) 
}

输出:

i: 3.1415926
after double: 6.2831852

另外Number的toString方法可以传入1个参数,按照进制来输出数字,非常的方便:

  i = 1000 
  Debug.Print(" 2进制" + i.toString(2)) 
  Debug.Print("16进制" + i.toString(16))

输出:

 2进制1111101000
16进制3e8
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-08-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 VBA 学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档