JavaScript语言精粹 笔记06 方法

JS包含了少量可用在标准类型上的标准方法。

Array
Function
Number
Object
RegExp
String

Array

array.concat(item...)

concat方法返回一个新数组,它包含array的浅复制并将1个或多个参数item附加在其后。如果参数item是一个数组,那么他的每个元素会被本别添加。

var a = ['a', 'b', 'c'];
var b = ['x', 'y', 'z'];
var c = a.concat(b, true);
// c 是 ['a', 'b', 'c', 'x', 'y', 'z', true]

 array的浅复制:

var p1={"name":"person1"};
var p2={"name":"person2"}; 
var arr=[p1];
var arr2=arr.concat(p2);
console.log(arr2[1].name);//person2
p2.name="person";
console.log(arr2[1].name);//person

array.join(separator)

join方法把array构造成一个字符串。

var a = ['a', 'b', 'c'];
a.push('d');
var c = a.join('');    // 'abcd';

array.pop()

pop和push使数组array像堆栈一样工作。如果array是空,pop会返回undefined。

var a = ['a', 'b', 'c'];
var c = a.pop(  );    // a 是 ['a', 'b'] & c 是 'c'

pop可以这样实现:

Array.prototype.pop=function(){
    return this.splice(this.length - 1, 1)[0];
}

array.push(item...)

var a = ['a', 'b', 'c'];
var b = ['x', 'y', 'z'];
var c = a.push(b, true);
// a 是 ['a', 'b', 'c', ['x', 'y', 'z'], true]
// c 是 5;

array.reverse()

var a = ['a', 'b', 'c'];
var b = a.reverse(  );
//a和b都是 ['c', 'b', 'a']

array.shift()

移除数组中的第一个元素并返回该元素。如果数组array是空,它会返回undefined。shift通常比pop慢得多。

var a = ['a', 'b', 'c'];
var c = a.shift(  );    // a 是 ['b', 'c'] & c 是 'a'

shift可以这样实现:

Array.prototype.pop=function(){
    return this.splice(0, 1)[0];
}

array.slice(start,end)

slice方法对array中的一段做浅复制,从array[start]复制到array[end-1],end参数可选,默认为数组长度。不要和splice方法混淆。

var a = ['a', 'b', 'c'];
var b = a.slice(0, 1);    // b is ['a']
var c = a.slice(1);       // c is ['b', 'c']
var d = a.slice(1, 2);    // d is ['b']

array.sort(comparefn)

JS默认比较函数假定所有要排序的元素都是字符串。

var n = [4, 8, 15, 16, 23, 42];
n.sort(  );
// n is [15, 16, 23, 4, 42, 8]

可以自定义比较函数来代替默认的比较函数。比较函数包含2个参数,相等返回0,如果参数1 应该排在前则返回一个负数,如果参数2 应该排在前则返回一个正数。

n.sort(function (a, b) {
    return a - b;
});
// n is [4, 8, 15, 16, 23, 42];
var m = ['aa', 'bb', 'a', 4, 8, 15, 16, 23, 42];
m.sort(function (a, b) {
    if (a === b) {
        return 0;
    }
    if (typeof a === typeof b) {
        return a < b ? -1 : 1;
    }
    return typeof a < typeof b ? -1 : 1;
});
// m is [4, 8, 15, 16, 23, 42, 'a', 'aa', 'bb']

为对象数组排序:

var by = function (name) {
    return function (o, p) {
        var a, b;
        if (typeof o === 'object' && typeof p === 'object' && o && p) {
            a = o[name];
            b = p[name];
            if (a === b) {
                return 0;
            }
            if (typeof a === typeof b) {
                return a < b ? -1 : 1;
            }
            return typeof a < typeof b ? -1 : 1;
        } else {
            throw {
                name: 'Error',
                message: 'Expected an object when sorting by ' + name
            };
        }
    };
};

var s = [
    {first: 'Joe',   last: 'Besser'},
    {first: 'Moe',   last: 'Howard'},
    {first: 'Joe',   last: 'DeRita'},
    {first: 'Shemp', last: 'Howard'},
    {first: 'Larry', last: 'Fine'},
    {first: 'Curly', last: 'Howard'}
];
s.sort(by('first'));    // s is [
//    {first: 'Curly', last: 'Howard'},
//    {first: 'Joe',   last: 'DeRita'},
//    {first: 'Joe',   last: 'Besser'},
//    {first: 'Larry', last: 'Fine'},
//    {first: 'Moe',   last: 'Howard'},
//    {first: 'Shemp', last: 'Howard'}
// ]
    

