1. 程式人生 > >數組、字符串對象的各種方法

數組、字符串對象的各種方法

alert div world color bstr 不包含 bst sta char

數組的常用方法

1,shift()方法:把數組的第一個元素刪除,並返回第一個元素的值

var a = [a, b, c];
console.log(a,a.shift());
//[‘b‘,‘c‘]     ‘a‘

2,pop():用於刪除並返回數組的最後一個(刪除元素)元素,如果數組為空則返回undefined ,把數組長度減 1

var a = [‘a‘, ‘b‘, ‘c‘];
console.log(a,a.pop());
//["a", "b"]      "c"

3,unshift() :將參數添加到原數組開頭,並返回數組的長度

var
movePos =[111,222,333,444]; movePos.unshift("55555") document.write(movePos) //["55555",111,222,333,444]

4,push():可向數組的末尾添加一個或多個元素,並返回新的長度,(用來改變數組長度)。

var movePos=[11,22];

var arr=movePos.push("333");

console.log(movePos,arr) //[11, 22, "333"] 3

5,concat()方法:用於連接兩個或多個數組,並返回一個新數組,新數組是將參數添加到原數組中構成的

var movePos=[11,22];
var arr=movePos.concat(4,5);
console.log(arr);//[11, 22, 4, 5]

6,join()方法:用於把數組中的所有元素放入一個字符串。元素是通過指定的分隔符進行分隔的。

var movePos=[11,22];
var arr=movePos.join("+");
console.log(arr)  //11+22

7,slice()方法:可從已有的數組中返回選定的元素。slice(開始截取位置,結束截取位置)

var movePos=[11,22,33];
var arr=movePos.slice(1
,2); console.log(arr)//[22]

8,splice()方法:方法向/從數組中添加/刪除項目,然後返回被刪除的項目。

var movePos=[11,22,33,44];
var arr=movePos.splice(1,2);//刪除
console.log(arr,movePos)
 [22, 33]     [11, 44]

var movePos =[111,222,333,444];
movePos.splice(2,1,"666")
console.log(movePos)

[111, 222, "666", 444]

--------------------

1 split:方法用於把一個字符串分割成字符串數組。

var host="?name=232&key=23";
host=host.split("?")
console.log(host)
["", "name=232&key=23"]

2 substring() 方法用於提取字符串中介於兩個指定下標之間的字符。

var host="?name=232&key=23";
host=host.substring(1)
console.log(host)
//name=232&key=23

var str = "hello world!";
var str1 = "wo";

3 indexOf() 方法:用於返回某個指定的字符串值在字符串中首次出現的位置。

  alert(str.indexOf(str1)) // 6

4 charAt() 方法:用於返回指定位置的字符。

  alert(str.charAt(0)) // h

5 slice() 方法:提取字符串的某個部分,並以新的字符串返回被提取的部分。

  alert(str.slice(2,5)) // llo。返回索引2-5但不包含5之間的字符

  alert(str.slice(2,-5)) // llo w。返回從索引2開始至倒數第五個位置但不包含其本身之間的字符。

  alert(str.slice(-5,-1)) // orld。返回倒數第五個位置至倒數第一個位置(不包含倒數第一個位置)之間的字符,且兩個參數均為負數時,第二個參數必須大於第一個參數

6 substr()方法:可在字符串中抽取從 start 下標開始的指定數目的字符。

  alert(str.substr(2,5)) // llo w。從索引2開始,返回5個字符

  alert(str.substr(-2,5)) // d!。即從倒數第二個字符開始返回5個字符,第一個參數可為負值,但第二個參數不可為負值

數組、字符串對象的各種方法