老鸟学Javascript - 第二弹

原文:http://h01mes.com/veteran-new…

string 和 array

在javascript定义里,字符串(string)不可修正范例,而数组(array)则是可修正范例。

<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>

效果是:

123
0,1,3

顺带一提,字符串用 “”, ”, 或许 “(用于多行定义)来示意,数组用[]。

更多例子:

<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>

运转效果:

123
1,2,3,,,,,,,
undefined

风趣的是,假如你强行转变数组的大小,javascript运转时会给数组内自动加上值undfined的元素。而字符串照样不能用这类方法修正。

转义字符 \

假如一个字符串内里包括特别字符(比方,”,双引号本来是用来示意字符串最先和完毕),我们用来做转义。

例子:

<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。然则我临时想不出来着实的用例,所以不做深切议论。

衔接(Concatenation)

我们用+,或许字符串模板来衔接字符串:

<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
    原文作者:范锉
    原文地址: https://segmentfault.com/a/1190000010052207
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