sort方法不稳定,s.sort(by('first')).sort(by('last'));不能产生我们希望的顺序。要修改by函数:

var by = function (name, minor) {
    return function (o, p) {
        var a, b;
        if (o && p && typeof o === 'object' && typeof p === 'object') {
            a = o[name];
            b = p[name];
            if (a === b) {
                return typeof minor === 'function' ? minor(o, p) : 0;
            }
            if (typeof a === typeof b) {
                return a < b ? -1 : 1;
            }
            return typeof a < typeof b ? -1 : 1;
        } else {
            throw {
                name: 'Error',
                message: 'Expected an object when sorting by ' + name
            };
        }
    };
};

s.sort(by('last', by('first')));    // s is [
//    {first: 'Joe',   last: 'Besser'},
//    {first: 'Joe',   last: 'DeRita'},
//    {first: 'Larry', last: 'Fine'},
//    {first: 'Curly', last: 'Howard'},
//    {first: 'Moe',   last: 'Howard'},
//    {first: 'Shemp', last: 'Howard'}
// ]

array.splice(start,deleteCount,item...)

从array中移除1个或多个元素,并用性的item替换它们。

var a = ['a', 'b', 'c'];
var r = a.splice(1, 1, 'ache', 'bug');
// a is ['a', 'ache', 'bug', 'c']
// r is ['b']

array.unshift(item...)

unshift类似于push,但是它是把item插入到array的开始部分,它返回array的新长度。

var a = ['a', 'b', 'c'];
var r = a.unshift('?', '@');
// a is ['?', '@', 'a', 'b', 'c']
// r is 5

Function

function.apply(thisArg,argArray)

apply方法调用函数function,传递一个被绑定到this上的对象和一个可选的参数数组。

obj:这个对象将代替function类里this对象
args:这个是数组,它将作为参数传给function(args-->arguments)

var Person=function(name,age){
    this.name=name;
    this.age=age;
    this.sayHi=function(){alert("Hi! My name is "+this.name+", I'm "+this.age)};
}

var Student=function(name,age,grade){
    Person.apply(this,arguments);//apply使Student类具备了Person类的全部方法和属性
    this.grade=grade;
}

var p1=new Person("Jesse",18);
p1.sayHi();//Hi! My name is Jesse, I'm 18.
var s1=new Student("Lily",10,5);
s1.sayHi();//Hi! My name is Lily, I'm 10.

可以利用apply的参数数组来简化程序:

例如

求数组中的最大值

var arr=[1,3,2];
//一般方法
var m=arr[0];
for(var i=1;i<arr.length;i++){
    m=Math.max(max,arr[i]);
}
alert(m);
//利用apply
m=Math.max.apply(null,arr);
alert(m);

Number

number.toExponential(fractionDigits)

toExponential方法把number转换成一个指数形式的字符串。可选参数fractionDigits控制小数点后的位数。

console.log(Math.PI.toExponential(0));//3e+0
console.log(Math.PI.toExponential(2));//3.14e+0
console.log(Math.PI.toExponential(7));//3.1415927e+0
console.log(Math.PI.toExponential(16));//3.1415926535897931e+0
console.log(Math.PI.toExponential());//3.141592653589793e+0

member.toFixed(fractionDigits)

toFixed方法把number转换成一个十进制形式的字符串。可选参数fractionDigits控制小数点位数。

console.log(Math.PI.toFixed(0));//3
console.log(Math.PI.toFixed(2));//3.14
console.log(Math.PI.toFixed(7));//3.1415927
console.log(Math.PI.toFixed(16));//3.1415926535897931
console.log(Math.PI.toFixed());//3

member.toPrecision(precision)

toPrecision方法把number转换成一个十进制形式的字符串。可选参数precision控制数字的位数。

console.log(Math.PI.toPrecision(2));//3.1
console.log(Math.PI.toPrecision(7));//3.141593
console.log(Math.PI.toPrecision(16));//3.141592653589793
console.log(Math.PI.toPrecision());//3.141592653589793

numbe.toString(radix)

toSting方法把number转换成一个字符串。可选参数radix控制基数,默认为10。radix参数最常用的是整数,但是他可以用任意数字。

console.log(Math.PI.toString(2));//11.001001000011111101101010100010001000010110100011
console.log(Math.PI.toString(8));//3.1103755242102643
console.log(Math.PI.toString(16));//3.243f6a8885a3
console.log(Math.PI.toString());//3.141592653589793

Object

object.hasOwnProperty(name)

如果object包含一个name属性,那么hasOwnProperty方法返回true。原型链中的同名属性是不会被检查的。

var a={memeber:true};
console.log(a.hasOwnProperty("memeber"));//true

