由於JS比較難掌握,所以我們會花多一點的時間來掌握它。那麼今天來說說js的數組和字符串。
數組
- 如何定義數組:
定義一個數組有3種方式
-
定義一個確定長度或者長度不定的數組(最常用的定義方式)
var 數組名稱=new Array(數組長度);
- 定義一個元素確定的數組:
var 數組名稱=new Array(元素,元素,元素..);
- 確定一個長度很短,已知確定元素:
var 數組名稱={元素,元素,元素...};
數組的主要屬性:
length
是長度屬性,返回數組的長度。
prototype
基本js每一個內置對象都會有該屬性,可以向對象增加屬性和方法。(博客最後分析哦~)
常用數組的方法(也叫函數):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
var array1=new Array("java","js","html","css");
var array2=new Array("籃球","足球","游泳");
document.write(array2.concat(array1));
//concat方法是將多組數組組合到一個數組,並返回結果
document.write("<hr/>");
//輸出橫線分割
document.write(array1.join("@"));
//join是將數組元素放到一個字符串裏,通過制定符號(這裏是@)連接。
document.write("<hr/>");
document.write(array1.pop());
//pop方法是刪除並且返回數組最後一個元素。
document.write("<hr/>");
document.write(array1.shift());
//shift表示刪除並且返回數組的第一個元素。
document.write("<hr/>");
document.write(array1.push("c++"));
//push方法表示在元素末尾添加一個元素或者多個元素,並返回新數組長度。
document.write("<hr/>");
document.write(array1.unshift("元素1","元素2"));
//unshift表示在數組開頭添加一個或者多個元素,並且返回新數組長度。
document.write("<hr/>");
document.write(array1.reverse());
//reverse表示顛倒數組中的元素
document.write("<hr/>");
document.write(array1.toString());
//toString表示將數組轉換爲字符串,並返回結果
document.write("<hr/>");
document.write(array1.slice(2,4));
//slice表示提取數組下表爲2到3的元素並返回結果
document.write("<hr/>");
document.write(array2.splice(1,2,"西瓜","蘋果"));
//splice表示刪除下標爲1到2的元素並添加新的元素。
document.write("<hr/>");
</script>
</html>
結果不太好演示太多了,大家實踐的話建議一條一條來,試一條註釋一條再試下一條。
字符串
字符串的定義方法:
- var 字符串名稱="字符串";
字符串的屬性:
length
屬性表示返回字符串的長度。
prototype
可以向對象增加屬性和方法。
常用字符串方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
var str1="我正在學習js,同時我也在學習java";
var str2="ilovestudy";
//定義字符串
document.write(str1.big());
//big方法是使字體變大
document.write("<hr/>");
document.write(str1.bold());
//bold方法是使字體加粗
document.write("<hr/>");
document.write(str1.italics());
//italics方法是使字體傾斜
document.write("<hr/>");
document.write(str1.charAt(2));
//charAt方法是返回在指定位置的字符(返回第2個字符)
document.write("<hr/>");
document.write(str1.charCodeAt(2));
//charCodeAt是反回在指定位置的字符的Unicode碼
document.write("<hr/>");
document.write(str1.concat(str2));
//concat方法是拼接字符串
document.write("<hr/>");
document.write(str1.indexOf("學習",5));
//返回字符串中檢索指定字符第一次出現的位置,(從下標爲5開始檢索)
document.write("<hr/>");
document.write(str1.lastIndexOf("學習",5));
//返回字符串中檢索指定字符最後一次出現的位置(從下標爲5之前檢索)
document.write("<hr/>");
document.write(str1.substr(2,3));
//substr從檢索開始提取指定數量的字符串(從下標爲2開始取3個字符串並返回值)
document.write("<hr/>");
document.write(str1.substring(2,5));
//substring從檢索開始下標提取字符串到終止值下標-1停止(從下標爲2到下標爲4取字符串並返回值)
document.write("<hr/>");
</script>
</html>
那麼關於prototype的知識咱請看下集,嘿嘿嘿~