var person = { getName: function () { console.log(this); return this.name; //returnname; //定義name會往外開始找name這一個變數 } }; person.name = 'kevin'; var name = 'test'; console.log(person.getName()); //var name = 'test'; //呼叫方法之後就看不到了
決定 this 的關鍵不在於它屬於哪個物件,而是在於 function「呼叫的時機點」 當你透過物件呼叫某個方法 (method) 的時候,此時 this 就是那個物件 (owner object)
1 2 3 4 5 6 7 8 9 10
var foo = function() { this.count++; };
foo.count = 0;
for( var i = 0; i < 5; i++ ) { foo(); //undefined } console.log(foo.count) //還是0
Array常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
let arrs = [1, 4, 2, 3, 0]; //var newArr = arrs.map(v => v * 2) var newArr = arrs.map(function (v, index, arr) { console.log(index); return v * 2; })
//var filterArr = arrs.filter(val => val > 1); var filterArr = arrs.filter(function (val, index, arr) { return val > 1; });
//var sortArr = arrs.sort((a, b) => a - b); var sortArr = arrs.sort(function (a,b) { return a - b; }); console.log(newArr); // [2, 8, 4, 6, 0] console.log(filterArr); // [4, 2, 3] console.log(sortArr); //[0, 1, 2, 3, 4]
浮點數轉整數
根據定義在JS中的數字背後都是以浮點數的方式運行 There is no such thing as an int in Javascript. All Numbers are actually doubles behind the scenes,我們習慣上還是會把整數或浮點數方開來看。在stackoverflow有人發問如果要將浮點數轉型成整數,但不希望四捨五入可以怎麼做(Converting a double to an int in Javascript without rounding
),我們可以有下面的作法。
vartext = "A apple a day keeps the doctor away.I have pen , I have apple.Uh ! ApplePen!!"; console.log(text.match(/applezzs/ig)); console.log("123abc123zz23".match(/^\d.*3/g)); //123abc123zz23 greedy console.log("123abc123zz23".match(/^\d.*?3/g)); //123 var match = /(hello) (\S+)/.exec('This is a hello world!'); console.log(match); // ['hello world!', 'hello', 'world!']