RegExp

regexp.exec(string)

如果它成功匹配regexp和字符串string,它会返回一个数组。数组中下标为0的元素包含正则表达式regexp匹配的子字符串。下标为1的元素是分组1捕获的文本,下标为2的元素是分组2捕获的文本,依此类推。如果匹配失败则返回null。

如果regexp带有一个g标志(全局标志),事情变得更加复杂了。查找不是从字符串的起始位置开始,而是从regexp.lastIndex( 初始值为0 )位置开始。如果匹配成功,那么regexp.lastIndex将被设置为该匹配后第一个字符的位置。不成功的匹配会重置regexp.lastIndex为0。

你可以通过循环调用exec去查询一个匹配模式在一个字符串中发生几次。要注意:如果你提前退出了循环,在次进入这个循环前必须把regexp的lastIndex重置为0。^因子也仅匹配regex.lastIndex为0的情况。

// 把一个简单的HTML文本分解为标签和文本
var text = '<html><body bgcolor=linen><p>' +'This is <b>bold</b>!</p></body></html>';
var tags = /[^<>]+|<(/?)([A-Za-z]+)([^<>]*)>/g;
var a, i;

while ((a = tags.exec(text))) {
    for (i = 0; i < a.length; i += 1) {
        console.log('// [' + i + '] ' + a[i]);
    }
    console.log(  );
}

// 结果:

// [0] <html>
// [1]
// [2] html
// [3]

// [0] <body bgcolor=linen>
// [1]
// [2] body
// [3]  bgcolor=linen

// [0] <p>
// [1]
// [2] p
// [3]

// [0] This is
// [1] undefined
// [2] undefined
// [3] undefined

// [0] <b>
// [1]
// [2] b
// [3]

// [0] bold
// [1] undefined
// [2] undefined
// [3] undefined

// [0] </b>
// [1] /
// [2] b
// [3]

// [0] !
// [1] undefined
// [2] undefined
// [3] undefined

// [0] </p>
// [1] /
// [2] p
// [3]

// [0] </body>
// [1] /
// [2] body
// [3]

// [0] </html>
// [1] /
// [2] html
// [3]

regex.test(string)

var b = /&.+;/.test('frank &amp; beans');
// b is true

String

string.charAt(pos)

返回string中pos位置的字符。

var name='Curly';
var c0=name.charAt(0);
console.log(c0);//C

var c1=name.charAt(-1);
console.log(c1);//空字符串
console.log(c1.length);//0

var c2=name.charAt(10);
console.log(c2
);//空字符串

string charCodeAt(pos)

返回一个以整数形式表示的在string中的pos位置上的字符码位。

var name='Curly';
var c0=name.charCodeAt(0);
console.log(c0);//67

var c1=name.charCodeAt(-1);
console.log(c1);//NaN

var c2=name.charCodeAt(10);
console.log(c2);//NaN

string.concat(string...)

var s = 'C'.concat('a', 't');    // s is 'Cat'

string.indexOf(searchString,position)

从string的postion(可选,默认为0)位置开始查找字符串searchString,如果找到返回第一个匹配字符的位置,否则返回-1。

var text = 'Mississippi';
var p = text.indexOf('ss');    // p is 2
p = text.indexOf('ss', 3);     // p is 5
p = text.indexOf('ss', 6);     // p is -1

string.lastIndexOf(searchString,position)

var text = 'Mississippi';
var p = text.lastIndexOf('ss');    //从字符串末尾向前找 p is 5
p = text.lastIndexOf('ss', 3);     //从字符串位置3处向前找 p is 2
p = text.lastIndexOf('ss', 6);     //从字符串位置6处向前找 p is 5
p = text.lastIndexOf('ss', -2);     // p is -1
p = text.lastIndexOf('ss', 20);     //20大于字符串长度,从字符串末尾向前找 p is 5

string.localCompare(this)

该函数采用底层操作系统提供的排序规则进行比较。

var m = ['AAA', 'A', 'aa', 'a', 'Aa', 'aaa'];
m.sort(function (a, b) {
    return a.localeCompare(b);//a<b结果为负,相等为0,a>b为正
});

// 在某些本地环境下 m 为['a', 'A', 'aa', 'Aa', 'aaa', 'AAA']

string.match(regexp)

如果没有g标识,调用string.match(regexp)的结果与string.exec(regexp)的结果相同,如果regexp有g标识,那么它返回一个包含除捕获分组之外的所有匹配的数组。

var text = '<html><body bgcolor=linen><p>' +
        'This is <b>bold</b>!</p></body></html>';
var tags = /[^<>]+|<(/?)([A-Za-z]+)([^<>]*)>/g;
var a, i;

