原文: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