<!DOCTYPE html>
<html lang="en"><head> <meta charset="UTF-8"> <title>ECMAScript3中数组方法</title></head><body><script>//字符串和数组之间相转换的方法 1.join() split() /*var str = 'abcdefg'; console.log(str.split(''));//["a", "b", "c", "d", "e", "f", "g"] var arr = [1,2,3,4,5,[6,7,[8,9]]]; console.log(typeof(arr.join()));//string console.log(arr.join());//1,2,3,4,5,6,7,8,9*///跟顺序有关的两个方法 2.reverse() sort() /*var a = [1,2,4]; console.log(a.reverse().join());//4,2,1 var ar = ['arr','brr','evv','cww']; console.log(ar.sort());//["arr", "brr", "cww", "evv"] var anum = [33,4,3,1,6,99]; console.log(anum.sort(function(a,b){ return a-b; }))//[1, 3, 4, 6, 33, 99] console.log(anum.sort(function(a,b){ return b-a; }))//[99, 33, 6, 4, 3, 1] var aN = ['Body','ss','ass']; console.log(aN.sort(function(a,b){ var s = a.toLowerCase(); var t = b.toLowerCase(); if(s>t) return -1;//返回的值小于0,则参数应该在前 if(s<t) return 1;//返回的值大于0,则参数应该在后 return 0;//等于0,说明顺序无关紧要 }))//["ss", "Body", "ass"]*/// 3.截取或添加数组元素返回新数组的方法,特别注意splice()这个方法会修改调用的数组。concat() slice() splice() /*var arr = [1,3,4]; console.log(arr.concat(3,[4,5]));//[1, 3, 4, 3, 4, 5] console.log(arr.concat(3,[4,['a','b']]));//[1, 3, 4, 3, 4, ['a','b']] var arr1 = 'bnemohioue'; console.log(arr1.slice(1,4));//nem slice()第一个参数表示开始位置,第二个参数表示结束位置,但不包含第二个函数 console.log(arr1.slice(2));//emohioue 只有一个参数时代表从开始位置到数组结尾的所有元素。 console.log(arr1.slice(3,-1))//mohiou 如果出现负数,它表示相对于数组中最后一个元素的位置。参数-1指定了最后一个元素的位置 var arr2 = [1,2,3,4,5,6,7,8]; console.log(arr2.splice(3));//[4, 5, 6, 7, 8] console.log(arr2);//[1, 2, 3] console.log(arr2.splice(2,0,[1,2]));//[] console.log(arr2)//[1, 2, [1,2], 3] console.log(arr2.splice(2,2,'a','b','c'))//[[1,2], 3] console.log(arr2)//[1, 2, "a", "b", "c"]*/// 4.向数组中尾部或头部添加、删除元素的方法,返回数组新的长度/删除的元素 push()和pop() unshift()和shift() /*var arr3 = [2,4,'d']; console.log(arr3.push('d','f'));//5 console.log(arr3);//[2, 4, "d", "d", "f"] console.log(arr3.pop());//f console.log(arr3);//[2, 4, "d", "d"] console.log(arr3.pop());//d console.log(arr3);//[2, 4, "d"] console.log(arr3.unshift('k','lk'));//5 console.log(arr3);//["k", "lk", 2, 4, "d"] console.log(arr3.shift());//k console.log(arr3);//["lk", 2, 4, "d"]*/// 5.toString()、toLocaleString()是toString()方法的本地方版本。 console.log([2,3,'f'].toString());//2,3,f 这里不使用任何参数调用join()方法返回的字符串是一样的。将其每个元素转成字符串 console.log(['s','c','s'].toLocaleString());//s,c,s</script></body></html>