# JS语言
本章不会对JavaScript进行一般性介绍。 有其他书籍可以对JavaScript进行了一般性介绍,请访问Mozilla 开发者网络(Mozilla Developer Network) (opens new window)上的精彩内容。
从表面上看,JavaScript是一种非常通用的语言,与其他语言没有太大的区别:
function countDown() {
for(var i=0; i<10; i++) {
console.log('index: ' + i)
}
}
function countDown2() {
var i=10;
while( i>0 ) {
i--;
}
}
但请注意,JS具有函数作用域,而不是C++中的那样的块作用域(请参阅函数和函数作用域(Functions and function scope) (opens new window))。
语句if ... else
、break
、continue
也可以按预期工作。 switch case除了能够比较整数值外,还可以比较其他类型的值:
function getAge(name) {
// switch over a string
switch(name) {
case "father":
return 58;
case "mother":
return 56;
}
return unknown;
}
JS存在几个可能为假的值,例如:false
、0
、""
、undefined
、null
。 例如,一个函数默认返回undefined
。 要测试其是否为假,请使用恒等运算符===
。 相等运算符==
将进行类型转换以测试其相等性。 如果可能,请使用更快更好的===
严格相等运算符来测试其身份(请参阅 比较运算符(Comparison operators) (opens new window)。
在底层,javascript有自己的做事方式。 例如数组:
function doIt() {
var a = [] // empty arrays
a.push(10) // addend number on arrays
a.push("Monkey") // append string on arrays
console.log(a.length) // prints 2
a[0] // returns 10
a[1] // returns Monkey
a[2] // returns undefined
a[99] = "String" // a valid assignment
console.log(a.length) // prints 100
a[98] // contains the value undefined
}
同样,对于来自于C++或Java且习惯于面向对象语言的人来说,JS的工作方式也不同。 JS并不是纯粹的面向对象语言,它是一种所谓基于原型的语言。 每个对象都有一个原型对象,一个对象是根据它的原型对象创建的。 请在道格拉斯·克罗克福德的Javascript的优秀部分(Javascript the Good Parts by Douglas Crockford) (opens new window)一书中阅读更多相关的信息。
要测试一些小的JS片段,可以使用在线的JS 控制台(JS Console) (opens new window)或构建一小段如下的QML代码:
import QtQuick 2.5
Item {
function runJS() {
console.log("Your JS code goes here");
}
Component.onCompleted: {
runJS();
}
}