JS Language
JS语言
This chapter will not give you a general introduction to JavaScript. There are other books out there for a general introduction to JavaScript, please visit this great side on Mozilla Developer Network.
本章不会对JavaScript进行一般性介绍。关于JavaScript的一般介绍,还有其他书籍,请访问Mozilla开发者网络并查看。
On the surface JavaScript is a very common language and does not differ a lot from other languages:
从表面上看,JavaScript是一种非常常见的语言,与其他语言没有太大区别:
function countDown() {
for(var i=0; i<10; i++) {
console.log('index: ' + i)
}
}
function countDown2() {
var i=10;
while( i>0 ) {
i--;
}
}
But be warned JS has function scope and not block scope as in C++ (see Functions and function scope).
但要警告的是,JS具有函数范围,而不是在C++的中阻塞作用域(参见函数和函数范围)。
The statements if ... else
, break
, continue
also work as expected. The switch case can also compare other types and not just integer values:
声明关键字if ... else
, break
, continue可以正常使用
。开关语句也可以类比其他语言,且不限于整数值:
function getAge(name) {
// switch over a string
switch(name) {
case "father":
return 58;
case "mother":
return 56;
}
return unknown;
}
JS knows several values which can be false, e.g. false
, 0
, ""
, undefined
, null
). For example, a function returns by default undefined
. To test for false use the ===
identity operator. The ==
equality operator will do type conversion to test for equality. If possible use the faster and better ===
strict equality operator which will test for identity (see Comparison operators).
JS知道几个可能为false的值,例如false
, 0
, ""
, undefined
, null
)。例如,函数默认返回undefined
值。要测试错误,请使用===标识运算符。==相等运算符将进行类型转换以测试相等性。如果可能,使用更快更好的===严格相等运算符,它将测试标识(请参阅比较运算符)。
Under the hood, javascript has its own ways of doing things. For example arrays:
其实,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
}
Also for people coming from C++ or Java which are used to an OO language JS just works differently. JS is not purely an OO language it is a so-called prototype based language. Each object has a prototype object. An object is created based on his prototype object. Please read more about this in the book Javascript the Good Parts by Douglas Crockford.
同样,对于来自面向对象的语言的C++或java的人来说,JS的工作方式也不同。JS不是一种纯粹的面向对象的语言,而是一种所谓的基于原型的语言。每个对象都有一个原型对象。根据他的原型对象创建一个对象。请在Douglas Crockford的《Javascript the Good Parts》一书中阅读更多关于这方面的内容。
To test some small JS snippets you can use the online JS Console or just build a little piece of QML code:
要测试一些小的JS代码片段,可以使用在线JS控制台,或者只构建一小段QML代码:
import QtQuick 2.5
Item {
function runJS() {
console.log("Your JS code goes here");
}
Component.onCompleted: {
runJS();
}
}