a = text.match(tags);
for (i = 0; i < a.length; i += 1) {
    console.log('// [' + i + '] ' + a[i]);
}

// 结果

// [0] <html>
// [1] <body bgcolor=linen>
// [2] <p>
// [3] This is
// [4] <b>
// [5] bold
// [6] </b>
// [7] !
// [8] </p>
// [9] </body>
// [10] </html>

string.replace(regexp/substr,replacement)

参数regexp/substr规定子字符串或要替换的模式的 RegExp 对象。如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。 replacement规定了替换文本或生成替换文本的函数。replace方法返回一个新的字符串。

它将在 string 中查找与 regexp 相匹配的子字符串,然后用 replacement 来替换这些子串。如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。

replacement 可以是字符串,也可以是函数。如果它是字符串,那么每个匹配都将由字符串替换。但是 replacement 中的 $ 字符具有特定的含义。如下表所示,它说明从模式匹配得到的字符串将用于替换。

字符 替换文本

$1、$2、...、$99

与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。

$&

与 regexp 相匹配的子串。

$`

位于匹配子串左侧的文本。

$'

位于匹配子串右侧的文本。

$$

直接量符号。

示例代码:

var str="Visit Microsoft!".replace("Microsoft", "Windows");//Visit Windows!

 执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "W3School":

var str="Welcome to Microsoft! "
+ "We are proud to announce that Microsoft has "
+ "one of the largest Web Developers sites in the world."

var str=str.replace(/Microsoft/g, "W3School");
//"Welcome to W3School! We are proud to announce that W3School has one of the largest Web Developers sites in the world."

 确保匹配字符串大写字符的正确:

text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");

把 "Doe, John" 转换为 "John Doe" 的形式:

name = "Doe, John";
name =name.replace(/(w+)s*,s*(w+)/, "$2 $1");//John Doe

把字符串中所有单词的首字母都转换为大写:

name = 'aaa bbb ccc';
uw=name.replace(/w+/g, function(word){
  return word.substring(0,1).toUpperCase()+word.substring(1);}
  //"Aaa Bbb Ccc"
  );

以上关于replace的内容来自于W3School

string.search(regexp)

类似于indexOf,如果找到返回第一个匹配的首字符位置。找不到则返回-1,此方法会忽略掉g标识。

var text = 'and in it he says "Any damn fool could';
var pos = text.search(/["']/);    // pos is 18

string.slice(start,end)

复制string中的一部分来构造一个新的字符串,从string的start位置到end-1位置。

var str='0123456789';
var s1=str.slice(1);//123456789
var s2=str.slice(9);//9
var s3=str.slice(2,5);//234
var s4=str.slice(5,2);//空字符串
var s5=str.slice(10);//空字符串

string.split(separator,limit)

把string依据separator分割成limit段,limit可选。separator可以是一个值字符串或者正则表达式。

var digits = '012345';
var a = digits.split('', 5);
// a is ['0', '1', '2', '3', '4']
var b = digits.split('');
// b is ['0', '1', '2', '3', '4','5']
var ip = '192.168.1.0';
var b = ip.split('.');
// b is ['192', '168', '1', '0']

var c = '|a|b|c|'.split('|');
// c is ['', 'a', 'b', 'c', '']

var text = 'last,  first ,middle';
var d = text.split(/s*,s*/);
// d is [
//    'last',
//    'first',
//    'middle'
// ]

注意,来自分组捕获的文本将会被包含在分割后的数组中:

var e = text.split(/s*(,)s*/);
// e is [
//    'last',
//    ',',
//    'first',
//    ',',
//    'middle'
// ]

当separator是一个正则表达式时,有一些JS的实现在输出数组中会禁止空字符串:

var f = '|a|b|c|'.split(/|/);
//一些系统中 f is ['a', 'b', 'c'] 
//另外一些系统中 f is ['', 'a', 'b', 'c', ''] 

string.substring(start,end)

用法同slice。与 slice不同的是,substring 不接受负的参数。建议用slice代替它。

string.toLowerCase()

返回一个新的字符串,把string中的字母都转成小写。

string.toUpperCase()

返回一个新的字符串,把string中的字母都转成小写。

String.fromCharCode(char...)

从一串数字中返回一个字符串。

var a = String.fromCharCode(67, 97, 116);
// a is 'Cat'

参考:《JavaScript语言精粹》Douglas Crockford著    赵泽欣 鄢学鹍 译

转载请注明出处:

作者:JesseLZJ
出处:http://jesselzj.cnblogs.com

原文地址:https://www.cnblogs.com/jesselzj/p/4793431.html