变量赋值

功能分类: Variables Applab JavaScript 少儿编程

为之前声明过的变量进行赋值。

为了在应用程序中处理数据,我们首先需要使用 var 来声明一个指定名称的变量,为其分配初始值并保存到内存里。程序 area = length * width; 被解释为 “将 length 与 width 相乘的结果赋值给变量 area ”。需要被赋值的变量放在 赋值操作符 = 的左侧。 赋值操作符 = 右侧可以为数字/字符串/布尔值,或返回数字/字符串/布尔值的方法,或返回数字/字符串/布尔值的表达式。

示例代码



// 声明变量、赋值,输出值信息到控制台日志
var x;
x = 5;
console.log("x has the value " + x)

示例代码:周长与面积 计算半径为 10 的圆的周长及面积,并输出结果到控制台日志。


// 计算半径为 10 的圆的周长及面积,并输出结果到控制台日志
var radius, circumference, area;
radius = 10;
circumference = 2 * Math.PI * radius;
area = Math.PI * radius * radius;
console.log("Circle radius 10 has circumference of " + circumference + " and area of " + area);

示例代码:Fibonacci 序列 编写代码生成 Fibonacci 序列的前 9 个数字。


// 编写代码生成 Fibonacci 序列的前 9 个数字
var termA, termB, termC;
termA = 1;
termB = 1;
termC = termA + termB;
console.log(termA + " " + termB + " " + termC);
termA = termB + termC;
termB = termC + termA;
termC = termA + termB;
console.log(termA + " " + termB + " " + termC);
termA = termB + termC;
termB = termC + termA;
termC = termA + termB;
console.log(termA + " " + termB + " " + termC);

示例代码:公告栏 收集信息并显示到公告栏。


// 收集信息并显示到公告栏
textLabel("myTextLabel", "Type a message and press press enter");
textInput("myTextInput", "");
var count;
count=1;
onEvent("myTextInput", "change", function(event) {
  var myText;
  myText = getText("myTextInput");
  write("Message #" + count + ": " + myText);
  setText("myTextInput", "");
  count = count + 1;
});

语法规则


x = ___;

参数说明

名称 类型 必需 参数描述
x 变量名称 Yes 通过使用这个名称,在程序里就可以使用这个变量。必须以字母开头,不能包含空格,可以包含字母、数字、减号 - 以及下划线 _ 。
___ 任意类型 Yes 赋值操作符 = 右侧可以为数字/字符串/布尔值,或返回数字/字符串/布尔值的方法,或返回数字/字符串/布尔值的表达式。

返回值

没有返回值。变量被赋值并保存在内存里。

提示说明

  • 在给变量赋值前,首先需要确保已使用 var 对变量进行了声明。
  • 可以在 赋值操作符 = 左右两侧同时使用同一个变量,比如经常被使用的计数代码如:count = count + 1;
  • = 是赋值操作符。== 是判断两个值是否相等的比较操作符。不要混淆哦!

查看更多少儿编程教程、JavaScript 介绍

返回文档首页