Kiểu Dữ Liệu Trong JQuery | Background

From jQuery JavaScript Library

JavaScript cung cấp một số kiểu dữ liệu. Thêm vào đó là một số loại như Seletor,  Event, và tất cả mội thứ bạn muốn biết về functions.

Contents

  • 1 String
    • 1.1 Quoting
    • 1.2 Built-in Methods
    • 1.3 Length Property
    • 1.4 Boolean Default
  • 2 Number
    • 2.1 Boolean Default
    • 2.2 Math
    • 2.3 Parsing Numbers
    • 2.4 Numbers to Strings
    • 2.5 NaN and Infinity
    • 2.6 Integer
    • 2.7 Float
  • 3 Boolean
  • 4 Object
    • 4.1 Dot Notation
    • 4.2 Array Notation
    • 4.3 Iteration
    • 4.4 Boolean default
    • 4.5 Prototype
  • 5 Options
  • 6 Array
    • 6.1 Iteration
    • 6.2 Boolean Default
    • 6.3 Array<Type> Notation
  • 7 Map
  • 8 Function
    • 8.1 Arguments
    • 8.2 Context, Call and Apply
    • 8.3 Scope
    • 8.4 Closures
    • 8.5 Proxy Pattern
  • 9 Callback
  • 10 Selector
  • 11 Event
  • 12 Element

//

String

"I'm a String in JavaScript!" 'So am I!'

A string trong JavaScript là một kiểu immutable object nghĩa là nó có thể chứa một, nhiều hoặc không chứa kí tự nào.

Kiểu của string là  “string”.

typeof "some string"; // "string"

Quoting(dấu nháy)

Một string có thể được định nghĩa sử dụng dấu nháyđơn hoặc ngoặc kép. Bạn có thể đặt các dấu nháyđơn trong cặp dấu nháy kép, và ngược lại. Để đặt dấu cùng loại bạn phải sử dụng backslash để escapse.

"You make 'me' sad." 'Holy "cranking" moses!' "<a href=\"home\">Home</a>"

Built-in Methods(các phương thức có sẵn)

Một string trong JavaScript có build sẵn một số phương thức để cập nhật chính nó, kiểu dữ liệu trả về luôn là kiểu string mới, mảng hoặc một số kiểu dữ liệu khác của js.

"hello".charAt(0) // "h" "hello".toUpperCase() // "HELLO" "Hello".toLowerCase() // "hello" "hello".replace(/e|o/g, "x") // "hxllx" "1,2,3".split(",") // ["1", "2", "3"]

Length Property(thuộc tính length)

Tất cả các string đều có thuộc tính length.

"Hello".length // 5 "".length // 0

Boolean Default

Kiểu String rỗng mặc định là false:

 !"" // true  !"hello" // false  !"true" // false  !new Boolean(false) // false

Number

12 3.543

Các số trong JavaScript là double có chiều dài 64-bit(8bytes). Chúng kiểu immutable, chỉ là string. Tất cả các toán tử cơ bản trong c như: (+, -, *, /, %, =, +=, -=, *=, /=, ++, –).

Kiểu của số là “number”.

typeof 12 // "number" typeof 3.543 // "number"

Boolean Default

Nếu một số là không thì default là false:

 !0 // true  !1 // false  !-1 // false

Vì số trong javascript là kiểu double nên giá trị trả về phía dưới không phải là bị lỗi.

0.1 + 0.2 // 0.30000000000000004

Math

JavaScript cung cấp một số công cụ để làm việc với số trong Math object.

Math.PI // 3.141592653589793 Math.cos(Math.PI) // -1

Parsing Numbers

parseInt và parseFloat giúp chuyển kiểu string sang kiểu số.  cả hai hàm đều thực hiện một số chuyển dạng sai, nếu không xác định rõ kiểu:

parseInt("123") = 123 (hệ thập phân) parseInt("010") = 8 (hệ bát phân) parseInt("0xCAFE") = 51966 (hệ thập luc phân) parseInt("010", 10) = 10 (xác định chuyển sang hệ thập phân) parseInt("11", 2) = 3 (xác định hệ nhị phân) parseFloat("10.10") = 10.1

Numbers to Strings

Khi bạn cộng số vào chuỗi, thì kết quả luôn luôn là chuỗi. Toán tử  cộng giống như  số, vì thế hãy cẩn thận: nếu bạn muốn cộng số giống như chuỗi, hãy đặt chúng vào dấu nháy, nếu muốn xử lý công như số thì hãy đặt chúng vào dấu ngoặc đơn:

