三: 数组排序

1: reverse() 颠倒数组顺序

    var a = [1,2,3,4,5];
    a.reverse();
    console.log(a);   //此时返回[5,4,3,2,1]

2: sort() 对元素排序

    var a = ["a","c","d","e","b"];
    a.sort();
    console.log(a);  //此时返回["a","b","c","d","e"]

sort() 使用排序函数,根据其他顺序执行操作时,必须提供一个函数参数,排序函数应该具有2个参数值 :

条件

如果自定义标准判断,a < b,在排序后的顺序中a应该出现在b之前,同时返回一个小于0的值
如果 a = b,就返回0
如果 a > b, 就返回一个大于0的值

    1、 根据排序函数比较数组大小,并按 "从小到大" 顺序执行排序
        function f(a,b){
            return (a-b);
        }
        var a = [3,1,2,4,5,7,6,8,0,9]
        a.sort(f);
        document.write( a );   //此时返回[0,1,2,3,4,5,6,7,8,9]

    2、 根据排序函数比较数组大小,并按 "从大到小" 顺序执行排序
        function g(a,b){
            return -(a-b);
        }
        var a = [3,1,2,4,5,7,6,8,0,9]
        a.sort(g);
        document.write( a );   //此时返回[9,8,7,6,5,4,3,2,1,0]

    3、 根据排序函数比较数组大小,并按 "奇偶" 顺序执行排序
        function g(a,b){
            var a = a % 2;  // %代表取余
            var b = b % 2;
            if( a == 0 ) return 1;
            if( b == 0 ) return -1;
        }
        var a = [3,1,2,4,5,7,6,8,0,9];
        a.sort(i);
        document.write(a);   //此时返回[9,8,7,6,5,4,3,2,1,0]

四 : 数组定位

1:indexOf() 返回元素值在数组中的索引值

    var ar = ["ab","cd","ef"];
    document.write(ar.indexOf("ab"));   //此时返回0

2:lastIndexOf() 返回指定元素值在数组中的最后一个匹配项的索引值

    var ar = ["ab","cd","ef"];
    document.write(ar.lastIndexOf("ab"));   //此时返回0

五 : 计算随机值

//创建数组
var Nums = ["99","98","95","86","97","79","80","92","94","96","88","89",];
var Prise = ["89,00,000","90,00,000","120,00,000","113,00,000","81,00,000",];

//利用Math.floor、Math.random求值计算
Nums[Math.floor(Math.random()*Nums.length + 1)-1]
Prise[Math.floor(Math.random()*Prise.length + 1)-1]