8 Array

与其他语言不同的是, ECMAScript 数组的每一项可以保存任何类型的数据。

也就是说,可以用数组的第一个位置来保存字符串,用第二位置来保存数值,用第三个位置来保存对象,以此类推。

1 如何将数组转换成字符串类型?

var colors = ["blue", "red", "green"];
console.log(colors.toString());
console.log(colors.join(" "));

常用的有如上两种方法。

2 需要在数组的后面再加入两项,怎么做?

var colors = ["a", "b", "c"];
colors.push("d", "e");

3 需要在数组前面加入两项,怎么做?

var colors = ["a", "b", "c"];
colors.unshift("d", "e");

4 颠倒:将下列数组的内容颠倒。

var colors = ["a", "b", "c"];
colors.reverse();

5 排序:对下列数组进行降序排列。

var values = [1, 10, 150, 15];
values.sort(compare);
console.log(values.toString());
function compare(num1, num2){
    return (num1 > num2) ? -1 : 1;
}

6 排序:将下列数组中的姓名,按照a-z的顺序进行排序

var arr = ["张三", "李四", "阿元", "王五"];
arr.sort(compare);
console.log(arr.toString());
function compare(str1, str2){
    return str1.localeCompare(str2);
}

7 合并

var alph = ["a", "b", "c"];
var alph2 = alph.concat("d", ["e", "f"]);

document.write( alph+'<br>' );
document.write( alph2+'<br>' );

8 截取

var alph = ["a", "b", "c", "d", "e"];
var alph2 = alph.slice(1,4);

document.write( alph+'<br>' ); 
document.write( alph2+'<br>' ); 

9 替换

var alph = ["a", "b", "c","d","e"];
var moved = alph.splice(1,3,"96","97","98","99");
document.write( moved+'<br>' );
document.write( alph+'<br>' );

10 位置方法

var alph = ["a", "b", "c", "d", "e", "d", "c", "b", "a"];
document.write( alph.lastIndexOf( "d") +"<br>");
document.write( alph.lastIndexOf( "d", 2) );

ECMAScript 5 为数组实例添加了两个位置方法: indexOf()和 lastIndexOf()。

这两个方法都接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。

11 迭代方法

ECMAScript 5 为数组定义了 5 个迭代方法。

every():对数组中的每一项运行给定函数,如果该函数对每一项都返回 true,则返回 true。

some():对数组中的每一项运行给定函数,如果该函数对任一项返回 true,则返回 true。

filter():对数组中的每一项运行给定函数,返回该函数会返回 true 的项组成的数组。

map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。

forEach:这个方法没有返回值,本质上与使用 for 循环迭代数组一样。

var person = [{name: "A", score:70},
    {name: "B", score:90},
    {name: "C", score:50},
    {name: "D", score:80}];

var result = person.filter( function(item, index, arr) {
        if (item.score >= 60) {
            return item;
        }
    }
);
result.forEach( function(item, index, arr) {
        document.write("name:" + item.name+" score:" + item.score + "<br>");
    }
);

12 归并

var values = [1,2,3,4,5];
var sum = values.reduce( function(prev, cur, index, array) {
    document.write(prev + "&nbsp;" + cur + "<br>");
    return prev + cur;
} );
原文地址:https://www.cnblogs.com/lijy/p/6611594.html