"" + 1 + 2; // "12" "" + (1 + 2); // "3" "" + 0.0000001; // "1e-7" parseInt(0.0000001); // 1 (!)

Hoặc sử dụng các function có trong lớp String để chuyển sang chuỗi:

String(1) + String(2); //"12" String(1 + 2); //"3"

NaN và Infinity

Khi chuyển giá trị của một biến không phải là số sang số thì kết quả sẽ là NaN. isNaN giúp xác định các trường hợp này:

parseInt("hello", 10) // NaN isNaN(parseInt("hello", 10)) // true

Khi chia cho không, kết quả là Infinity:

1 / 0 // Infinity

Cả NaN and Infinity đều là dạng của “number”:

typeof NaN // "number" typeof Infinity // "number"

Chú ý rằng NaN cho kết quả khác với các loại khác khi so sánh với nhau:

NaN == NaN // false (!)

Nhưng:

Infinity == Infinity // true

Integer

Integer là một loại Number, Khi được xác định rõ, hoặc không phải là số thực.

Float

float cũng là một loại Number, khi xác định rõ hoặc khi trỏ đến số thực.

Boolean

Kiểu trong JavaScript là true hoặc false:

if ( true ) console.log("always!") if ( false ) console.log("never!")

Khi một lựa chọn được xác định là boolean, thường như thế này:

$("...").somePlugin({ hideOnStartup: true, onlyOnce: false });

Object(Đối tượng)

Mọi thứ trong JavaScript là một object. Cách dễ dàn nhất để tạo object là từ khóa Object:

var x = {}; var y = { name: "Pete", age: 15 };

Type của một object là “object”:

typeof {} // "object"

Dot Notation(dấu chấm)

Có thể truy cập thuộc tính của object bằng dấu chấm:

y.name // "Pete" y.age // 15 x.name = y.name + " Pan" // "Pete Pan" x.age = y.age + 1 // 16

Array Notation

Hoặc bạn có thể truy cập và cập nhật các thuộc tính sử dùng ký hiệu mảng cho phép bạn tự động chọn thuộc tính:

var operations = { increase: "++", decrease: "--" } var operation = "increase"; operations[operation] // "++"; operations["multiply"] = "*"; // "*"

Iteration

Lặp qua các object dễ dàng với vòng lặp loop:

var obj = { name: "Pete", age: 15 }; for(key in obj) { alert("key is "+[key]+", value is "+obj[key]); }

Chú ý rằng vòng lặp có thể được kế thừa từ Object.prototype (see Object.prototype is verboten), vì vậy bạn nên cẩn thận khi dùng các thư viện khác chung với jquery, nhất là Prototype.

jQuery cung cấp các function each(each-function) dùng để lặp qua các thuộc tính của đối tượng, cũng như các phần tử của mảng:

jQuery.each(obj, function(key, value) { console.log("key", key, "value", value); });

Mặt hạn chế là các phương thưc callback được gọi trên mỗi giá trị, vì vậy bạn sẽ mất ngữ cảnh của đối tượng đang thao tác. Chi tiết hãy xem ví dụ ở các function sau.

Boolean default

Một đối tượng, không có vấn đề gì khi có hoặc không có thuộc tính, vì mặc định là false:

 !{} // false

Prototype

Tất cả các đối tượng đề có một thuộc tính chung là prototype. Bất cứ khi nào trình thông dịch cũng tìm thuộc tính này,  Nó cũng kiểm tra thuộc tính này.  jQuery sử dụng thuộc tính này để thêm các method cho các thể hiện của JQuery.

var form = $("#myform"); form.clearForm; // undefined form.fn.clearForm = function() { return this.find(":input").each(function() { this.value = ""; }).end(); }; form.clearForm() // works for all instances of jQuery objects, because the new method was added to the prototype

Options

Options trong jQuery là các đối tượng  JavaScript. Bất cứ khi nào  Options cũng được đề cập như là một loại ữ liệu, các đồi tượng này và tất cả các thuộc tính của nó đều không bắt buộc sử dụng. Cũng có một số ngoại lệ.  Đối tượng nổi bật nhất của jQuery về sử dụng Options là các phương thức  AJAX. Gần như tất cả Plugin trong JQuery đều cung cấp các API cho option: Chúng hoạt động không cần bất cứ sự cài đặt nào, cho phép người dùng xác định bất kỳ cái gì mà họ cần.

