Archive for the Javascript Category

Note: learning javascript using NodeJS

Posted in Javascript with tags , on 2016 年 01 月 11 日 by Kun-Yi

最近開始想跟上時代腳步 開始練一下Javascript 配合未來趨勢,底下是我看某些教材練習的片段, person 是一個 object 宣告 可以直接用for 去列舉屬性還蠻方便做很多meta programming 而整數的sort 從小排到大 則是跟C 語言的qsort 一樣要提供一個compare function 只是這裡是沒有名稱的形式 而且傳回定義同C語言

var person = {
name : “Jules Verne",
job : “Author",
year_of_birth : 1828,
year_of_death : 1905
},
prop;

for (prop in person)
{
console.log(“His " + prop + " is " + person[prop]);
}

var arr = [5, 2, 3, 4, 1];

arr.sort(function (a, b) {
console.log (“a:" + a + “, b:" + b + “, a – b:" + (a – b));
return a – b;
});
console.log(arr);

執行結果如下

His name is Jules Verne
His job is Author
His year_of_birth is 1828
His year_of_death is 1905
a:5, b:2, a – b:3
a:5, b:3, a – b:2
a:2, b:3, a – b:-1
a:5, b:4, a – b:1
a:3, b:4, a – b:-1
a:5, b:1, a – b:4
a:4, b:1, a – b:3
a:3, b:1, a – b:2
a:2, b:1, a – b:1
[ 1, 2, 3, 4, 5 ]