javascript 数据类型

本文深入解析JavaScript中的数据类型,包括基本类型如字符串、数字、布尔值等,以及引用类型如对象、数组和函数。详细介绍了各种类型的常见操作,如数字的四舍五入、字符串的拼接与替换,以及类型转换的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

javascript数据类型分为基本类型和引用类型。基本类型分为5种,string,number,boolean,null和undefined。

引用类型:对象(object),数组(Array),函数(Function)

基本类型是不可变的原始值,引用类型是可变的引用。

1)Number类型

常见操作:

Math.round(0.23) 四舍五入取整

Math.floor(0.23) 向下取整

Math.ceil(0.23) 向上取整

Math.min(4, 5) 返回最小值

Math.max(4, 5) 返回最大值

number.toFixed(n)保留n为小数

2)String类型

常见操作:

var s = ‘aaa’;

s.charAt(0); //a

s.indexOf(‘a’); //0

s.split(’a‘); //["", "", "", ""] 可以是正则表达式

s.replace(‘a’, ‘A’); //AAA

s.toUpperCase(); //AAA

s.concat(‘BBB’); //aaaBBB

提取字符串片段:

s.substring(start, stop ); //不允许负数

s.slice(start, end);

s.substr(start, lenth);

3)Null和Undefined

注意事项:

typeof null  --》object

typeof undefined –》undefined

null == undefined (true)

nul === undefined (false)

undefined 转换为数字是 NaN,null转换为数字是0

类型转换

1)原始值转换为对象:new String(),new Boolean(),new Number()

2)对象转换为原始值:toString(),valueOf()

举个例子:

image

这两个函数的使用情况:Every object has a [[DefaultValue]] property, which is computed on-demand. When asking for this property, the interpreter also provides a "hint" for what sort of value it expects. If the hint is String, then toString is used before valueOf. But, if the hint is Number, then valueOf will be used first. Note that if only one is present, or it returns a non-primitive, it will usually call the other as the second choice.

大致意思就是每个对象都有一个根据需求确定的默认值,如果隐式转换是number类型,则会优先调用valueOf函数,如果是string类型,则会调用toString方法。

image

image

3)字符串转换数字(parseInt,parseFloat)

var s = '111';
parseInt(s); //111

4)数字,布尔型转换为字符串(toString)

var num = 111;
num.toString(); //'111'
var numToString = num + ''; //'111'

5)字符串或数字转换为布尔值

var bool = !!num;

转载于:https://www.cnblogs.com/Candybunny/p/5456804.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值