DIV CSS 佈局教程網

JavaScript 常用引用類型操作方法大盤點
編輯:JavaScript基礎知識     

引用類型的方法多而零散,平時用到再查往往記不牢。這篇按類型把常用 API 集中梳理一遍,方便日後快速定位。

Array 類型

排序:sort 與比較函數

升序:

function compare(value1, value2){
  if (value1 < value2){
    return -1;
  }
  if (value1 > value2){
    return 1;
  } else{
    return 0;
  }
}
var values = [0,1,5,10,15];
values.sort(compare);
console.log(values); // [0,1,5,10,15]

降序只需把返回值反過來:

function compare(value1, value2){
  if (value1 < value2){
    return 1;
  }
  if (value1 > value2){
    return -1;
  } else{
    return 0;
  }
}

slice:截取

slice(start, end) 返回從指定位置開始到數組末尾的所有項;若給兩個參數,則返回起止位置之間的項,但不含結束位置。

var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
console.log(colors2); // green, blue, yellow, purple
console.log(colors3); // green, blue, yellow

splice:刪除、插入、替換

刪除——兩個參數:起始位置與要刪除的項數。

var colors = ["red", "green", "blue"];
var removed = colors.splice(0,1);
console.log(colors); // green, blue
console.log(removed); // red

插入——三個參數:起始位置、0(刪除項數)、要插入的項。

var colors = ["red", "green", "blue"];
var removed = colors.splice(1,0,"yellow", "orange");
console.log(colors); // ["red", "yellow", "orange", "green", "blue"]
console.log(removed); // 返回空數組

替換——三個參數:起始位置、要刪除的項數、任意數量的插入項。

var colors = ["red", "green", "blue"];
var removed = colors.splice(1,1,"yellow", "orange");
console.log(colors); // ["red", "yellow", "orange", "blue"]
console.log(removed); // ["green"]

RegExp 類型

var pattern1 = /[bc]/i;
var pattern2 = new RegExp("[bc]at", "i");

兩種寫法完全等價。注意傳給 RegExp 構造函數的兩個參數都是字符串,不能把正則字面量直接傳進去。由於模式參數是字符串,某些情況下需要進行雙重轉義:

var pattern1 = /[bc]/i;
var pattern2 = new RegExp("\\[bc\\]at", "i");

RegExp 實例方法:exec

接收一個參數(要應用模式的字符串),返回包含第一個匹配信息的數組。

var text = "cat, bat, sat, fat";
var pattern1 = /.at/;
var matches = pattern1.exec(text);
console.log(matches); // ["cat"]

字符串方法:match

var text = "cat, bat, sat, fat";
var pattern1 = /.at/;
var matches2 = text.match(pattern1);
console.log(matches2); // ["cat"]

測試方法:test

var text = "000-00-0000";
var pattern = /\d{3}-\d{2}-\d{4}/;
if (pattern.test(text)){
  console.log("The pattern was matched");
}

Function 類型

把 arguments 轉為數組

(function() {
  var slice = Array.prototype.slice,
      aArguments = slice.apply(arguments);
  console.log(aArguments);
})(10, 20, 30);

arguments.callee 是一個指針,指向擁有該 arguments 對象的函數。注意在嚴格模式下訪問它會拋出錯誤。

函數的屬性與方法

length 表示函數希望接收的命名參數個數。

function sayName(name){ alert(name); }
function sum(num1,num2){ return num1 + num2; }
function sayHi(){ alert("hi"); }
console.log(sayName.length); //1
console.log(sum.length); //2
console.log(sayHi.length); //0

call 與 apply

function sum(num1, num2){
  return num1 + num2;
}
function callSum1(num1,num2){
  return sum.apply(this,arguments);
}
function callSum2(num1, num2){
  return sum.apply(this, [num1, num2]);
}
console.log(callSum1(10,10)); // 20
console.log(callSum2(10,10)); // 20

window.color = "red";
var o = {color:"blue"};
function sayColor(){
  console.log(this.color);
}
sayColor();            // red
sayColor.call(this);   // red
sayColor.call(window); // red
sayColor.call(o);      // blue

基本包裝類型

var value = "25";
var number = Number(value);
console.log(typeof number);              // number
console.log(number instanceof Number);   // false

var obj = new Number(value);
console.log(typeof obj);                 // object
console.log(obj instanceof Number);      // true

