Javascript Good Part读书笔记-JavaScript方法
文章目录
方法(Methods)
数组(array)
- array.concat(item…)
通过浅拷贝产生一个新的数组,并添加item到这个数组。
1 2 3 4 |
var a = ['a', 'b', 'c']; var b = ['x', 'y', 'z']; var c = a.concat(b, true); // c is ['a', 'b', 'c', 'x', 'y', 'z', true] |
- array.join(separator)
生成一个字符串由separator
分割的字符串,默认分隔符是,
。
1 2 3 |
var a = ['a', 'b', 'c']; a.push('d'); var c = a.join(''); // c is 'abcd'; |
- array.pop()
删除并返回数组的最后一个元素,如果是空数组则返回 undefined
。
1 2 |
var a = ['a', 'b', 'c']; var c = a.pop(); // a is ['a', 'b'] & c is 'c' |
可实现为:
1 2 3 |
Array.method('pop', function () { return this.splice(this.length - 1, 1)[0]; }); |
- array.push(item…)
追加item到数组末尾,返回数组长度。
1 2 3 4 5 |
var a = ['a', 'b', 'c']; var b = ['x', 'y', 'z']; var c = a.push(b, true); // a is ['a', 'b', 'c', ['x', 'y', 'z'], true] // c is 5; |
可实现为:
1 2 3 4 5 |
Array.method('push', function () { this.splice.apply( this, [this.length,0].concat(Array.prototype.slice.apply(arguments))); return this.length; }); |
- array.reverse()
反转数组元素,返回一个数组。
1 2 3 |
var a = ['a', 'b', 'c']; var b = a.reverse(); // both a and b are ['c', 'b', 'a'] |
- array.shift()
删除数组的第一个元素并返回该元素,如果是空数组则返回undefined
。通常比pop
方法慢很多(需要进行元素移动)。
1 2 3 |
var a = ['a', 'b', 'c']; var c = a.shift(); // a is ['b', 'c'] & c is 'a' |
可实现为:
1 2 3 4 |
Array.method('shift', function () { return this.splice(0, 1)[0]; }); |
- array.slice(start, end)
数组一部的的浅拷贝
1 2 3 4 |
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*.splice(*start, deleteCount, item…)
从一个数组删除元素,并返回被删除的元素数组。如果有item参数,则从start位置替换/插入这些元素。
- start参数表示开始的位置
deleteCount表示从start开始删除元素的个数
1 2 3 4
var a = ['a', 'b', 'c']; var r = a.splice(1, 1, 'ache', 'bug'); // a is ['a', 'ache', 'bug', 'c'] // r is ['b']
array.sort(comparefn)
数组排序,默认假设数组是字符串。数字排序会出错。
1 2 3 |
var n = [4, 8, 15, 16, 23, 42]; n.sort( ); // n is [15, 16, 23, 4, 42, 8] |
数字排序
1 2 3 4 |
n.sort(function (a, b) { return a - b; }); // n is [4, 8, 15, 16, 23, 42]; |
数字,字符串混合排序
1 2 3 4 5 6 7 8 9 10 |
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'] |
对象单属性排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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 }; }; s.sort(by('first')).sort(by('last')); |
对象多属性排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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'))); |
- array.unshift(item…)
在数组开头添加item元素,返回数组的新长度。
1 2 3 |
var a = ['a', 'b', 'c']; var r = a.unshift('?', '@'); // a is ['?', '@', 'a', 'b', 'c'] // r is 5 |
可实现为:
1 2 3 4 5 |
Array.method('unshift', function () { this.splice.apply( this, [0, 0].concat(Array.prototype.slice.apply(arguments))); return this.length; }); |
### 函数(Function)
- function.apply(thisArg, argArray)
调用一个函数,传递this的对象绑定和一个可选的参数数组。
数字(Number)
- number.toExponential(fractionDigits)
转换数字到字符串,fractionDigits 0~20
1 2 3 4 5 6 7 8 |
document.writeln(Math.PI.toExponential(0)); document.writeln(Math.PI.toExponential(2)); document.writeln(Math.PI.toExponential(7)); document.writeln(Math.PI.toExponential(16)); document.writeln(Math.PI.toExponential( )); // Produces 3e+0 3.14e+0 3.1415927e+0 3.1415926535897930e+0 3.141592653589793e+0 |
- number.toFixed(fractionDigits)
转换数字到字符串,fractionDigits 0~20,默认0
1 2 3 4 5 6 7 8 |
document.writeln(Math.PI.toFixed(0)); document.writeln(Math.PI.toFixed(2)); document.writeln(Math.PI.toFixed(7)); document.writeln(Math.PI.toFixed(16)); document.writeln(Math.PI.toFixed()); // Produces 3 3.14 3.1415927 3.1415926535897930 3 |
- number*.toPrecision(*precision)
转换数字到字符串,precision 1~21
1 2 3 4 5 6 7 |
document.writeln(Math.PI.toPrecision(2)); document.writeln(Math.PI.toPrecision(7)); document.writeln(Math.PI.toPrecision(16)); document.writeln(Math.PI.toPrecision()); // Produces 3.1 3.141593 3.141592653589793 3.141592653589793 |
- number.toString(radix)
转换数字到字符串。
1 2 3 4 5 6 |
document.writeln(Math.PI.toString(2)); document.writeln(Math.PI.toString(8)); document.writeln(Math.PI.toString(16)); document.writeln(Math.PI.toString( )); // Produces 11.001001000011111101101010100010001000010110100011 3.1103755242102643 3.243f6a8885a3 3.141592653589793 |
对象(Object)
- object.hasOwnProperty(name)
如果对象包含属性名则返回true(不会在原型链上查找)
1 2 3 4 5 |
var a = {member: true}; var b = Object.create(a); var t = a.hasOwnProperty('member'); // t is true var u = b.hasOwnProperty('member'); // u is false var v = b.member; // v is true |
### 正则表达式(RegExp)
- regexp.exec(string)
如字符串成功匹配的正则表达式,则返回一个数组,数组的第0个元素为匹配的子字符串,从1开始依次为捕获的分组。如果匹配失败则返回null
- regexp.test(string)
测试字符串是否匹配正则表达式,如果匹配则返回true
,否则返回false
。不要使用g
标记
1
|
var b = /&.+;/.test('frank beans'); // b is true |
1 2 3 |
RegExp.method('test', function (string) { return this.exec(string) !== null; }); |
### 字符串(String) * string.charAt(pos)
1 2 |
var name = 'Curly'; var initial = name.charAt(0); // initial is 'C' |
1 2 3 |
String.method('charAt', function (pos) { return this.slice(pos, pos + 1); }); |
string.charCodeAt(pos)
1 2
var name = 'Curly'; var initial = name.charCodeAt(0); // initial is 67
string.concat(string…)
1
var s = 'C'.concat('a', 't'); // s is 'Cat'
string.indexOf(searchString, position)
1 2 3 4
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)
1 2 3 4
var text = 'Mississippi'; var p = text.lastIndexOf('ss'); // p is 5 p = text.lastIndexOf('ss', 3); // p is 2 p = text.lastIndexOf('ss', 6); // p is 5
string.localeCompare(that)
1 2 3 4 5 6
var m = ['AAA', 'A', 'aa', 'a', 'Aa', 'aaa']; m.sort(function (a, b) { return a.localeCompare(b); }); // m (in some locale) is // ['a', 'A', 'aa', 'Aa', 'aaa', 'AAA']
string.match(regexp)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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) { document.writeln(('// [' + i + '] ' + a[i]).entityify()); } // The result is // [0] <html> // [1] <body bgcolor=linen> // [2] <p> // [3] This is // [4] // [5] bold // [6] // [7] ! // [8] </p> // [9] </body> // [10] </html>
string.replace(searchValue, replaceValue)
1
var result = "mother_in_law".replace('_', '-');
var oldareacode = /((\d{3}))/g; var p = ‘(555)666-1212’.replace(oldareacode, ‘$1-’); // p is ‘555-666-1212’
1 2 3 4 5 6 7 8 9 |
符号替换 | Dollar sequence | Replacement | | --------------- | -------------- | | $$ | $ | | $& | 匹配的文本 | | $number | 获取的分组文本 | | $` | 匹配之前的文本 | | $' | 匹配之后的文本 | |
String.method(‘entityify’, function () { var character = { ‘<’ : “, ‘>’ : “, ‘&’ : “, ‘“’ : “ }; // Return the string.entityify method, which // returns the result of calling the replace method. // Its replaceValue function returns the result of // looking a character up in an object. This use of // an object usually outperforms switch statements. return function () { return this.replace(/[<>&“]/g, function © { return character[c]; }); }; }()); alert(”<&>“.entityify()); // <&>
1
|
* string.search(regexp) |
var text = ‘and in it he says “Any damn fool could’; var pos = text.search(/[“‘]/); // pos is 18
1
|
* string.slice(start, end) |
var text = ‘and in it he says “Any damn fool could’; var a = text.slice(18); // a is ‘“Any damn fool could’ var b = text.slice(0, 3); // b is ‘and’ var c = text.slice(-5); // c is ‘could’ var d = text.slice(19, 32); // d is ‘Any damn fool’
1
|
* string.split(separator, limit) |
var digits = ‘0123456789’; var a = digits.split(“, 5); // a is [‘0’, ‘1’, ‘2’, ‘3’, ‘4’]
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’, “]
ar 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’ // ]
var f = ‘|a|b|c|’.split(/|/); // f is [‘a’, ‘b’, ‘c’] on some systems, and // f is [“, ‘a’, ‘b’, ‘c’, “] on others
1 2 3 4 5 6 7 8 9 10 11 |
* string.substring(start, end) * string.toLocaleLowerCase( ) * string.toLocaleUpperCase( ) * string.toLowerCase( ) * string.toUpperCase( ) * String.fromCharCode(char...) |
var a = String.fromCharCode(67, 97, 116); // a is ‘Cat’
1
|
|
文章作者 binbin wen
上次更新 2019-11-02