記錄一些 js 實用的方法

說明

記錄一些 js 實用的方法

從字符串中提取 img 標籤,獲取每個 img 的 src

export function getImg(str) {
  let imgs = str.match(/<img.+?>/gi);
  imgs = imgs.map(function(item, index) {
    //提取出src
    let _src = item.match(/src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
    // console.log("_src", _src);
    return '<img src="' + _src + '" width="100%">';
  });
}

DOM獲取

export function getEle(el) {
  return document.querySelector(el);
}
export function getEles(el) {
  return document.querySelectorAll(el);
}

判斷字符串是否以給定字符“結尾”

endsWith() 方法用來判斷當前字符串是否是以另外一個給定的子字符串“結尾”的,根據判斷結果返回 true 或 false。

str.endsWith(searchString [, position]);

參數:

  • searchString, 要搜索的子字符串
  • position, 可選。作爲 str 的長度,默認值爲 str.length。
var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

這個方法已經加入到 ECMAScript 6 標準當中,但是可能還沒有在所有的 JavaScript 實現中可用。

polyfill:

	if (!String.prototype.endsWith) {
		String.prototype.endsWith = function(search, this_len) {
			if (this_len === undefined || this_len > this.length) {
				this_len = this.length;
			}
			return this.substring(this_len - search.length, this_len) === search;
		};
	}
	

判斷數據類型

 isType(params, type) {
    // 判斷數據類型
    // String Number Boolean Undefined Null Object Array Function HTMLDocument HTMLDocument
    return Object.prototype.toString.call(params) === "[object " + type + "]";
  }

判斷一個數組是否包含一個指定的值

includes() 方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false。

arr.includes(searchElement, fromIndex)

參數:

  • searchElement,需要查找的元素值
  • fromIndex,可選,從該索引處開始查找 searchElement。如果fromIndex 大於等於數組長度 ,則返回 false 。該數組不會被搜索。如果爲負值,則按升序從 array.length - fromIndex 的索引開始搜索。默認爲 0。
[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

includes() 方法有意設計爲通用方法。它不要求 this 值是數組對象,所以它可以被用於其他類型的對象 (比如類數組對象)。下面的例子展示了 在函數的 arguments 對象上調用的 includes() 方法。

(function() {
  console.log([].includes.call(arguments, 'a')); // true
  console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');

Polyfill

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

數組內容位置排序

export var arraySort = {
  arr: null,
  init(_arr) {
    if (this.typeof(_arr, "Array")) {
      this.arr = _arr;
    } else {
      throw new TypeError("Initialization data type is not an array");
    }
  },
  swapArray(x, y) {
  	// 交換數組中兩個索引處的元素
    this.arr.splice(x, 1, ...this.arr.splice(y, 1, this.arr[x]));
  },
  sortUp(index) {
    if (index != 0) {
      this.swapArray(index, index - 1);
    }
  },
  sortDown(index) {
    if (index != this.arr.length - 1) {
      this.swapArray(index, index + 1);
    }
  },
  del(_index, callback) {
    if (this.typeof(callback, "Function")) {
      if (callback()) {
        this.arr.splice(_index, 1);
      }
    } else {
      if (this.arr.length > 1) {
        this.arr.splice(_index, 1);
      }
    }
  },
  typeof(params, type) {
    // 判斷數據類型
    // String Number Boolean Undefined Null Object Array Function HTMLDocument HTMLDocument
    return Object.prototype.toString.call(params) === "[object " + type + "]";
  }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章