Boolean

var falseObject = new Boolean(false);
var result = falseObject && true; // true
// 布爾表達式中的所有對象都會被轉換為 true,
// 因此 falseObject 在布爾表達式中代表的是 true
console.log(result); // true

var falseValue = false;
result = falseValue && true;
console.log(result); // false

console.log(typeof falseObject);            // object
console.log(typeof falseValue);             // boolean
console.log(falseObject instanceof Boolean); // true
console.log(falseValue instanceof Boolean);  // false

Number

var numberObject = new Number(10);
var numberValue = 10;
console.log(typeof numberObject);          // object
console.log(typeof numberValue);           // number
console.log(numberObject instanceof Number); // true
console.log(numberValue instanceof Number);  // false

String 類型

字符方法

charAt() 以單字符字符串形式返回給定位次的字符;charCodeAt() 返回該位置的字符編碼。

var stringValue = "hello world";
console.log(stringValue.charAt(1));     // e
console.log(stringValue.charCodeAt(1)); // 101

字符串操作方法

concat() 拼接一或多個字符串。

var stringValue = "hello ";
var result = stringValue.concat("world");
console.log(result);       // hello world
console.log(stringValue);  // hello(原字符串不變)

slice(start, end)——若傳入負數,會把負值與字符串長度相加。

var str="Hello happy world!";
console.log(str.slice(6));    // happy world!
console.log(str.slice(6,11)); // happy
console.log(str.slice(-3));   // ld!
console.log(str.slice(3, -4)); // lo happy wo

substring(start, end)——若傳入負數,會把所有參數都當作 0。

var str="Hello happy world!";
console.log(str.substring(6));    // happy world!
console.log(str.substring(6,11)); // happy
console.log(str.substring(-3));   // Hello happy world!
console.log(str.substring(3, -4)); // Hel

substr(start, length)——負的第一個參數會加上字符串長度,負的第二個參數則轉為 0。

var str="Hello world!";
console.log(str.substr(3));    // lo world!
console.log(str.substr(3, 7)); // lo worl
console.log(str.substr(-3));   //  ld!
console.log(str.substr(3, -3)); // 空字符串

字符串位置方法

var stringValue = "hello world";
console.log(stringValue.indexOf("o"));      // 4
console.log(stringValue.lastIndexOf("o"));  // 7

這兩個方法都可以接收可選的第二個參數,指定從哪個位置開始搜索。

var stringValue = "hello world";
console.log(stringValue.indexOf("o", 6));     // 7
console.log(stringValue.lastIndexOf("o", 6)); // 4

字符串的模式匹配方法

match()

var text = "cat, bat, sat, fat";
var pattern = /.at/;
var matches = text.match(pattern);
console.log(matches.index);      // 0
console.log(matches[0]);         // cat
console.log(pattern.lastIndex);  // 0

search()

var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
console.log(pos); // 1

replace()

var text = "cat, bat, sat, fat";
var result = text.replace("at", "ond");
console.log(result); // cond, bat, sat, fat

var result = text.replace(/at/g, "ond");
console.log(result); // cond, bond, sond, fond

Global 對象

encodeURI() 和 encodeURIComponent() 可對 URI(通用資源標識符)進行編碼,以便發送給瀏覽器;對應的解碼方法是 decodeURI() 和 decodeURIComponent()。

var url = "https://www.baidu.com/";
console.log(encodeURI(url));
console.log(encodeURIComponent(url));

Math 對象

Math.random() 返回介於 0 和 1 之間的隨機數(不含 0 和 1)。套用下面的公式,可以從指定整數範圍內隨機取值:

值 = Math.floor(Math.random() * 可能值的總數 + 第一個可能的值)

例如取 1 到 10 之間的隨機數:

var num = Math.floor(Math.random()*10+1);

封裝成通用方法:

function selectFrom(lowerValue, upperValue){
  var choice = upperValue - lowerValue + 1;
  return Math.floor(Math.random()*choice + lowerValue);
}
var num = selectFrom(2,10);
console.log(num);

var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
var color = colors[selectFrom(0, colors.length-1)];
console.log(color);

這些 API 單看都不難,難的是記住差異——比如 slice 與 substring 對負數的處理截然相反,splice 的第二個參數在插入場景下必須為 0。建議把這類對比反覆寫一遍,比單純閱讀有效得多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved