codecamp

变量和赋值(Variables and assignment)

JavaScript中的变量在使用前必须先声明,否则会报错引用错误(Reference Error):

var foo; // 声明变量“foo”

赋值(Assignment)

你可以在声明变量的同时为其赋值:

var foo = 6;

你也可以给已经存在的变量重新赋值:

foo = 4; // 更改变量的值

复合赋值操作符(Compount assignment operators)

有很多复合赋值操作符,例如+=。下面的两个赋值操作等价:

x += 1;
x = x + 1;

标识符和变量名(Identifiers and variable names)

标识符就是事物的名字,在JavaScript中他们扮演不同的语法角色。例如,变量的名称是一个标识符。 大体上,标识符的第一个字符可以是任何Unicode字符、美元标志符($)或下划线(_)。后面可以是任意字符和数字。因此,下面全是合法的标识符:

arg0
_tmp
$elem
π

注意:首字符不能是数字,如果是数字的话,该如何区分是数字还是变量呢? 一些标识符是“保留关键字”——他们是语法的一部分,不能用作变量名:

arguments break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield

从技术上讲,下面三个标识符不是保留字,但也不应该作为变量名:

Infinity NaN undefined

深入阅读

Valid JavaScript variable names [by Mathias Bynens]

语法(Syntax)
值(Values)
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }