js使用技巧

来源:互联网 发布:焦作优易网络 编辑:程序博客网 时间:2024/06/05 15:02
js中indexOf    介绍indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。这里注意是首次出现。demo:var arry = ['apple', 'apple', 'dog', 'dog'];console.log(arry.indexOf('apple')); //0console.log(arry.indexOf('dog')); //2可以利用indexOf的这个特性,配合高阶函数filter对数组去重复元素的操作。demo:var arry = ['apple', 'apple', 'dog', 'dog'],    result;result = arry.filter(function(ele, index, arr) {    return arr.indexOf(ele) === index;})console.log(result.toString());//apple,dog//Array中的sort()方法默认把所有元素先转换为String再排序,结果'10'排在了'2'的前面,因为字符'1'比字符'2'的ASCII码小console.log([10, 20, 1, 2].sort()); // [1, 10, 2, 20]//解决办法,运用sort()的高阶函数,来实现 通常规定,对于两个元素x和y,如果认为x < y,则返回-1,如果认为x == y,则返回0,如果认为x > y,则返回1,这样,排序算法就不用关心具体的比较过程,而是根据比较结果直接排序var res = [10, 20, 1, 2];res.sort(function(x, y) { //正序    if (x > y) {        return 1;    } else if (x < y) {        return -1    }    return 0;})console.log('res', res);res.sort(function(x, y) { //倒序    if (x < y) {        return 1;    }    if (x > y) {        return -1;    }    return 0;})console.log('res', res);//字符串的情况下,默认情况下,对字符串排序,是按照ASCII的大小比较的,现在,我们提出排序应该忽略大小写,按照字母序排序。var chart = ['Google', 'apple', 'Microsoft'];chart.sort(function (s1, s2) {    x1 = s1.toUpperCase();    x2 = s2.toUpperCase();//转换成大写    if (x1 < x2) {        return -1;    }    if (x1 > x2) {        return 1;    }    return 0;}); // ['apple', 'Google', 'Microsoft']/**在这个例子中,我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力。**/function lazy_sum(arr) {    var sum = function() {        return arr.reduce(function(x, y) {            return x + y;        });    }    return sum;}var f = lazy_sum([1, 2, 3, 4, 5]);
0 0
原创粉丝点击