位置:海鸟网 > IT > JavaScript >

JavaScript学习笔记 2-变量、字符串

变量

还是先看例子,内容很少,也很简单:
JavaScript变量练习(完整代码)
<html>
<head>
<script language="JavaScript">
<!-- hide me

// load up some variables
var secs_per_min = 60;
var mins_per_hour = 60;
var hours_per_day = 24;
var days_per_year = 365;
//当首次用一变量时,应以“var”申明。 尽管以var 作为变量申明严格说并不必要,但这是一个好习惯。
//对变量名大小写敏感

// do some calculations
var secs_per_day = secs_per_min * mins_per_hour * hours_per_day;
var secs_per_year = secs_per_day * days_per_year;

//here's how to use JavaScript to write out HTML
//这里介绍如何用JavaScript写变量和网页。
document.writeln("<b>The monkey dances ");
//可用document.writeln() 来写文本和网页中的HTML
document.writeln(secs_per_year);
document.writeln(" seconds per year.</b><p>");

// end hiding -->
</script>
</head>
</html>
字符串

一个字符串使用的小例:
JavaScript字符串练习(完整代码)
<html>
<head>
<script language="JavaScript">
<!-- hide me

// load up some variables
var nice_monkey = "The monkey smiles at you and recites Shakespeare.";
var bad_monkey = "The monkey scowls at you and burps.";
//申报变量时即给变量赋值,使它等于这些字符串,于是当你想写这些字符串时,你可写:

document.writeln(nice_monkey+"<br>");
var monkey = prompt("What's the monkey's name?", "The monkey");
//这里我们称为用户反馈提示方式,当它被调用时,启动一个对话框请求用户输入信息。用
//户完成后敲OK返回信息。在上行中返回信息放入其变量中。

var demanding="demands, no, insists upon receiving";
var tech=" a computer that won't crash, and a homemade brower!";
var techy_monkey = monkey + demanding + tech;

document.writeln(techy_monkey+"<br>");
document.writeln(techy_monkey.fontcolor('red'));
//这一句的意思是:将字符串 techy_monkey 用红色显示在屏幕上