写在前面:由于自身英语水平有限,所以翻译不敢保证能让所有人都理解,如果您在阅读中发现什么疑问,请务必及时查看官方API,以免误导。另外,有部分是未经翻译的,一方面是因为找不到合适的中文描述之,还有就是有的地方看英文更易懂~
这一篇是Types第一篇——Array、String,即MooTools1.3.1里对js原生类型的扩展
归纳以下,Array、String方法如下:
Array | Array.each:用于循环遍历数组或伪数组(如getElementsByTagName返回的结果或arguments) Array.clone:返回传入数组的一个副本 Array.from:转换传入的(已经定义过且不是数组的)参数为一个数组 each:数组中的每一个元素调用一个函数 invoke:将一个指定的方法运用到数组上并返回处理后的数组 every:如果每一个条目都满足传入的测试函数,则返回true,这个方法只有在不支持Array:every方法的浏览器中才有效 filter:以新数组的形式过滤返回能够让传入的测试函数返回true的元素,此方法只在不支持Array:filter方法的浏览器中有效 clean:清除数组中为null或undefined的项,并返回一个新数组 indexOf:返回第一个与所提供值相同的数组项,如果不存在则返回-1 map:在数组的每一个元素上调用一个提供的函数,结果作为一个数组返回 some:在至少有一个元素满足传入数组的测试函数时返回true associate:Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array link:接受一个具有名称/function对的对象用于分配数组的值 contains:测试某个数组是否含有某个条目 append:把传入的数组附加到当前数组末尾 getLast:返回数组最后一个条目(item) getRandom:返回数组中的一个随机项 include:(数组没有出现过相同的元素时)把传入的元素push到数组里面(区分大小写和类型) combine:当前数组与传入的数组合并,不出现重复的项目,区分大小写、类型 erase:移除数组中重复出现的项 empty:清空数组项 flatten:展开多维数组到一个一维数组中,返回这个新数组 pick:返回传入数组的第一个有定义的值,或null hexToRgb:十六进制颜色值转换为rgb值 rgbToHex:颜色的rgb值转换为十六进制值 |
---|---|
String | String.from:把传入的参数转换成为字符串 String.uniqueID:生成一个唯一的id test:使用字符串和正则表达式获取匹配 contains:检查传入的字符串是否包含在当前字符串中 trim:清除字符串开头和末尾的空白符 clean:清除无关系的空白符 camelCase:把带有连字符号的字符串转换成驼峰式 hyphenate:与camelCase方法相反 capitalize:单词的首字母大写 escapeRegExp:转义正则表达式的特殊字符 toInt:转换字符串并根据指定的基数返回number值 toFloat:把字符串转换成浮点值 hexToRgb:十六进制的字符串转换为rgb值 rgbToHex:rgb字符串转换成十六进制颜色值 substitute:使用一个传入的对象或数组替换字符串关键字,移除未定义的关键字并忽略不匹配的关键字 stripScripts:把字符串内的标签剥离字符串(从字符串中去除) |
//Type: Array
//Array类型的一些方法和函数的集合
Function: Array.each
用于循环遍历数组或伪数组(如getElementsByTagName返回的结果或arguments)
Array.each(iterable, fn[, bind]);
参数:
iterable - (array) 需要循环访问(遍历迭代)的数组
fn - (function) 用于每一个元素测试的函数
bind - (object, optional) 函数里的'this'所指向的对象
其中fn参数语法:fn(item, index, object)
item - (mixed) 数组中当前条目
index - (number) 当前条目的索引,如果是对象的情况下,传入的是条目的key而不是索引
object - (mixed) The actual array/object
Array.each(['Sun', 'Mon', 'Tue'], function(day, index) {
console.log('name: ' + day + ' , ' + 'index: ' + index);
})
Function: Array.clone
返回传入数组的一个副本
var clone = Array.clone(myArray);
var colors = ['red', 'green', 'blue'];
var copy = Array.clone(colors);
colors[0] = 'orange';
console.log(copy);//["red", "green", "blue"]
Function: Array.from
转换传入的(已经定义过且不是数组的)参数为一个数组
var splatted = Array.from(obj);
参数:obj - (mixed) 任何类型的变量
返回:(array) 如果传入的参数是一个数组,则返回这个数组,否则返回一个以被传入的变量为唯一元素的数组
console.log(Array.from('string!'));//['string!']
console.log(Array.from([1,2,3]));//[1,2,3]
Array method: each
数组中的每一个元素调用一个函数
myArray.each(fn[, bind]);
参数:
fn - (function) 在数组中每一个条目都会执行的函数
bind - (object, optional) 指定在函数中将作为'this'来使用的对象
fn语法:fn(item, index, array)
item - (mixed) The current item in the array.
index - (number) The current item's index in the array.
array - (array) The actual array.
[1,2,3].each(function(item, index) {
console.log(item*index);//0,2,6
});
说明:此方法只有在不支持本地化的Array:forEach方法的浏览器里可用
Array method: invoke
将一个指定的方法运用到数组上并返回处理后的数组
var arr = myArray.invoke(method[, arg, arg, arg ...])
参数:
method - (string) 将要运用到数组的每一个项目上的方法
arg - (mixed) 需要给方法传入的参数
返回:(array) 运用了这个方法之后以数组的形式返回结果
console.log([4,7,10,25,16,40,35].invoke('limit', 10, 30));//[10, 10, 10, 25, 16, 30, 30]
console.log([0,false,'string'].invoke('limit', 10, 20));// throws an error!
说明:被调用的方法应该是数组的每个项目都有的方法,如果方法不存在,则抛出错误
Array method: every
如果每一个条目都满足传入的测试函数,则返回true,这个方法只有在不支持Array:every方法的浏览器中才有效
var allPassed = myArray.every(fn[, bind]);
alert([10,20,30].every(function(item, index) {return item > 20;}));//false
Array method: filter
以新数组的形式过滤返回能够让传入的测试函数返回true的元素,此方法只在不支持Array:filter方法的浏览器中有效
var filteredArray = myArray.filter(fn[, bind]);
var arr = [10,20,30,40].filter(function(item, index) {
return item >= 20;
});
console.log(arr);//[20, 30, 40]
Array method: clean
清除数组中为null或undefined的项,并返回一个新数组
var cleanedArray = myArray.clean();
console.log([null, '', 1, 0, undefined, 2, false, true].clean());//["", 1, 0, 2, false, true]
Array method: indexOf
返回第一个与所提供值相同的数组项,如果不存在则返回-1,这个方法只在不支持Array:indexOf的浏览器中可用
var index = myArray.indexOf(item[, from]);
参数:
item - (object) 提供的用于在数组中查找的条目
from - (number, optional: 默认是 0) 查询开始的索引
['apple', 'lemon', 'banana'].indexOf('lemon'); // returns 1
['apple', 'lemon'].indexOf('banana'); // returns -1
Array method: map
在数组的每一个元素上调用一个提供的函数,结果作为一个数组返回,此方法只在不支持Array:map的浏览器可用
var mappedArray = myArray.map(fn[, bind]);
console.log([2,4,6].map(function(item, index) {return item * 2;}));//[4, 8, 12]
Array method: some
在至少有一个元素满足传入数组的测试函数时返回true,此法只在浏览器不支持本地化(native)Array:some方法时可用
var somePassed = myArray.some(fn[, bind]);
console.log([1,4,7,9].some(function(item, index) {return item > 5;}));//true
Array method: associate
Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array
var associated = myArray.associate(obj);
参数:obj - (array) 数组元素将在新创建的对象中被用作key的数组
返回:(object) 新关联的对象
var en = ['one', 'two', 'three'];
var num = [1, 2, 3];
console.log(num.associate(en));//{one=1, two=2, three=3}
Array method: link
接受一个具有名称/function对的对象用于分配数组的值
var result = myArray.link(object);
参数:object - (object) 传入一个具有名称/function对的对象,作为名值对匹配的模板
返回:(object) 新关联的对象
var el = new Element('div');
var arr = [10, 'string', el, false, {foo: 'foo'}];
var newArr = arr.link({
object: Type.isObject,
element: Type.isElement,
number: Type.isNumber,
string: Type.isString,
myBoolean: function(o) {return o != null;}
});
console.log(newArr);//{number:10, string:'string', element: el, myBoolean: false, object: {foo: 'foo'}}
Array method: contains
测试某个数组是否含有某个条目
var inArray = myArray.contains(item[, from]);
console.log(['a','b','c','d'].contains('b'));//true
console.log(['a','b','c','d'].contains('b', 2));//false
Array method: append
把传入的数组附加到当前数组末尾
var myArray = myArray.append(otherArray);
返回:(array)原数组但包含传入的数组的值
var colors = ['red', 'yellow', 'blue'];
console.log(colors.append(['green', 'maroon']));//["red", "yellow", "blue", "green", "maroon"]
Array method: getLast
返回数组最后一个条目(item)
myArray.getLast();
console.log(['a', 'b', 'c'].getLast());//'c'
console.log([].getLast());//null
Array method: getRandom
返回数组中的一个随机项
myArray.getRandom();
['Cow', 'Pig', 'Dog', 'Cat'].getRandom(); // returns one of the items
Array method: include
(数组没有出现过相同的元素时)把传入的元素push到数组里面(区分大小写和类型)
myArray.include(item);
参数:item - (object) 想要添加到数组中的条目
返回:(array) 添加新条目后的数组
console.log(['red', 'Blue', 'green'].include(['blue', 'yellow']));//["red", "Blue", "green", ["blue", "yellow"]]
console.log(['red', 'Blue', 'green'].include('blue'));//['red', 'Blue', 'green', 'blue']
console.log(['red', 'Blue', 'green'].include('Blue'));//['red', 'Blue', 'green']
说明:如果要添加一个已经存在的item到数组里,可以使用数组的push方法
Array method: combine
当前数组与传入的数组合并,不出现重复的项目,区分大小写、类型
myArray.combine(array);
console.log(['red', 'Blue', 'green'].combine(['blue', 'yellow', 'Blue', false]));
//["red", "Blue", "green", "blue", "yellow", false]
Array method: erase
移除数组中重复出现的项
myArray.erase(item);
console.log(['a', 'b', 'c', 'd', 'c'].erase('c'));//['a', 'b', 'd']
console.log(['a', 'b', 'c', 'd', 'c'].erase('e'));//['a', 'b', 'c', 'd', 'c']
Array method: empty
清空数组项
myArray.empty();
console.log(['a', 1, true].empty());//[]
Array method: flatten
展开多维数组到一个一维数组中,返回这个新数组
myArray.flatten();
console.log([1,2,3,[4,5,6,7],[[[8],9],5]].flatten());//[1, 2, 3, 4, 5, 6, 7, 8, 9, 5]
Array method: pick
返回传入数组的第一个有定义的值,或null
var picked = [var1, var2, var3].pick();
function say(msg, err) {
return [err, msg, 'There was no message supplied.'].pick();
}
console.log(say());//There was no message supplied.
console.log(say('message!'));//message!
console.log(say('message!', 'Err message!'));//Err message!
Array method: hexToRgb
十六进制颜色值转换为rgb值
myArray.hexToRgb([array]);
参数:array - (boolean, optional) 如果传入true, 将返回rgb值的一个数组(如[255, 51, 0])而非字符串(如"rgb(255, 51, 0)")
console.log([255, 221, 51].hexToRgb());//rgb(597,545,81)
console.log([255, 221, 51].hexToRgb(1));//[597, 545, 81]
Array method: rgbToHex
颜色的rgb值转换为十六进制值
myArray.rgbToHex([array]);
console.log([255, 221, 51].rgbToHex());//#ffdd33
console.log([255, 221, 51].rgbToHex(1));//["ff", "dd", "33"]
console.log([255, 221, 51, 0].rgbToHex());//transparent
console.log([255, 221, 51, 0.5].rgbToHex());//#ffdd33
//Type: String
//string对象的一些方法和函数的集合
Function: String.from
把传入的参数转换成为字符串
String.from(arg);
console.log(String.from(10));//'10'
console.log(String.from(true));//'true'
Function: String.uniqueID
生成一个唯一的id
String.uniqueID();
$$('.a')[0].set('id', String.uniqueID())
console.log($$('.a')[0].get('id'));//随机的string
String method: test
使用字符串和正则表达式获取匹配
myString.test(regex[, params]);
参数:
regex - (mixed) 想要匹配的字符串或正则The string or regular expression you want to match the string with.
params - (string, optional) 如果第一个参数是string,这个参数表示任何你想传入正则表达式的参数('g'无效果).
console.log('I hate you!'.test(/Hate/i));//true
console.log('I hate you!'.test('i', 'i'));//true
console.log('I hate you!'.test('love'));//false
String method: contains
检查传入的字符串是否包含在当前字符串中
myString.contains(string[, separator]);
参数:
string - (string) 想查询的字符串
separator - (string, optional) 字符串分隔符 (比如Element classNames是被空格分隔的)
console.log('a bc-d'.contains('b'));//true
console.log('a bc-d'.contains('b', ' '));//false
console.log('a bc-d'.contains('d', '-'));//true
String method: trim
清除字符串开头和末尾的空白符
myString.trim();
console.log('|' + ' I hate you! '.trim() + '|');//|I hate you!|
String method: clean
清除无关系的空白符
myString.clean();
console.log(' I hate you ! '.clean());//I hate you !
String method: camelCase
把带有连字符号的字符串转换成驼峰式
myString.camelCase();
console.log('I-hate-you!'.camelCase());//IHateYou!
String method: hyphenate
与camelCase方法相反
myString.hyphenate();
console.log('IHateYou!'.hyphenate());//-i-hate-you!
String method: capitalize
单词的首字母大写
myString.capitalize();
console.log('i hate you!'.capitalize());//I Hate You!
String method: escapeRegExp
转义正则表达式的特殊字符
myString.escapeRegExp();
console.log('Animal.dogs[1]'.escapeRegExp());//Animal\.dogs\[1\]
String method: toInt
转换字符串并根据指定的基数返回number值
myString.toInt([base]);
参数:base - (number, optional) 使用的基数(默认是10)
console.log('10em'.toInt());//10
console.log('30'.toInt(8));//24
console.log('11'.toInt(2));//3
console.log('13.67'.toInt());//13
String method: toFloat
把字符串转换成浮点值
myString.toFloat();
console.log('12.35'.toFloat());//12.35
String method: hexToRgb
十六进制的字符串转换为rgb值
myString.hexToRgb([array]);
console.log('#123'.hexToRgb());//rgb(17,34,51)
console.log('123'.hexToRgb());//rgb(17,34,51)
console.log('#123'.hexToRgb(true));//[17, 34, 51]
String method: rgbToHex
rgb字符串转换成十六进制颜色值
myString.rgbToHex([array]);
console.log('rgb(17,34,51)'.rgbToHex());//#112233
console.log('rgb(17,34,51,0)'.rgbToHex());//transparent
console.log('rgb(17,34,51)'.rgbToHex(true));//["11", "22", "33"]
String method: substitute
使用一个传入的对象或数组替换字符串关键字,移除未定义的关键字并忽略不匹配的关键字
myString.substitute(object[, regexp]);
参数:
object - (mixed) 用于替换字符串的名/值对
regexp - (regexp, optional) 用在关键字中的正则表达式,带有全局标识,默认是/\\?\{([^{}]+)\}/g
返回:(string) - 被替换的字符串
var myString = '{subject} is {property_1} and {property_2}.';
var myObject = {subject: 'Jack Bauer', property_1: 'our lord', property_2: 'saviour'};
myString.substitute(myObject); // Jack Bauer is our lord and saviour
var date = new Date();
var s = 'The name of the user is [name],'
+ ' the status of the user is [status], '
+ ' the last time [name] visited this page is [datetime].';
var o = {
name: 'chemdemo',
status: 'visitor',
datetime: date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate()
};
console.log(s.substitute(o, /\[([^\[\]]+)\]/g));
//The name of the user is chemdemo, the status of the user is visitor, the last time chemdemo visited this page is 2011-2-31.
String method: stripScripts
把字符串内的标签剥离字符串(从字符串中去除)
myString.stripScripts([evaluate]);
参数:evaluate - (boolean, optional) 如果传入true,字符串内的script标签将被执行
返回:(string) - 返回没有标签的字符串
console.log('<script>alert(\'Hello\');<\/script>Hello World!'.stripScripts());//Hello World!
console.log('<script>alert(\'Hello\');<\/script>Hello World!'.stripScripts(true));//先弹出alert框在返回Hello World!