Kiểu Dữ Liệu Trong JQuery | Background
Có thể bạn quan tâm
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
|
//
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 // 0Boolean Default
Kiểu String rỗng mặc định là false:
!"" // true !"hello" // false !"true" // false !new Boolean(false) // falseNumber
12 3.543Cá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 // falseVì 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.30000000000000004Math
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) // -1Parsing 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.1Numbers 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)) // trueKhi chia cho không, kết quả là Infinity:
1 / 0 // InfinityCả 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 // trueInteger
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 // 16Array 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:
!{} // falsePrototype
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 prototypeOptions
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] // 3Iteration
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, 2Cá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:
![] // falseArray<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", 3The 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 // trueContext, 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", 2Scope
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); // 0It 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(); // 1The 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
-
Ép Kiểu Trong JavaScript | Học Lập Trình JavaScript
-
Cách ép Kiểu Trong Javascript (chuyển đổi Kiểu Dữ Liệu) - Freetuts
-
Thay đổi Kiểu Dữ Liệu Trong Javascript - Viblo
-
Kiểu Dữ Liệu Trong JavaScript - Viblo
-
Làm Thế Nào để ép Kiểu Integer Cho Một Số Hoặc Một String Số Trong ...
-
Ép Kiểu Trong JavaScript - Lập Trình Từ Đầu
-
Cách Ép Kiểu String, Number, Boolean Trong Javascript
-
Cách Chuyển đổi Kiểu Dữ Liệu Trong Javascript - Techmaster
-
Number, String, Array Và Object Trong JavaScript - 200lab Education
-
Ép Kiểu Dữ Liệu Trong Java
-
Ép Kiểu Trong Java - Học Java Miễn Phí Hay Nhất - VietTuts
-
Ép Kiểu Trong C++ - Techacademy
-
Chuyển đổi Kiểu Dữ Liệu Trong Java - KungFu Tech
-
Ép Kiểu Int Sang Float Và Ngược Lại Trong C/C++ - Lập Trình Không Khó