zoukankan      html  css  js  c++  java
  • 基本包装类型

    基本包装类型

    引用类型与基本包装类型的主要区别就是对象的生存期。

    var s1=new String ('some text');
    

    使用new操作符创建的引用类型的实例,在执行流离开当前作用域之前都一直保存在内存中。而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁。

    var s1 ="some text";
    s1.color='red';
    alert(s1.color);//undefined
    

    number类型

    var num=10;
    alert(num.toFixed(2));//"10.00"
    

    string类型

    1、字符方法

    var stringObject=new String('hello world');
    alert(stringValue.charAt(1));//e;
    

    2、字符串操作方法

    var stringValue='hello';
    var result=stringValue.concat('world','!');
    alert(result);//"hello world!";
    

    虽然concat()是专门用来拼接字符串的方法,但实践中使用更多的还是加号操作符(+)。

    另外三个基于自字符串创建新字符串的方法:slice()、substr()和substring()。具体来说,slice()和substring()的第二个参数指定的是子字符串最后一个字符后面的位置。而substr()的第二个参数指定的是返回的字符个数。如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。

    在传递的参数是负值的情况下,它们的行为就不尽相同。slice()会将传入的负值与字符串的长度相加,substr()方法将负的第一个参数加上字符串的长度,而将负的第二个参数转化为0.最后,substring()会把所有负值都转化为0.

    var stringValue='hello world';
    alert(stringValue.splice(-3));//'rld';
    alert(stringValue.substring(-3));//'hello world';
    alert(stringValue.substr(-3));//'rld';
    

    3、字符串位置方法

    indexOf()和lastIndexOf(),这两个方法都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置(如果没有找到,则返回-1).

    var stringValue='hello world';
    alert(stringValue.indexOf('o'));//4
    alert(stringValue.lastIndexOf('o'));//7
    

    当接收可选的第二个参数时,表示从字符串中的哪个位置开始搜索,忽略该位置之前的所有字符。

    var string="lorem ipsum dolor sit amet";
    var positions= new Array();
    var pos=string.indexOf('e');
    
    while(pos>-1){
    	positions.push(pos);
    	pos=string.indexOf('e',pos+1);
    }
    console.log(positions);//"3,24"
    

    4、trim()方法

    var stringValue="   hello world  ";
    var trim=stringValue.trim();
    alert(trim);//"hello world"
    努力将自己的温暖带给身边的人!!!!!
  • 相关阅读:
    BeautifulSoup中的select方法
    BeautifulSoup中的find,find_all
    python中sys.stdout、sys.stdin
    python sort、sorted
    Numpy常用操作
    pandas (loc、iloc、ix)的区别
    小波变化库——Pywalvets学习笔记
    python filter()函数
    Redis数据库总结
    高逼格企业级MySQL数据库备份方案,原来是这样....
  • 原文地址:https://www.cnblogs.com/xiaoli52qd/p/6286905.html
Copyright © 2011-2022 走看看