JS积累学习

3,402 阅读1分钟

一、数组的合并

数组合并不去重可以直接用Array.concat()

var a = [1];
var b = [1, 2];
var c = [1, 2, 3];
a.concat(b, c); //[1,1,2,1,2,3]

自定义数组合并去重

var a = [1, 2, 3, 4];
var b = [3, 4, 5, 6];
function MergeArray(arr1,arr2){
    var _arr = new Array();
    for(var i=0;i<arr1.length;i++){
       _arr.push(arr1[i]);
    }
    for(var i=0;i<arr2.length;i++){
        var flag = true;
        for(var j=0;j<arr1.length;j++){
            if(arr2[i]==arr1[j]){
                flag=false;
                break;
            }
        }
        if(flag){
            _arr.push(arr2[i]);
        }
    }
    return _arr;
}

MergeArray(a, b);  //[1, 2, 3, 4, 5, 6]

关于数组去重的方法很多,详细的请看javascript 数组合并与去重

二、数组排序

如果是字母,按字母顺序排序

var a = ["ba", "bb", "bac", "abc"];
a.sort(); //["abc", "ba", "bac", "bb"]

如果是数字,按大小排序

var a = [2, 1, 0, -1, -8, -2];
a.sort(function(a,b){return a - b}); //[-8, -2, -1, 0, 1, 2]

如果数组里面是对象,我们参考一下这个方法排序

var ArraySortBy = function(name){
    return function(o, p){
        var a, b;
        if (typeof o === "object" && typeof p === "object" && o && p) {
            a = o[name];
            b = p[name];
            if (a === b) {
                return 0;
            }
            if (typeof a === typeof b) {
                return a < b ? -1 : 1;
            }
            return typeof a < typeof b ? -1 : 1;
        }
        else {
            throw ("error");
        }
    }
}

var a = [{name: 'Amy', age: 10}, {name: 'Jim', age: 8}, {name: 'bob', age: 9}]

a.sort(ArraySortBy('age'));

三、数组的删除

var a = [1,2,3,4];
a.splice(1,1); //[1,3,4]

第一个参数为开始的位置,第二个参数为从第一个参数位置开始要删除的数目;如果第一个参数为负数,则开始的位置从数组的尾部开始倒数计算。

四、对象的循环

var a = {name: 'Amy', age: 18};
for (key in a) {
	console.log(key, a[key])
}

// name Amy
// age 18

五、对象的删除

var a = {name: 'Amy', age: 18};
delete a['name'] //true
a  //{age: 18}

六、浮点计算问题 js的浮点计算会出现计算错误的问题

0.1 + 0.2 //0.30000000000000004

我们需要通过toFixed的方法来解决这个问题。

七、关于Array.find()和Array.indexOf()在safari上不支持,也就意味着iPhone手机不支持。

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let o be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var o = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of o with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = o.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of o with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of o with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in o && o[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}



if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, "find", {
    value: function(predicate) {
     'use strict';
     if (this == null) {
       throw new TypeError('Array.prototype.find called on null or undefined');
     }
     if (typeof predicate !== 'function') {
       throw new TypeError('predicate must be a function');
     }
     var list = Object(this);
     var length = list.length >>> 0;
     var thisArg = arguments[1];
     var value;

     for (var i = 0; i < length; i++) {
       value = list[i];
       if (predicate.call(thisArg, value, i, list)) {
         return value;
       }
     }
     return undefined;
    }
  });
}