In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces JavaScript common methods and encapsulation instance analysis related knowledge, detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that everyone will have a harvest after reading this JavaScript common methods and encapsulation instance analysis article, let's take a look at it together.
1. String correlation 1.1 format method
In various programming languages, the format method of string is more common, the following is a js version of the format method implemented by js extension. No browser currently supports this method.
if(! String.prototype.format ){ String.prototype.format = function() { var e = arguments; return this.replace(/{(\d+)}/g,function(t, n) { return typeof e[n] != "undefined" ? e[n] : t; }) };}
Examples:
var template = "Today's weather is very {0}, everyone go {1} together! ";alert(template.format(" sunny "," outing "));
Effect:
2. Array dependency 1.2 forEach(callback,context) operates on each element of an array
Internet Explorer 9 and above, as well as other non-IE browsers, support this method.
The following is an extension of compatibility:
/** forEach can accept an optional context parameter (changing the this pointer in the callback function) in addition to a required callback parameter (second parameter). */ if (! Array.prototype.forEach && typeof Array.prototype.forEach !== "function") { Array.prototype.forEach = function(callback, context) { //Traverse the array, calling the callback function on each item, where the array is validated using native methods. if (Object.prototype.toString.call(this) === "[object Array]") { var i,len; //traverse all elements of the array for (i = 0, len = this.length; i
< len; i++) { if (typeof callback === "function" && Object.prototype.hasOwnProperty.call(this, i)) { if (callback.call(context, this[i], i, this) === false) { break; // or return; } } } } };} 例子: var drinks = ['雪碧','可乐','脉动','红牛','农夫山泉']; var context = { str1 : '【', str2 : '】'}; drinks.forEach(function(item){ console.log(this.str1 + item + this.str2);},context); 效果:This method is well supported in all major browsers.
1.3 indexOf(searchvalue,fromindex) Query the subscript of a value in an array
Internet Explorer 9 and above, as well as other non-IE browsers, support this method.
The following is an extension of compatibility:
//Get the subscript if (!) of the first occurrence of an element in the array 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 ? 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; }; } 例子: var index = drinks.indexOf('雪碧');alert(index);//0 类似的还有lastIndexOf,用于获取数组中某个元素最后一次出现的位置。如果数组没有这个元素,则返回-1。 该方法的实现: //获取某元素在数组中最后一次出现的下标if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = len - 1; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { n = 0; } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) { if (k in t && t[k] === searchElement) { return k; } } return -1; };}
通过这两个方法,我们可以来做一些有意思的事情了。比如,判断一个对象是否为数组?
IE9 以上的浏览器,已经支持通过Array.isArray()来验证一个对象是否为数组了。
比如:
var result = Array.isArray([]);alert(typeof []);//objectalert(result); //true
那么,如果我们自己来实现,又该如何做呢?下面给出一个简单思路,
简单模拟一下这个过程:
//首先,让我们来看一看数组的构造器是咋样的?console.log([].constructor.toString()); /* 打印出来是这样的: function Array() { [native code] }*/
于是便有了
var Array = function(){ } Array.isArray = function(obj){ return obj.constructor.toString().indexOf('Array') != -1;} var result = Array.isArray([]); alert(result); //true
虽然取巧了点,不过目的确实达到了。
2.数组封装
通过数组的一些基本方法,我们可以开始自己模拟一下java中的ArrayList了
代码如下:
//模拟ArrayListfunction ArrayList(){ var arr = []; //用于保存数据的数组 var length = 0; //数组的长度,默认为0 /** * 判断是否为空 */ this.isEmpty = function(){ return length == 0; } /** * 获取列表长度 */ this.size = function(){ return length; } /** * 判断对象中是否包含给定对象 */ this.contains = function(obj){ if(arr.indexOf(obj) != -1){ return true; } return false; } /** * 新增 */ this.add = function(obj){ length = length + 1; arr.push(obj); } /** * 删除 * 参数1 obj : 需要删除的元素 * 参数2 deleteAll: 是否全部删除,否则默认删除第一个匹配项 */ this.remove = function(obj,deleteAll){ var len = arr.length; for(var i = 0 ;i
< len ;i++){ if(arr[i] == obj){ arr.splice(i,1); length = length - 1; if(!deleteAll){ break; } } } } /** * 根据索引获取对应的元素 */ this.get = function(index){ if(index >length - 1){ return null; } return arr[index]; } /** * Get List Array */ this.toArray = function(){ return arr; } /** * Gets the subscript of an element * Returns a number if it occurs only once, and an array if it occurs more than once. */ this.indexOf = function(obj){ var rstArr = []; var count = 0; for(var i = 0 ;i < length ;i++){ if(obj == arr[i]){ rstArr[count++] = i; } } if(count == 1){ return rstArr[0]; } return rstArr; } this.toString = function(){ return arr.toString(); }}//test code var list = new ArrayList();list.add ('Zhang San');list.add ('Li Si');list.add ('Wang Wu');list.add ('Zhao Liu');list.add ('Wang Wu');console.log (list.size());console.log (list.toString());console.log (list.contains (''));list.remove ('',true); //null,undefined,''console.log (list.toString());console.log (list.get(0));console.log (list.get(1));console.log (list.get(2));console.log (list.size()); console.log(list.toArray());list.add ('Zhang San');list. add ('Zhang San');console.log(list.toArray());console.log(list.indexOf ('Zhang San'));console.log(list.indexOf ('Zhao Liu'));
Run Results:
About "JavaScript common methods and encapsulation example analysis" The content of this article is introduced here, thank you for reading! I believe that everyone has a certain understanding of the knowledge of "JavaScript common methods and encapsulation example analysis". If you still want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.