原文:http://h01mes.com/veteran-new...javascript
在javascript定義裏,字符串(string)不可修改類型,而數組(array)則是可修改類型。html
<head> <script> var str = "123"; str[0] = "0"; alert(str); var arr = [1, 2, 3]; arr[0] = "0"; alert(arr); </script> </head> <body> </body> </html>
結果是:java
123 0,1,3
順帶一提,字符串用 "", '', 或者 ``(用於多行定義)來表示,數組用[]。數組
更多例子:google
<head> <script> var str = "123"; str.length = 10; alert(str); var arr = [1, 2, 3]; arr.length = 10; alert(arr); alert(arr[3]); </script> </head> <body> </body>
運行結果:code
123 1,2,3,,,,,,, undefined
有趣的是,若是你強行改變數組的大小,javascript運行時會給數組內自動加上值undfined的元素。而字符串仍是不能用這種辦法修改。htm
若是一個字符串裏面包含特殊字符(好比,",雙引號原本是用來表示字符串開始和結束),咱們用來作轉義。ip
例子:ci
<html> <head> <script> alert("\""); alert("a\nb"); alert("a\tb"); </script> </head> <body> </body> </html>
運行結果:字符串
" a b a b
這裏,"用來表示",n表示換行,t表示製表符。在google裏面搜索"javascript special characters"能夠拿到完整的列表。
而且,咱們能夠使用轉義字符在字符串裏面直接寫ascII碼和Unicode。可是我暫時想不出來實在的用例,因此不作深刻討論。
咱們用+,或者字符串模板來鏈接字符串:
<html> <head> <script> var js = "javascript"; var message1 = "I like " + js; //using + alert(message1); var message2 = `and ${js}'s particularities`; //using string template alert(message2); </script> </head> <body> </body> </html>
運行結果:
I like javascript and javascript's particularities
若是是數組呢,用concat()
<html> <head> <script> var arr = ['a', 'b', 'c']; var added = arr.concat(['d', 'e', 'f']); alert(added); </script> </head> <body> </body> </html>
運行結果:
a,b,c,d,e,f
用[]
<html> <head> <script> var arr = ['a', 'b', 'c']; var str = "abc"; alert(arr[0]); alert(str[0]); </script> </head> <body> </body> </html>
運行結果:
a a
用indexOf()
<html> <head> <script> var arr = ['abc', 'xyz', 123, 789]; alert(arr.indexOf(123)); alert(arr.indexOf('xyz')); alert(arr.indexOf(789)); alert(arr.indexOf('abc')); var str = "abcxyz";//a=>0 b=>1 c=>2 x=>3 alert(str.indexOf('xyz')); </script> </head> <body> </body> </html>
運行結果:
2 1 3 0 3
不解釋。
用substring() 和 slice() ...
例子:
<html> <head> <script> var str = "abcxyz";//a=>0 b=>1 c=>2 x=>3 y=>4 z=>5 alert(str.substring(0, 5));// does not include 5(z) alert(str.substring(3));//start from 3(x) to the end var arr = ["a", "b", "c", "x", "y", "z"]; alert(arr.slice(0, 5));// does not include 5(z) alert(arr.slice(3));//start from 3(x) to the end </script> </head> <body> </body> </html>
運行結果:
abcxy xyz a,b,c,x,y x,y,z