Home  >  Article  >  Web Front-end  >  简单介绍JavaScript中字符串创建的基本方法_基础知识

简单介绍JavaScript中字符串创建的基本方法_基础知识

WBOY
WBOYOriginal
2016-05-16 15:51:13968browse

创建一个字符串有几种方法。最简单的是用引号将一组字符包含起来,可以将其赋值给一个字符串变量。

   var myStr = "Hello, String!";



      可以用双引号或单引号将字符串包含,但要注意,作为界定字符串的一对引号必须是相同的,不能混用。


      像var myString = "Fluffy is a pretty cat.'; 这样的声明就是非法的。


      允许使用两种引号,使得某些操作变得简单,比如将一种嵌入另外一种:

 document.write("<img src='img/logo.jpg'    style="max-width:90%"  style="max-width:90%" alt="Logo">");

 

      我们在上面脚本创建了几个字符串,但本质上,它们并不是真正的字符串对象,准确地说,它们是字符串类型的值。要创建一个字符串对象,可使用如下语句:var strObj = new String("Hello, String!");


      使用typeof运算符查看会发现,上面的myStr类型为string,而strObj类型为object。
   
      如果想知道字符串的长度,使用其length属性:string.length。


      得到字符串的指定位置的字符使用方法:string.charAt(index);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn