zoukankan      html  css  js  c++  java
  • javascript 数据类型

    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;
  • 相关阅读:
    git命令
    svg学习系列02-简单的svg图形和线条
    svg学习系列01-svg简介
    jQuery分页插件
    svg简介
    css3选择器
    sublime使用
    HTML5新特性
    html新的语义化标签和表单控件
    DOM详解
  • 原文地址:https://www.cnblogs.com/Candybunny/p/5456804.html
Copyright © 2011-2022 走看看