Hãy xem ví dụ sau về  form plugin. Nó cho phép gởi một form qua  AJAX với code rất đơn giản:

$("#myform").ajaxForm();

Nó sẻ dụng thuộc tính action của form trong html để gán mặc đinh cho AJAX khi gởi đi. Bạn có thể định nghĩa lại nếu muốn bằng cách thay đổi giá trị của các option:

$("#myform").ajaxForm({ url: "mypage.php", type: "POST" });

Array

Arrays trong JavaScript là danh sách có thể thay đổi giá trị với các phương thưc có sẵn mà JS cung cấp. Định nghĩa mảng như sau:

var x = []; var y = [1, 2, 3];

Type của một array là “object”:

typeof []; // "object" typeof [1, 2, 3]; // "object"

Đọc và cập nhật các phần tử của mảng sử dụng kí hiệu mảng:

x[0] = 1; y[2] // 3

Iteration

Một array có thuộc tính length rất hữu ích khi lặp:

for (var i = 0; i < a.length; i++) { // Do something with a[i] }

Khi thực thi, bạn chỉ nên đọc length một lần(như sau), để tăng tốc độ của vòng lặp.

for (var i = 0, j = a.length; i < j; i++) { // Do something with a[i] }

Một cách khác sử dụng loop để đọc các phần tử của mảng là bạn bỏ kí hiệu mảng trong thân của vòng lặp, gán trong phần điều kiện(như sau):(Chú ý: nó sẽ không hoạt động nếu mảng chứa chuỗi 0(không) hoặc chuỗi rỗng)!

for (var i = 0, item; item = a[i]; i++) { // Bạn chỉ cần thao tác trên item }

jQuery cung cấp each-function để lặp qua các phần tử của mảng, cũng như thuộc tính của đối tượng:

var x = [1, 2, 3]; jQuery.each(x, function(index, value) { console.log("index", index, "value", value); });

Mặt hạn chế là các phương thức callback chỉ có hiệu lực trên mỗi phần tử hoặc thuộc tính mà nó lặp qua.

Thuộc tính length cũng có thể được sử dụng  để thêm các phần tử vào cuối mảng:

var x = []; x.push(1); x[x.length] = 2; x // 1, 2

Các phương thức khác là reverse, join, shift, unshift, pop, slice, splice and sort:

var x = [0, 3, 1, 2]; x.reverse() // [2, 1, 3, 0] x.join(" – ") // "2 - 1 - 3 - 0" x.pop() // [2, 1, 3] x.unshift(-1) // [-1, 2, 1, 3] x.shift() // [2, 1, 3] x.sort() // [1, 2, 3] x.splice(1, 2) // [2, 3]

Chú ý: Phương thức .unshift() không trả về thuộc tính length trong Internet Explorer.

Boolean Default

Một mảng có thể có phần tử hoặc không, nhưng không bao giờ có default là false:

 ![] // false

Array<Type> Notation

Trong jQuery API bạn thường thấy từ khóa  Array<Type>:

dragPrevention Array<String>

Khai báo này chỉ định rằng Một phương thức mà tham số có thể là mảng, và có thể xác định loại dữ liệu mà user mong đợi.

Map

Loại dữ liệu này được sử dụng trong các hàm AJAX, để chứa data cho request. Kiểu dữ liệu này có thể là String, Một mảng array<Form elements>, hoặc một đối tượng trong JQuery với các cặp keys/values. Cuối cùng, Nó có thể gán cho nhiều giá trị cho một key bởi gán một mảng cho key đó.

{'key[]':['valuea','valueb']}

Code phía server tương ứng là (Trong PHP):

$_REQUEST['key'][0]="valuea"; $_REQUEST['key'][1]="valueb";

Function(Hàm)

Một hàm trong  JavaScript có thể có tên hoặc không. Một hàm không tên(An anonymous function) có thể được gán cho biến hoặc truyề tham số vào các phương thức khác.

function named() {} var handler = function() {}

Có rất nhiều hàm không tên (anonymous functions) trong jQuery code:

$(document).ready(function() {}); $("a").click(function() {}); $.ajax({ url: "someurl.php", success: function() {} });

type của một hàm là  “function”.

Arguments(Tham số)

Bên trong hàm có một số biến từ ngoài truyền vào gọi là tham số, Nó giống như một mảng mà trong đó có thuộc tính length, Nhưng không có các phương thức build sẵn cho mảng.

function log(x) { console.log(typeof x, arguments.length); } log(); // "undefined", 0 log(1); // "number", 1 log("1", "2", "3"); // "string", 3

The arguments object also has a callee property, which refers to the function you’re inside of. For instance:

var awesome = function() { return arguments.callee } awesome() == awesome // true

Context, Call and Apply

In JavaScript, the variable “this” always refers to the current context. By default, “this” refers to the window object. Within a function this context can change, depending on how the function is called.

All event handlers in jQuery are called with the handling element as the context.

$(document).ready(function() { // this refers to window.document }); $("a").click(function() { // this refers to an anchor DOM element });

You can specify the context for a function call using the function-built-in methods call and apply. The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.

function scope() { console.log(this, arguments.length); } scope() // window, 0 scope.call("foobar", [1,2]); // "foobar", 1 scope.apply("foobar", [1,2]); // "foobar", 2

Scope

In JavaScript, all variables defined inside a function are only visible inside that function scope. Consider the following example:

// global var x = 0; (function() { // private var x = 1; console.log(x); // 1 })(); console.log(x); // 0

It defines a variable x in the global scope, then defines an anonymous function and executes it immediately (the additional parentheses are required for immediate execution). Inside the function another variable x is defined with a different value. It is only visible within that function and doesn’t overwrite the global variable.

Closures

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. In the following example, the variable counter is visible within the create, increment, and print functions, but not outside of them.

function create() { var counter = 0; return { increment: function() { counter++; }, print: function() { console.log(counter); } } } var c = create(); c.increment(); c.print(); // 1

The pattern allows you to create objects with methods that operate on data that isn’t visible to the outside—the very basis of object-oriented programming.

Proxy Pattern

Combining the above knowledge gives you as a JavaScript developer quite a lot of power. One way to combine that is to implement a proxy pattern in JavaScript, enabling the basics of aspect-oriented programming (AOP):

(function() { // log all calls to setArray var proxied = jQuery.fn.setArray; jQuery.fn.setArray = function() { console.log(this, arguments); return proxied.apply(this, arguments); }; })();

The above wraps its code in a function to hide the “proxied”-variable. It saves jQuery’s setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won’t be able to notice the difference between the original and the proxied method.

Callback

A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. jQuery’s event system uses such callbacks everywhere:

$("body").click(function(event) { console.log("clicked: " + event.target); });

Most callbacks provide arguments and a scope. In the event-handler example, the callback is called with one argument, an Event. The scope is set to the handling element, in the above example, document.body.

Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false:

$("#myform").submit(function() { return false; });

Instead of always returning false, the callback could check fields of the form for validity, and return false only when the form is invalid.

Selector

A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most cases, the DOM document present in all browsers, but can also be a XML document received via AJAX.

The selectors are a composition of CSS and custom additions. XPath selectors are available as a plugin.

All selectors available in jQuery are documented on the Selectors API page.

There are lot of plugins that leverage jQuery’s selectors in other ways. The validation plugin accepts a selector to specify a dependency, whether an input is required or not:

emailrules: { required: "#email:filled" }

This would make a checkbox with name “emailrules” required only if the user entered an email address in the email field, selected via its id, filtered via a custom selector “:filled” that the validation plugin provides.

If Selector is specified as the type of an argument, it accepts everything that the jQuery constructor accepts, eg. Strings, Elements, Lists of Elements.

Event

jQuery’s event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

Those properties are all documented, and accompanied by examples, on the Event page.

Element(Phần tử)

Một phần tử trong Document Object Model (DOM) luôn có các thuộc tính(attributes), text và phần tử con(children). Nó cung cấp các phương thức để duyệt các phần tử cha, phần tử con và truy cập đến các thuộc tính của chính nó.

Bất cứ  khi nào bạn sử dụng phương thức each, ngữ cảnh của phương thức gọi trở về luôn được được gán cho các phần tử của DOM.

Some properties of DOM elements are quite consistent among browsers. Consider this example of a simple on-blur-validation:

$(":text").blur(function() { if(!this.value) { alert("Please enter some text!"); } });

Bạn có thể dùng $(this).val() thay vì this.value để truy cập tới giá trị của input.

Retrieved from “http://docs.jquery.com/Types“

Từ khóa » ép Kiểu Float Trong Javascript