截取數組:slice(startIndex,endIndex):
返回數組中指定開始位置倒結束位置的數組。不改變原數組內容。
另外還有一個重要的方法,插入、刪除或替換數組元素方法:
splice(startIndex,howmany,element1~elementX):會修改原數組內容。參數含義分別為:“指定開始位置”,“刪除多少個元素個數(可以為0)”,“添加到數組中的新元素(從startIndex下標開始)”。
相關運用
//題目一:"A[B]C[D]E[F]G"將其分為兩個數組,分別是 ACEG 和 [B][D][F].
代碼如下:
function QuestionFn1() {
var str = "A[B]C[D]E[F]G";
var oGetTwoArray = new GetTwoArray();
//取左右括號中的值
oGetTwoArray.GetLeftAndRightValue(str);
oGetTwoArray.GetNoLeftAndRightValue(str);
var array1 = oGetTwoArray.arrBetweenLeftRight;
var array2 = oGetTwoArray.arrNoLeftRight;
alert(array1.join(""));
alert(array2.join(""));
}
//找到左右括號的index
function GetTwoArray() {
this.indexLeft = 0; //左括號索引
this.indexRight = 0; //右括號索引
this.arrBetweenLeftRight = []; //數組:存放左右括號中的字母
this.arrNoLeftRight = []; //數組:存放沒有括號包圍的字母
//取左右括號中的值
this.GetLeftAndRightValue = function(str) {
//找到字符串中左括號的index
this.indexLeft = str.indexOf('[');
this.indexRight = str.indexOf(']');
//取括號中的值(包含括號)
var value = str.substring(this.indexLeft, this.indexRight + 1);
//存放到數組中
this.arrBetweenLeftRight.push(value);
//剩下的str
var restStr = str.substr(this.indexRight + 1);
//如果還有左右括號則繼續找
if (restStr.indexOf('[') != -1 && restStr.indexOf(']') != -1) {
this.GetLeftAndRightValue(restStr);
}
}
//取沒有左右括號包圍的值
this.GetNoLeftAndRightValue = function(str) {
//找到字符串中左括號的index
this.indexLeft = str.indexOf('[');
this.indexRight = str.indexOf(']');
//取沒有左右括號包圍的值(跟著右括號的第一個)
var value = str.substring(0, 1);
if (value != '[') { //因為第一個就有可能就是左括號
//存放到數組中
this.arrNoLeftRight.push(value);
}
//剩下的str
var restStr = str.substr(this.indexRight + 1);
//如果還有左右括號則繼續找
if (restStr.indexOf('[') != -1 && restStr.indexOf(']') != -1) {
this.GetNoLeftAndRightValue(restStr);
}
//剩下的沒有左右括號了,就全部添數組里去
else if (restStr.indexOf('[') == -1 && restStr.indexOf(']') == -1) {
this.arrNoLeftRight.push(restStr);
}
}
}
//題目二:有兩個有序整數數組,例如【1, 3, 5, 7, 9】和【2, 4, 6, 7, 8, 10, 13】,設計一個函數使兩個數組合并,并且剔除掉兩個數組里重復的元素.
代碼如下:
function QuestionFn2() {
var arr1 = [1, 3, 5, 7, 9];
var arr2 = [2, 4, 6, 7, 8, 10, 13];
新聞熱點
疑難解答
圖片精選