博主在js上已經花費了很長時間,不禁深深地被其輕巧而強大的功能,以及優雅靈活的寫法所折服,一直沒找到機會來總結一下,最近發現了簡書這個不錯的平臺,正好把學習的東西做一個匯總。
題外話
我始終認為,學習編程最好的方式就是去寫,甭管寫的怎樣,也要去練習。
當初學完了數組,我記得自己是先把里面的每一個方法都敲了一遍,然后反復思考,通過這些方法,我能夠做些什么?
很多語法我一開始也是很不理解的,然而在不斷地運用過程中,慢慢地就開始明白過來了。只要抓住一個大方向,然后不斷地練,就一定能深入理解!
正如國外一個有名的數學家所言,只有抓住了主樹干,枝葉方面的細節便會奇跡般地豐富起來。
很多初學者,包括當年的我自己,總是覺得這個也要學,那個也要學,不敢直接去找工作,總想著全部學完了才行。可是呢,怎樣算是個頭呢,技術這東西日新月異。css3來了,一股腦兒跑去學css3,后來各種框架如雨后春筍般破土而出,ext.js,easy-ui,bootstrap,等等,面對各種各樣的新框架,真的感覺時間不夠。
其實,現在我個人感覺真不必這樣,要知道,所有的js框架都是以js為源頭,當自己js的功底足夠牢固,那么就一切OK。我之前認識的一個朋友,從來沒接觸過bootstrap,后來公司要用,看了兩三天直接就上手,用bootstrap來開發項目了。
js + css是根,真是如此的。
否則,你永遠會覺得自己在學習,卻不知道這樣的目的是什么。所以,不管三七二十一,如果你現在還是一個處于迷茫求職階段的畢業生,或者是剛培訓完,那么,不用慌,先找一份工作干起來再說,在工作中慢慢積累。
不要害怕,覺得自己好多不懂,會不會有問題,真沒關系的,不要企圖把所有技術學完了再去找工作。
哈,閑話不多說,開始記錄。
1.字符串相關
1.1 format方法
在各種編程語言中,字符串的format方法是比較常見的,以下通過js擴展的方式,實現了js版本的format方法。目前貌似還沒有瀏覽器支持這一個方法。
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;
})
};
}
例子:
var template = "今天的天氣很{0},大家一起去{1}!";
alert(template.format("晴朗","郊游"));
效果:
2.數組相關
1.2 forEach(callback,context) 操作數組中的每一個元素
ie9以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。
以下是兼容性的擴展寫法:
/**
forEach除了接受一個必須的回調函數參數,還可以接受一個可選的上下文參數(改變回調函數里面的this指向)(第2個參數)。
*/
if (!Array.prototype.forEach && typeof Array.prototype.forEach !== "function") {
Array.prototype.forEach = function(callback, context) {
// 遍歷數組,在每一項上調用回調函數,這里使用原生方法驗證數組。
if (Object.prototype.toString.call(this) === "[object Array]") {
var i,len;
//遍歷該數組所有的元素
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);
效果:
這個方法在各大瀏覽器都得到了較好的支持。
1.3 indexOf(searchvalue,fromindex) 查詢數組中某一個值的下標
ie9以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。以下是兼容性的擴展寫法:
//獲取某元素在數組中第一次出現的下標
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;
};
}
例子:
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 []);//object
alert(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
雖然取巧了點,不過目的確實達到了。
數組封裝
通過數組的一些基本方法,我們可以開始自己模擬一下java中的ArrayList了,話不多說,貼上代碼:
//模擬ArrayList
function 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];
}
/**
* 獲取列表數組
*/
this.toArray = function(){
return arr;
}
/**
* 獲取某一個元素的角標
* 如果只出現一次,就返回一個數字,如果大于一次,就返回數組
*/
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();
}
}
//測試代碼
var list = new ArrayList();
list.add('張三');
list.add('李四');
list.add('王五');
list.add('趙六');
list.add('王五');
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('張三');
list.add('張三');
console.log(list.toArray());
console.log(list.indexOf('張三'));
console.log(list.indexOf('趙六'));
運行結果:
本章結束 ...
剽悍一小兔,電氣自動化畢業。
參加工作后對計算機感興趣,深知初學編程之艱辛。
希望將自己所學記錄下來,給初學者一點幫助。
免責聲明: 博客中所有的圖片素材均來自百度搜索,僅供學習交流,如有問題請聯系我,侵立刪,謝謝。