《JS高级程序设计》之五

1、函数内部的特殊对象:arguments 和 this。arguments 的主要用途是保存函数参数,有一个callee 的属性,该属性是一个指针,指向拥有这个arguments 对象的函数。

例如:阶乘函数:

function factorial(num){
   if(num <= 1)  {
       return 1;
    }else{
       return num * arguments.callee(num-1);
}
}
    

 2、每个函数都包含两个属性:length和prototype。

  length属性表示函数希望接收的命名参数的个数。

3、每个函数都白喊两个非继承而来的方法:apply()和call(),apply()方法接收两个参数:一个是运行函数的作用域,另一个是参数数组。call() 方法与apply() 方法的不同之处是,第二个参数传递给函数的参数必须逐个列举出来。

function sum(num1 , num2){
  return num1+num2;
}

function callSum1(num1 , num2){
  return sum.apply(this , [num1 , num2]);
}

function callSum2(num1 , num2){
  return sum.call(this , num1 , num2);
}

4、toFixed() 方法会按照指定的小数位返回数值的字符串表示。

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

toExponential() 方法返回以指数表示法。

var num = 10;
alert(num.toExponential(1));  //"1.0e+1"

5、用于访问字符串中特定字符的方法是:charAt() 和 charCodeAt() ,charAt() 以单字字符串形式返回给定位置的那个字符。 charCodeAt()返回给定位置的字符的编码。

6、字符串操作方法

方法 var stringValue = "hello world"; 参数为正数     参数为负数  
stringValue.slice(3,7) "lo w" 不包括第二个参数位置处的字符 stringValue.slice(-3) stringValue.slice(8) -3+11 "rld"
stringValue.substring(3,7) "lo w" 同上 stringValue.substring(-3) stringValue.substring(0) 负数全变为0  "hello world"
stringValue.substr(3,7) "lo worl" 第二个参数表示要返回的字符的个数 stringValue.substr(-3,-4) stringValue.substr(8,0) 第一个参数加上长度变为正数,第二个参数变为0 "" 

7、查找子字符串位置的方法

indexOf() 从字符串的开头向后搜索子字符串,返回子字符串的位置
lastIndexOf() 从字符串的末尾向前搜索子字符串,返回子字符串的位置

8、trim() 会创建一个字符串的副本,删除前置及后缀的所有空格,然后返回结果。

9、看模式是否匹配的方法

方法 用法 举例
exec()

接收一个参数,即要应用模式的字符串,

返回包含第一个匹配项信息的数组

var text = "mom and daddy and baby";

var pattern1 = /mom( and daddy( and baby))/;

var matches = pattern1 .exec(text);

test()

接收一个字符串参数,模式与参数匹配

返回true,否则返回false

var text = "000-00-000";

var pattern = /d{3}-d{2}-d{4}/;

if(pattern.test(text )){

  alert("The pattern was matched");

}

match()

接收一个参数,要么是一个正则表达式,

要么是一个RegExp对象

var text = "cat , bat , sat , fat";

var pattern = /.at/;

var matches = text.match(pattern);

search() 同上

var text = "cat , bat , sat , fat";

var pos = text.search(/at/);

10、替换子字符串的操作:

var text = "cat , bat , sat , fat";
var result = text.replace("at","bond");   //第二个参数也可以是一个函数
alert(result);  //"cond , bond , song , fond"

 11、split() 方法可以基于指定的分隔符将一个字符串分割成多个字符串,并将结果放在一个数组找那个。

var colorText = "red , green , blue , yellow";
var colors1 = colorText .split("," , 3);    //第一个参数是分隔符,可以是字符串,也可以是RegExp对象,第二个参数用于指定数组的大小

 12、localeCompare() 方法,比较两个字符串,

var stringValue = "yellow";
alert(stringValue.localCompare("brick"));    //1,在字符串参数之后,返回1
alert(stringValue.localCompare("yellow"));    //0
alert(stringValue.localCompare("zoo"));    //-1,在字符串参数之前,返回-1

13、formCharCode() 方法,接收一或多个字符编码,然后将它们转换成一个字符串。

alert(String.formCharCode(104 , 101 , 108 , 108 , 111));  //"hello"

14、生成两个数之间的随机数

function selectFrom(lowerValue , upperValue){
    var choices =  upperValue - lowerValue +1;
    return Math.floor(Math.random() * choices + lowerValue) ;
}

 

原文地址:https://www.cnblogs.com/qducn/p/7535799.html