首页 > 代码库 > JavaScript中的字符串和数组

JavaScript中的字符串和数组

js中操作字符串和操作数组是差不多的。

以下面的数组为例:

var arr = [e, c, r, o];var arrnum = [6, 4, 23, 67];

1、判断是否为数组

if(arr instanceof Array) {    console.log(true);}if(Array.isArray(arr)) { //ECMAScript 5    console.log(true);}

2、格式化为字符串

console.log(arr.join(,));

3、添加删除

arr.push(‘x‘);console.log(arr); //["e", "c", "r", "o", "x"] arr.pop();console.log(arr); //["e", "c", "r", "o"] arr.shift();console.log(arr); //["c", "r", "o"]arr.unshift(‘d‘);console.log(arr); //["d", "c", "r", "o"]

4、排序方法

console.log(arr.reverse()); //["o", "r", "c", "d"] console.log(arr.sort());    //["c", "d", "o", "r"] console.log(arrnum.sort()); //转换为字符串后比较 [23, 4, 6, 67] console.log(arrnum.sort(compare)); //[4, 6, 23, 67] console.log(arrnum.sort(compareEx)); //[4, 6, 23, 67] function compare(a, b) {    if(a < b) {        return -1;    } else if(a > b) {        return 1;    } else {        return 0;    }}function compareEx(a, b) {    return a - b;}

5、操作方法

var arrnew = arr.concat(‘red‘, [‘ss‘, ‘z‘]);console.log(arrnew); //["e", "c", "r", "o", "red", "ss", "z"] 
console.log(arr.slice(2));      //["r", "o"]console.log(arr.slice(1, 3));   // ["c", "r"]
//splice 最强大 返回值为删除的组成的数组 自身改变console.log(arr.splice(1, 3));  //["c", "r", "o"] console.log(arr);                    //["e"]var arr = [‘e‘, ‘c‘, ‘r‘, ‘o‘];   console.log(arr.splice(2, 0, ‘add‘, ‘dd‘)); //[]console.log(arr); //["e", "c", "add", "dd", "r", "o"] var arr = [‘e‘, ‘c‘, ‘r‘, ‘o‘];console.log(arr.splice(2, 2, ‘ed‘, ‘fr‘)); //["r", "o"] console.log(arr); //["e", "c", "ed", "fr"] 

6、位置方法 ECMAScript 5

var arr = [‘e‘, ‘c‘, ‘r‘, ‘o‘];console.log(arr.indexOf(‘t‘)); //-1console.log(arr.indexOf(‘c‘)); //1console.log(arr.lastIndexOf(‘c‘)); //1

7、迭代方法 ECMAScript 5

var num = [1, 3, 5, 10, 56, 11];var r = num.every(function(item, index, array) {         //所有满足返回true    return (item % 2 == 0);});console.log(r);r = num.filter(function(item, index, array) {        //过滤    return (item % 2 == 0);});console.log(r);r = num.some(function(item, index, array) {       //一个符合就返回true    return (item % 2 == 0);});console.log(r);r = num.map(function(item, index, array) {        //返回新数组    return (item - 1);});console.log(r);//对每项操作num.forEach(function(item, index, array) {    console.log(item);});

8、缩小方法 ECMAScript 5

//参数:前一项,当前项,序号,数组var num = [1, 3, 5, 10, 56, 11];var sum = num.reduce(function(pre, cur, index, array) {    return pre + cur;});console.log(sum);  //86var sum = num.reduceRight(function(pre, cur, index, array) {    console.log(pre + ‘ ‘ + cur);    return pre - cur;});console.log(sum); //-64

9、字符串

var name = ‘zjzhome‘;console.log(name.charAt(1));  //jconsole.log(name.substring(1, 3)); //和slice类似 首选slice //jzconsole.log(name.substr(3)); //homeconsole.log(name.substr(1, 3)); //jzh

 

JavaScript中的字符串和数组