diff options
Diffstat (limited to 'files/vi/web')
232 files changed, 50430 insertions, 0 deletions
diff --git a/files/vi/web/accessibility/aria/aria_live_regions/index.html b/files/vi/web/accessibility/aria/aria_live_regions/index.html new file mode 100644 index 0000000000..bbeee0897f --- /dev/null +++ b/files/vi/web/accessibility/aria/aria_live_regions/index.html @@ -0,0 +1,259 @@ +--- +title: ARIA live regions +slug: Web/Accessibility/ARIA/ARIA_Live_Regions +translation_of: Web/Accessibility/ARIA/ARIA_Live_Regions +--- +<p>Sử dụng JavaScript, nó có thể thay đổi vài phần trong trang web mà không yêu cầu tải lại trang — lấy ví dụ, để cập nhật danh sách kết quả tìm kiếm ngay lập tức, hoặc để hiển thị một cảnh báo hay thông báo mà không bắt người dùng phải tương tác. Mặc dù những thay đổi này có thể nhìn thấy đối với người dùng, nó lại có thể không rõ ràng với những người cần sự hỗ trợ của công nghệ trợ năng. ARIA live regions giúp xử lý điều này bằng <span class="tlid-translation translation" lang="vi"><span title="">việc cung cấp một cách để lập trình các thay đổi nội dung động có thể được nhận diện bởi các công nghệ trợ năng.</span></span></p> + +<div class="note"> +<p><span class="tlid-translation translation" lang="vi"><span title=""><strong>Lưu ý:</strong> Các công nghệ trợ năng sẽ thông báo các thay đổi trong nội dung của một khu vực trực tiếp.</span> <span title="">Khu vực trực tiếp trước hết phải hiện diện (và thường trống), để trình duyệt và công nghệ hỗ trợ nhận thức được điều đó.</span> <span title="">Mọi thay đổi sau đó sẽ được thông báo.</span></span></p> + +<p>Đơn giản chỉ cần thêm vào thuộc tính <code>aria-live</code> hoặc thuộc tính chuyên biệt <code>role</code> (như là <code>role="alert"</code>) trong markup ban đầu chưa có hoạt động.</p> + +<p>Dynamically adding an element with an <code>aria-live</code> attribute or specialized <code>role</code> to the document also won't result in any announcement by assistive technologies (as, at that point, the browser/assistive technologies are not aware of the live region yet, so cannot monitor it for changes).</p> + +<p>Always make sure that the live region is present in the document first, and only then dynamically add/change any content.</p> +</div> + +<h2 id="Simple_live_regions"><span class="mw-headline" id="Live_Region_State">Simple live regions</span></h2> + +<p>Dynamic content which updates without a page reload is generally either a region or a widget. Simple content changes which are not interactive should be marked as live regions. Below is a list of each related ARIA live region property with a description.</p> + +<ol> + <li><code><strong>aria-live</strong></code>: The <code>aria-live=POLITENESS_SETTING</code> is used to set the priority with which screen reader should treat updates to live regions - the possible settings are: <code>off</code>, <code>polite</code> or <code>assertive</code>. The default setting is <code>off</code>. This attribute is by far the most important.</li> + <li> + <p class="comment"><code><strong>aria-controls</strong></code>: The <code>aria-controls=[IDLIST]</code> is used to associate a control with the regions that it controls. Regions are identified just like an <code>id</code> in a <code>div</code>, and multiple regions can be associated with a control using a space, e.g. <code>aria-controls="myRegionID1 myRegionsID2"</code>.</p> + + <div class="warning">Not known if the aria-controls aspect of live regions is implemented in current ATs, or which. Needs research.</div> + </li> +</ol> + +<p>Normally, only <code>aria-live="polite"</code> is used. Any region which receives updates that are important for the user to receive, but not so rapid as to be annoying, should receive this attribute. The screen reader will speak changes whenever the user is idle.</p> + +<p>For regions which are not important, or would be annoying because of rapid updates or other reasons, silence them with <code>aria-live="off"</code>.</p> + +<h3 id="Dropdown_box_updates_useful_onscreen_information">Dropdown box updates useful onscreen information</h3> + +<p>A website specializing in providing information about planets provides a dropdown box. When a planet is selected from the dropdown, a region on the page is updated with information about the selected planet.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html notranslate"><fieldset> + <legend>Planet information</legend> + <label for="planetsSelect">Planet:</label> + <select id="planetsSelect" aria-controls="planetInfo"> + <option value="">Select a planet&hellip;</option> + <option value="mercury">Mercury</option> + <option value="venus">Venus</option> + <option value="earth">Earth</option> + <option value="mars">Mars</option> + </select> + <button id="renderPlanetInfoButton">Go</button> +</fieldset> + +<div role="region" id="planetInfo" aria-live="polite"> + <h2 id="planetTitle">No planet selected</h2> + <p id="planetDescription">Select a planet to view its description</p> +</div> + +<p><small>Information courtesy <a href="https://en.wikipedia.org/wiki/Solar_System#Inner_Solar_System">Wikipedia</a></small></p> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js notranslate">const PLANETS_INFO = { + mercury: { + title: 'Mercury', + description: 'Mercury is the smallest and innermost planet in the Solar System. It is named after the Roman deity Mercury, the messenger to the gods.' + }, + + venus: { + title: "Venus", + description: 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.' + }, + + earth: { + title: "Earth", + description: 'Earth is the third planet from the Sun and the only object in the Universe known to harbor life.' + }, + + mars: { + title: "Mars", + description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries a name of the Roman god of war, and is often referred to as the "Red Planet".' + } +}; + +function renderPlanetInfo(planet) { + const planetTitle = document.querySelector('#planetTitle'); + const planetDescription = document.querySelector('#planetDescription'); + + if (planet in PLANETS_INFO) { + planetTitle.textContent = PLANETS_INFO[planet].title; + planetDescription.textContent = PLANETS_INFO[planet].description; + } else { + planetTitle.textContent = 'No planet selected'; + planetDescription.textContent = 'Select a planet to view its description'; + } +} + +const renderPlanetInfoButton = document.querySelector('#renderPlanetInfoButton'); + +renderPlanetInfoButton.addEventListener('click', event => { + const planetsSelect = document.querySelector('#planetsSelect'); + const selectedPlanet = planetsSelect.options[planetsSelect.selectedIndex].value; + + renderPlanetInfo(selectedPlanet); +}); +</pre> + +<p>{{EmbedLiveSample('Dropdown_box_updates_useful_onscreen_information', '', 350)}}</p> + +<p>As the user selects a new planet, the information in the live region will be announced. Because the live region has <code>aria-live="polite"</code>, the screen reader will wait until the user pauses before announcing the update. Thus, moving down in the list and selecting another planet will not announce updates in the live region. Updates in the live region will only be announced for the planet finally chosen.</p> + +<p>Here is a screenshot of VoiceOver on Mac announcing the update (via subtitles) to the live region:</p> + +<p><img alt="A screenshot of VoiceOver on Mac announcing the update to a live region. Subtitles are shown in the picture." src="https://mdn.mozillademos.org/files/15815/Web_Accessibility_ARIA_ARIA_Live_Regions.png" style="height: 573px; width: 800px;"></p> + +<h2 id="Preferring_specialized_live_region_roles">Preferring specialized live region roles</h2> + +<p>In the following well-known predefined cases it is better to use a specific provided "live region role":</p> + +<table style="width: 100%;"> + <thead> + <tr> + <th scope="col">Role</th> + <th scope="col">Description</th> + <th scope="col">Compatibility Notes</th> + </tr> + </thead> + <tbody> + <tr> + <td>log</td> + <td>Chat, error, game or other type of log</td> + <td>To maximize compatibility, add a redundant <code>aria-live="polite"</code> when using this role.</td> + </tr> + <tr> + <td>status</td> + <td>A status bar or area of the screen that provides an updated status of some kind. Screen reader users have a special command to read the current status.</td> + <td>To maximize compatibility, add a redundant <code>aria-live="polite"</code> when using this role.</td> + </tr> + <tr> + <td>alert</td> + <td>Error or warning message that flashes on the screen. Alerts are particularly important for client side validation notices to users. (TBD: link to ARIA form tutorial with aria info)</td> + <td>To maximize compatibility, some people recommend adding a redundant <code>aria-live="assertive"</code> when using this role. However, adding both <code>aria-live</code> and <code>role="alert"</code> causes double speaking issues in VoiceOver on iOS.</td> + </tr> + <tr> + <td>progressbar</td> + <td>A hybrid between a widget and a live region. Use this with aria-valuemin, aria-valuenow and aria-valuemax. (TBD: add more info here).</td> + <td></td> + </tr> + <tr> + <td>marquee</td> + <td>for text which scrolls, such as a stock ticker.</td> + <td></td> + </tr> + <tr> + <td>timer</td> + <td>or any kind of timer or clock, such as a countdown timer or stopwatch readout.</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Advanced_live_regions">Advanced live regions</h2> + +<p>(TBD: more granular information on the support of the individual attributes with combinations of OS/Browser/AT).</p> + +<p>General support for Live Regions was added to JAWS on version 10.0. In Windows Eyes supports Live Regions since version 8.0 "for use outside of Browse Mode for Microsoft Internet Explorer and Mozilla Firefox". NVDA added some basic support for Live Regions for Mozilla Firefox back in 2008 and was improved in 2010 and 2014. In 2015, basic support was also added for Internet Explorer (MSHTML).</p> + +<p>The Paciello Group has some <a href="https://www.paciellogroup.com/blog/2014/03/screen-reader-support-aria-live-regions/">information about the state of the support of Live Regions </a>(2014). Paul J. Adam has researched<a href="http://pauljadam.com/demos/aria-atomic-relevant.html"> the support of Aria-Atomic and Aria-Relevant</a> in particular. </p> + +<ol> + <li><code><strong>aria-atomic</strong></code>: The <code>aria-atomic=BOOLEAN</code> is used to set whether or not the screen reader should always present the live region as a whole, even if only part of the region changes. The possible settings are: <code>false</code> or <code>true</code>. The default setting is <code>false</code>.</li> + <li><code><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-relevant_attribute" title="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-relevant_attribute"><strong>aria-relevant</strong></a></code>: The <code>aria-relevant=[LIST_OF_CHANGES]</code> is used to set what types of changes are relevant to a live region. The possible settings are one or more of: <code>additions</code>, <code>removals</code>, <code>text</code>, <code>all</code>. The default setting is: <code>additions text</code>.</li> + <li><code><strong>aria-labelledby</strong></code>: The <code>aria-labelledby=[IDLIST]</code> is used to associate a region with its labels, similar to aria-controls but instead associating labels to the region. and label identifiers are separated with a space.</li> + <li><code><strong>aria-describedby</strong></code>: The <code>aria-describedby=[IDLIST]</code> is used to associate a region with its descriptions, similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space.</li> +</ol> + +<h3 id="Advanced_use_case_Clock"><span class="mw-headline" id="Use_Case:_Clock">Advanced use case: Clock</span></h3> + +<p>As an illustration of <code>aria-atomic</code>, consider a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time simply overwriting the current content.</p> + +<pre class="notranslate"><div id="clock" role="timer" aria-live="polite"></div> +</pre> + +<pre class="brush: js notranslate">/* basic JavaScript to update the clock */ + +setInterval(function() { + var now = new Date(); + document.getElementById('clock').innerHTML = "Time: " + now.getHours() + ":" + ("0"+now.getMinutes()).substr(-2); +}, 60000); +</pre> + +<p>The first time the function executes, the entirety of the string that is added will be announced. On subsequent calls, only the parts of the content that changed compared to the previous content will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users.</p> + +<p>One way around this would be to first clear the contents of the live region, and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates.</p> + +<p><code>aria-atomic="true"</code> ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "Time: 17:34").</p> + +<pre class="notranslate"><div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> +</pre> + +<div class="note"> +<p><strong>Note</strong>: As observed, setting/updating the innerHTML again would cause the whole text to be read again, whether or not you set aria-atomic="true", so the above Clock example does not work as expected.</p> +</div> + +<p class="syntaxbox">A working example of a simple year control for better understanding:</p> + +<pre class="syntaxbox notranslate"><div id="date-input"> + <label>Year: + <input type="text" id="year" value="1990" onblur="change(event)"/> + </label> +</div> + +<div id="date-output" aria-live="polite"> + The set year is: + <span id="year-output">1990</span> +</div></pre> + +<p class="syntaxbox"></p> + +<pre class="syntaxbox notranslate">function change(event) { + var yearOut = document.getElementById("year-output"); + switch (event.target.id) { + case "year": + yearOut.innerHTML = event.target.value; + break; + default: + return; + } +};</pre> + +<p class="syntaxbox"></p> + +<p>Without <code>aria-atomic="true" </code>the screenreader announces only the changed value of year.</p> + +<p>With <code>aria-atomic="true"</code>, the screenreader announces "The set year is: <em>changedvalue</em>"</p> + +<h3 id="Advanced_use_case_Roster"><span class="mw-headline" id="Use_Case:_Roster">Advanced use case: Roster</span></h3> + +<p>A chat site would like to display a list of users currently logged in. Display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload).</p> + +<pre class="notranslate"><ul id="roster" aria-live="polite" aria-relevant="additions removals"> + <!-- use JavaScript to add remove users here--> +</ul> +</pre> + +<p>Breakdown of ARIA live properties:</p> + +<ul> + <li><code>aria-live="polite"</code> indicates that the screen reader should wait until the user is idle before presenting updates to the user. This is the most commonly used value, as interrupting the user with "assertive" might interrupt their flow.</li> + <li><code>aria-atomic</code> is not set (<code>false</code> by default) so that only the added or removed users should be spoken and not the entire roster each time.</li> + <li><code>aria-relevant="additions removals"</code> ensures that both users added or removed to the roster will be spoken.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles">ARIA roles</a></li> +</ul> diff --git a/files/vi/web/accessibility/aria/index.html b/files/vi/web/accessibility/aria/index.html new file mode 100644 index 0000000000..b7587c76b0 --- /dev/null +++ b/files/vi/web/accessibility/aria/index.html @@ -0,0 +1,136 @@ +--- +title: ARIA +slug: Web/Accessibility/ARIA +tags: + - ARIA + - Accessibility + - HTML + - NeedsTranslation + - TopicStub +translation_of: Web/Accessibility/ARIA +--- +<p class="summary"><span class="seoSummary">Accessible Rich Internet Applications <strong>(ARIA) </strong>is a set of attributes that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities. </span></p> + +<p><span class="seoSummary">It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies</span> when there is not otherwise a mechanism. For example, ARIA enables accessible navigation landmarks in HTML4, JavaScript widgets, form hints and error messages, live content updates, and more. </p> + +<div class="warning"> +<p>Many of these widgets were later incorporated into HTML5, and <strong>developers should prefer using the correct semantic HTML element over using ARIA</strong>, if such an element exists. For instance, native elements have built-in <a href="/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets">keyboard accessibility</a>, roles and states. However, if you choose to use ARIA, you are responsible for mimicking (the equivalent) browser behaviour in script.</p> +</div> + +<p>Here's the markup for a progress bar widget:</p> + +<pre class="brush: html notranslate"><div id="percent-loaded" role="progressbar" aria-valuenow="75" + aria-valuemin="0" aria-valuemax="100"> +</div> +</pre> + +<p>This progress bar is built using a <code><div></code>, which has no meaning. Unfortunately, there isn't a more semantic tag available to developers in HTML 4, so we need to include ARIA roles and properties. These are specified by adding attributes to the element. In this example, the <code>role="progressbar"</code> attribute informs the browser that this element is actually a JavaScript-powered progress bar widget. The <code>aria-valuemin</code> and <code>aria-valuemax</code> attributes specify the minimum and maximum values for the progress bar, and the <code>aria-valuenow</code> describes the current state of it and therefore must be kept updated with JavaScript.</p> + +<p>Along with placing them directly in the markup, ARIA attributes can be added to the element and updated dynamically using JavaScript code like this:</p> + +<pre class="brush: js notranslate"><code>// Find the progress bar <div> in the DOM. + var progressBar = document.getElementById("percent-loaded");</code> + +<code>// Set its ARIA roles and states, +// so that assistive technologies know what kind of widget it is.</code> + progressBar.setAttribute("role", "progressbar"); + progressBar.setAttribute("aria-valuemin", 0); + progressBar.setAttribute("aria-valuemax", 100); + +// Create a function that can be called at any time to update +// the value of the progress bar. + function updateProgress(percentComplete) { + progressBar.setAttribute("aria-valuenow", percentComplete); + }</pre> + +<div class="note"> +<p>Note that ARIA was invented after HTML4, so does not validate in HTML4 or its XHTML variants. However, the accessibility gains it provides far outweigh any technical invalidity.</p> + +<p>In HTML5, all ARIA attributes validate. The new landmark elements (<code><main></code>, <code><header></code>, <code><nav></code> etc) have built-in ARIA roles, so there is no need to duplicate them.</p> +</div> + +<h2 id="Support">Support</h2> + +<p>Like any other web technology, there are varying degrees of support for ARIA. Support is based on the operating system and browser being used, as well as the kind of assistive technology interfacing with it. In addition, the version of the operating system, browser, and assistive technology are contributing factors. Older software versions may not support certain ARIA roles, have only partial support, or misreport its functionality.</p> + +<p>It is also important to acknowledge that some people who rely on assistive technology are reluctant to upgrade their software, for fear of losing the ability to interact with their computer and browser. Because of this, it is important to <a href="/en-US/docs/Learn/Accessibility/HTML">use semantic HTML elements</a> whenever possible, as semantic HTML has far better support for assistive technology.</p> + +<p>It is also important to test your authored ARIA with actual assistive technology. Much as how browser emulators and simulators are not an effective solution for testing full support, proxy assistive technology solutions aren't sufficient to fully guarantee functionality.</p> + +<section id="sect1"> +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Tutorials">Tutorials</h2> + +<dl> + <dt><a href="/en-US/docs/Accessibility/An_overview_of_accessible_web_applications_and_widgets">Introduction to ARIA</a></dt> + <dd>A quick introduction to making dynamic content accessible with ARIA. See also the classic <a class="external" href="http://dev.opera.com/articles/view/introduction-to-wai-aria/">ARIA intro by Gez Lemon</a>, from 2008.</dd> + <dt><a class="external" href="http://zomigi.com/blog/videos-of-screen-readers-using-aria-updated/">Videos of screen readers using ARIA</a></dt> + <dd>See both real and simplified examples from around the web, including "before" and "after" ARIA videos.</dd> + <dt><a class="external" href="https://w3c.github.io/using-aria/">Using ARIA</a></dt> + <dd>A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.</dd> +</dl> + +<h2 id="Simple_ARIA_enhancements">Simple ARIA enhancements</h2> + +<dl> + <dt><a class="external" href="https://www.paciellogroup.com/blog/2013/02/using-wai-aria-landmarks-2013/">Enhancing page navigation with ARIA landmarks</a></dt> + <dd>A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. <a class="external" href="http://www.paciellogroup.com/blog/2011/07/html5-accessibility-chops-aria-landmark-support/">See also, ARIA landmark implementation notes</a> and examples on real sites (updated as of July 2011).</dd> + <dt><a href="/en-US/docs/ARIA/forms">Improving form accessibility</a></dt> + <dd>ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes.</dd> +</dl> + +<h2 id="ARIA_for_Scripted_Widgets">ARIA for Scripted Widgets</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets">Writing keyboard-navigable JavaScript widgets</a></dt> + <dd>Built-in elements like <input>, <button> etc have built-in keyboard accessibility. If you 'fake' these with <div>s and ARIA, you must ensure your widgets are keyboard accessible.</dd> + <dt><a href="/en-US/docs/Accessibility/ARIA/ARIA_Live_Regions" title="Live Regions">Live regions</a></dt> + <dd>Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.</dd> + <dt><a class="external" href="http://www.freedomscientific.com/Training/Surfs-up/AriaLiveRegions.htm">Using ARIA Live Regions to announce content changes</a></dt> + <dd>A quick summary of live regions, by the makers of JAWS screen reader software. Live regions are also supported by NVDA with Firefox, and VoiceOver with Safari.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Tools" id="References">References</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Accessibility/ARIA/Roles">ARIA Roles</a></dt> + <dd>Reference pages covering all the WAI-ARIA roles discussed on MDN.</dd> +</dl> + +<h2 class="Tools" id="Standardization_Efforts">Standardization Efforts</h2> + +<dl> + <dt><a class="external" href="https://www.w3.org/TR/wai-aria-1.1/">WAI-ARIA Specification</a></dt> + <dd>The W3C specification itself.</dd> + <dt><a class="external" href="https://www.w3.org/TR/wai-aria-practices-1.1/">WAI-ARIA Authoring Practices</a></dt> + <dd> + <p>The official best practices documents how best to ARIA-ify common widgets and interactions. An excellent resource.</p> + </dd> +</dl> + +<h2 id="Videos">Videos</h2> + +<p>Following talks are a great way to understand ARIA:</p> + +<p><a href="https://www.youtube.com/watch?v=qdB8SRhqvFc">ARIA, Accessibility APIs and coding like you give a damn! – Léonie Watson</a></p> + +<h2 id="Filing_Bugs">Filing Bugs</h2> + +<p><a href="/en/Accessibility/ARIA/How_to_file_ARIA-related_bugs" title="https://developer.mozilla.org/en/ARIA/How_to_file_ARIA-related_bugs">File ARIA bugs on browsers, screen readers, and JavaScript libraries.</a></p> +</div> +</div> +</section> + +<h2 id="Related_Topics" name="Related_Topics">Related topics</h2> + +<p><a href="/en-US/docs/Accessibility">Accessibility</a>, <a href="/en-US/docs/AJAX">AJAX</a>, <a href="/en-US/docs/Web/JavaScript">JavaScript</a></p> + +<section id="Quick_Links"> +<ol> + <li><a href="/en-US/docs/Web/Guide" title="REDIRECT Web">Web Development</a></li> + <li><a href="/en-US/docs/Mozilla/Accessibility" title="Accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. Mozilla strives to make its software accessible; the documents below cover the ways in which we do so.">Accessibility and Mozilla</a></li> +</ol> +</section> diff --git a/files/vi/web/accessibility/index.html b/files/vi/web/accessibility/index.html new file mode 100644 index 0000000000..908f9c13c5 --- /dev/null +++ b/files/vi/web/accessibility/index.html @@ -0,0 +1,76 @@ +--- +title: Accessibility +slug: Web/Accessibility +tags: + - Accessibility + - Landing + - NeedsTranslation + - TopicStub +translation_of: Web/Accessibility +--- +<p><span class="seoSummary"><strong>Accessibility</strong> (often abbreviated to <strong>A11y</strong>—as in "a" then 11 characters then "y") in Web development means enabling as many people as possible to use Web sites, even when those people's abilities are limited in some way. </span></p> + +<p>For many people, technology makes things easier. For people with disabilities, technology makes things possible. Accessibility means developing content to be as accessible as possible no matter an individual's physical and cognitive abilities and no matter how they access the web.</p> + +<p>"<strong>The Web is fundamentally designed to work for all people</strong>, whatever their hardware, software, language, culture, location, or physical or mental ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability." (<a href="http://www.w3.org/standards/webdesign/accessibility" title="http://www.w3.org/standards/webdesign/accessibility">W3C - Accessibility</a>)</p> + +<div class="cleared topicpage-table"> +<div class="section"> +<h2 class="Key_accessibility_tutorials" id="Key_accessibility_tutorials" name="Key_accessibility_tutorials">Key tutorials</h2> + +<p>The MDN <a href="/en-US/docs/Learn/Accessibility">Accessibility Learning Area</a> contains modern, up-to-date tutorials covering accessibility essentials:</p> + +<dl> + <dt><a href="/en-US/docs/Learn/Accessibility/What_is_accessibility">What is accessibility?</a></dt> + <dd>This article starts off the module with a good look at what accessibility actually is — this includes what groups of people we need to consider and why, what tools different people use to interact with the Web, and how we can make accessibility part of our web development workflow.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/HTML">HTML: A good basis for accessibility</a></dt> + <dd>A great deal of web content can be made accessible just by making sure the correct HTML elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/CSS_and_JavaScript">CSS and JavaScript accessibility best practices</a></dt> + <dd>CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure even complex content is as accessible as possible.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/WAI-ARIA_basics">WAI-ARIA basics</a></dt> + <dd>Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/Multimedia">Accessible multimedia</a></dt> + <dd>Another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users. This article shows how.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/Mobile">Mobile accessibility</a></dt> + <dd>With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Other_documentation" id="Other_documentation" name="Other_documentation">Other documentation</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG">Understanding the Web Content Accessibility Guidelines</a></dt> + <dd> + <p>This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing).</p> + </dd> + <dt><a href="/en/Accessibility/Keyboard-navigable_JavaScript_widgets" title="en/Accessibility/Keyboard-navigable JavaScript widgets">Keyboard-navigable JavaScript widgets</a></dt> + <dd>Until now, web developers who want to make their styled <div> and <span> based widgets accessible have lacked the proper techniques. <strong>Keyboard accessibility</strong> is part of the minimum accessibility requirements which a developer should be aware of.</dd> + <dt><a href="/en-US/docs/Accessibility/ARIA" title="/en-US/docs/Accessibility/ARIA">ARIA</a></dt> + <dd>A collection of articles to learn how to use ARIA to make your HTML documents more accessible.</dd> + <dt><a href="/en-US/docs/Accessibility/AT_Development" title="AT Development">Assistive technology (AT) development</a></dt> + <dd>A collection of articles intended for AT developers</dd> + <dt><a href="/en-US/docs/Web/Accessibility/Mobile_accessibility_checklist">Mobile accessibility checklist</a></dt> + <dd>This document provides a concise checklist of accessibility requirements for mobile app developers.</dd> + <dt><a href="/en-US/docs/Web/Accessibility/Cognitive_accessibility">Cognitive accessibility</a></dt> + <dd>When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments.</dd> + <dt><a href="/en-US/docs/Web/Accessibility/Seizure_disorders">Accessibility for seizure disorders</a></dt> + <dd>Some types of visual web content can induce seizures in people with certain brain disorders. Understand the types of content that can be problematic, and find tools and strategies to help you avoid them.</dd> + <dt></dt> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/Accessibility" title="/en-US/docs/tag/Accessibility">View all articles about Accessibility...</a></span></p> +</div> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://lists.mozilla.org/listinfo/accessibility">Mozilla mailing list about accessibility</a></li> + <li><a href="http://www.w3.org/WAI/IG/">WAI Interest Group</a></li> + <li><a href="https://mozillians.org/en-US/group/1-accessibility">Mozillians group about accessibility</a></li> + <li><a href="/en-US/docs/Web/Guide" title="REDIRECT Web">Developer guides</a></li> + <li><a href="/en-US/docs/Mozilla/Accessibility" title="Accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. Mozilla strives to make its software accessible; the documents below cover the ways in which we do so.">Accessibility and Mozilla</a></li> +</ul> + +<section id="Quick_Links"></section> diff --git a/files/vi/web/api/audiocontext/createoscillator/index.html b/files/vi/web/api/audiocontext/createoscillator/index.html new file mode 100644 index 0000000000..e0a786a181 --- /dev/null +++ b/files/vi/web/api/audiocontext/createoscillator/index.html @@ -0,0 +1,118 @@ +--- +title: AudioContext.createOscillator() +slug: Web/API/AudioContext/createOscillator +translation_of: Web/API/BaseAudioContext/createOscillator +--- +<p>{{ APIRef("Web Audio API") }}</p> + +<div> +<p>Phương thức <code>createOscillator()</code> của giao thức {{ domxref("AudioContext") }} tạo một cái {{ domxref("OscillatorNode") }} (nút máy dao động). Tức là ta cái nguồn từ dạng sóng.</p> +</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="brush: js">var audioCtx = new AudioContext(); +var oscillator = audioCtx.createOscillator();</pre> + +<h3 id="Description" name="Description">Trả về</h3> + +<p>Một cái {{domxref("OscillatorNode")}}.</p> + +<h2 id="Examples" name="Examples">Ví dụ</h2> + +<p>Ví dụ này trình bày sử dụng đơn giản của một cái AudioContext để tạo một cái OsillatorNode. Để biết thêm thông tin, xem biểu hiện, và trang {{domxref("OscillatorNode")}} của chúng tôi</p> + +<p>Ví dụ này trình bày sử dụng đơn giản của một cái AudioContext để tạo một cái OsillatorNode. Để biết thêm thông tin, xem biểu hiện <a href="http://mdn.github.io/violent-theremin/">Violent Theremin</a> (<a href="https://github.com/mdn/violent-theremin/blob/gh-pages/scripts/app.js">app.js</a>); và trang {{ domxref("OscillatorNode") }} của chúng tôi.</p> + +<pre class="brush: js">// create web audio api context +var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); + +// create Oscillator node +var oscillator = audioCtx.createOscillator(); + +oscillator.type = 'square'; +oscillator.frequency.value = 3000; // Hz +<code>oscillator.connect(audioCtx.destination); +</code>oscillator.start();</pre> + +<h2 id="Quy_cách">Quy cách</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Quy cách</th> + <th scope="col">Địa vị</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('Web Audio API', '#widl-AudioContext-createOscillator-OscillatorNode', 'createOscillator')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Đặc trưng</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(10.0)}}{{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(25.0)}} </td> + <td>{{CompatNo}}</td> + <td>15.0{{property_prefix("webkit")}}<br> + 22 (unprefixed)</td> + <td>6.0{{property_prefix("webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Đặc trưng</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>26.0</td> + <td>1.2</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>33.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> +</ul> diff --git a/files/vi/web/api/audiocontext/index.html b/files/vi/web/api/audiocontext/index.html new file mode 100644 index 0000000000..da175915e4 --- /dev/null +++ b/files/vi/web/api/audiocontext/index.html @@ -0,0 +1,305 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +tags: + - API + - Audio + - AudioContext + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API + - sound +translation_of: Web/API/AudioContext +--- +<p>{{APIRef("Web Audio API")}}</p> + +<div> +<p>The <code>AudioContext</code> interface represents an audio-processing graph built from audio modules linked together, each represented by an {{domxref("AudioNode")}}. An audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an AudioContext before you do anything else, as everything happens inside a context.</p> +</div> + +<p>An <code>AudioContext</code> can be a target of events, therefore it implements the {{domxref("EventTarget")}} interface.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("AudioContext.AudioContext", "AudioContext()")}}</dt> + <dd>Creates and returns a new <code>AudioContext</code> object.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("AudioContext.currentTime")}} {{readonlyInline}}</dt> + <dd>Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at <code>0</code>.</dd> + <dt>{{domxref("AudioContext.destination")}} {{readonlyInline}}</dt> + <dd>Returns an {{domxref("AudioDestinationNode")}} representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.</dd> + <dt>{{domxref("AudioContext.listener")}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("AudioListener")}} object, used for 3D spatialization.</dd> + <dt>{{domxref("AudioContext.sampleRate")}} {{readonlyInline}}</dt> + <dd>Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an {{domxref("AudioContext")}} cannot be changed.</dd> + <dt>{{domxref("AudioContext.state")}} {{readonlyInline}}</dt> + <dd>Returns the current state of the <code>AudioContext</code>.</dd> + <dt>{{domxref("AudioContext.mozAudioChannelType")}} {{ non-standard_inline() }} {{readonlyInline}}</dt> + <dd>Used to return the audio channel that the sound playing in an {{domxref("AudioContext")}} will play in, on a Firefox OS device.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("AudioContext.onstatechange")}}</dt> + <dd>An event handler that runs when an event of type {{event("statechange")}} has fired. This occurs when the <code>AudioContext</code>'s state changes, due to the calling of one of the state change methods ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Also implements methods from the interface </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("AudioContext.close()")}}</dt> + <dd>Closes the audio context, releasing any system audio resources that it uses.</dd> + <dt>{{domxref("AudioContext.createBuffer()")}}</dt> + <dd>Creates a new, empty {{ domxref("AudioBuffer") }} object, which can then be populated by data and played via an {{ domxref("AudioBufferSourceNode") }}.</dd> + <dt>{{domxref("AudioContext.createConstantSource()")}}</dt> + <dd>Creates a {{domxref("ConstantSourceNode")}} object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.</dd> + <dt>{{domxref("AudioContext.createBufferSource()")}}</dt> + <dd>Creates an {{domxref("AudioBufferSourceNode")}}, which can be used to play and manipulate audio data contained within an {{ domxref("AudioBuffer") }} object. {{ domxref("AudioBuffer") }}s are created using {{domxref("AudioContext.createBuffer")}} or returned by {{domxref("AudioContext.decodeAudioData")}} when it successfully decodes an audio track.</dd> + <dt>{{domxref("AudioContext.createMediaElementSource()")}}</dt> + <dd>Creates a {{domxref("MediaElementAudioSourceNode")}} associated with an {{domxref("HTMLMediaElement")}}. This can be used to play and manipulate audio from {{HTMLElement("video")}} or {{HTMLElement("audio")}} elements.</dd> + <dt>{{domxref("AudioContext.createMediaStreamSource()")}}</dt> + <dd>Creates a {{domxref("MediaStreamAudioSourceNode")}} associated with a {{domxref("MediaStream")}} representing an audio stream which may come from the local computer microphone or other sources.</dd> + <dt>{{domxref("AudioContext.createMediaStreamDestination()")}}</dt> + <dd>Creates a {{domxref("MediaStreamAudioDestinationNode")}} associated with a {{domxref("MediaStream")}} representing an audio stream which may be stored in a local file or sent to another computer.</dd> + <dt>{{domxref("AudioContext.createScriptProcessor()")}}</dt> + <dd>Creates a {{domxref("ScriptProcessorNode")}}, which can be used for direct audio processing via JavaScript.</dd> + <dt>{{domxref("AudioContext.createStereoPanner()")}}</dt> + <dd>Creates a {{domxref("StereoPannerNode")}}, which can be used to apply stereo panning to an audio source.</dd> + <dt>{{domxref("AudioContext.createAnalyser()")}}</dt> + <dd>Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualisations.</dd> + <dt>{{domxref("AudioContext.createBiquadFilter()")}}</dt> + <dd>Creates a {{domxref("BiquadFilterNode")}}, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc.</dd> + <dt>{{domxref("AudioContext.createChannelMerger()")}}</dt> + <dd>Creates a {{domxref("ChannelMergerNode")}}, which is used to combine channels from multiple audio streams into a single audio stream.</dd> + <dt>{{domxref("AudioContext.createChannelSplitter()")}}</dt> + <dd>Creates a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.</dd> + <dt>{{domxref("AudioContext.createConvolver()")}}</dt> + <dd>Creates a {{domxref("ConvolverNode")}}, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.</dd> + <dt>{{domxref("AudioContext.createDelay()")}}</dt> + <dd>Creates a {{domxref("DelayNode")}}, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.</dd> + <dt>{{domxref("AudioContext.createDynamicsCompressor()")}}</dt> + <dd>Creates a {{domxref("DynamicsCompressorNode")}}, which can be used to apply acoustic compression to an audio signal.</dd> + <dt>{{domxref("AudioContext.createGain()")}}</dt> + <dd>Creates a {{domxref("GainNode")}}, which can be used to control the overall volume of the audio graph.</dd> + <dt>{{domxref("AudioContext.createIIRFilter()")}}</dt> + <dd>Creates an {{domxref("IIRFilterNode")}}, which represents a second order filter configurable as several different common filter types.</dd> + <dt>{{domxref("AudioContext.createOscillator()")}}</dt> + <dd>Creates an {{domxref("OscillatorNode")}}, a source representing a periodic waveform. It basically generates a tone.</dd> + <dt>{{domxref("AudioContext.createPanner()")}}</dt> + <dd>Creates a {{domxref("PannerNode")}}, which is used to spatialise an incoming audio stream in 3D space.</dd> + <dt>{{domxref("AudioContext.createPeriodicWave()")}}</dt> + <dd>Creates a {{domxref("PeriodicWave")}}, used to define a periodic waveform that can be used to determine the output of an {{ domxref("OscillatorNode") }}.</dd> + <dt>{{domxref("AudioContext.createWaveShaper()")}}</dt> + <dd>Creates a {{domxref("WaveShaperNode")}}, which is used to implement non-linear distortion effects.</dd> + <dt>{{domxref("AudioContext.createAudioWorker()")}}</dt> + <dd>Creates an {{domxref("AudioWorkerNode")}}, which can interact with a web worker thread to generate, process, or analyse audio directly. This was added to the spec on August 29 2014, and is not implemented in any browser yet.</dd> + <dt>{{domxref("AudioContext.decodeAudioData()")}}</dt> + <dd>Asynchronously decodes audio file data contained in an {{domxref("ArrayBuffer")}}. In this case, the ArrayBuffer is usually loaded from an {{domxref("XMLHttpRequest")}}'s <code>response</code> attribute after setting the <code>responseType</code> to <code>arraybuffer</code>. This method only works on complete files, not fragments of audio files.</dd> + <dt>{{domxref("AudioContext.getOutputTimestamp()")}}</dt> + <dd>Returns a new <code>AudioTimestamp</code> containing two correlated context's audio stream position values: the <code>AudioTimestamp.contextTime</code> member contains the time of the sample frame which is currently being rendered by the audio output device (i.e., output audio stream position), in the same units and origin as context's {{domxref("AudioContext.currentTime")}}; the AudioTimestamp.performanceTime member contains the time estimating the moment when the sample frame corresponding to the stored contextTime value was rendered by the audio output device, in the same units and origin as {{domxref("performance.now()")}}.</dd> + <dt>{{domxref("AudioContext.resume()")}}</dt> + <dd>Resumes the progression of time in an audio context that has previously been suspended.</dd> + <dt>{{domxref("AudioContext.suspend()")}}</dt> + <dd>Suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process.</dd> +</dl> + +<h2 id="Obsolete_methods">Obsolete methods</h2> + +<dl> + <dt>{{domxref("AudioContext.createJavaScriptNode()")}}</dt> + <dd>Creates a {{domxref("JavaScriptNode")}}, used for direct audio processing via JavaScript. This method is obsolete, and has been replaced by {{domxref("AudioContext.createScriptProcessor()")}}.</dd> + <dt>{{domxref("AudioContext.createWaveTable()")}}</dt> + <dd>Creates a {{domxref("WaveTableNode")}}, used to define a periodic waveform. This method is obsolete, and has been replaced by {{domxref("AudioContext.createPeriodicWave()")}}.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>Basic audio context declaration:</p> + +<pre class="brush: js">var audioCtx = new AudioContext();</pre> + +<p>Cross browser variant:</p> + +<pre class="brush: js">var AudioContext = window.AudioContext || window.webkitAudioContext; +var audioCtx = new AudioContext(); + +var oscillatorNode = audioCtx.createOscillator(); +var gainNode = audioCtx.createGain(); +var finish = audioCtx.destination; +// etc.</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Audio API', '#the-audiocontext-interface', 'AudioContext')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(10.0)}}{{property_prefix("webkit")}}<br> + 35</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(25.0)}} </td> + <td>{{CompatNo}}</td> + <td>15.0{{property_prefix("webkit")}}<br> + 22</td> + <td>6.0{{property_prefix("webkit")}}</td> + </tr> + <tr> + <td><code>createStereoPanner()</code></td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(37.0)}} </td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>onstatechange</code>, <code>state</code>, <code>suspend()</code>, <code>resume()</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(40.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari(8.0)}}</td> + </tr> + <tr> + <td><code>createConstantSource()</code></td> + <td>{{CompatChrome(56.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(52)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(43)}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Unprefixed</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(37.0)}} </td> + <td>2.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>createStereoPanner()</code></td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + <tr> + <td><code>onstatechange</code>, <code>state</code>, <code>suspend()</code>, <code>resume()</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>createConstantSource()</code></td> + <td>{{CompatChrome(56.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(52)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(56.0)}}</td> + </tr> + <tr> + <td>Unprefixed</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(43)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul style="margin-left: 40px;"> + <li><a href="/en-US/docs/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> + <li>{{domxref("OfflineAudioContext")}}</li> +</ul> diff --git a/files/vi/web/api/canvas_api/index.html b/files/vi/web/api/canvas_api/index.html new file mode 100644 index 0000000000..dc582ea7ce --- /dev/null +++ b/files/vi/web/api/canvas_api/index.html @@ -0,0 +1,129 @@ +--- +title: Canvas API +slug: Web/API/Canvas_API +translation_of: Web/API/Canvas_API +--- +<div>{{CanvasSidebar}}</div> + +<p class="summary"><strong>Canvas API</strong> cung cấp phương tiện để vẽ đồ họa thông qua <a href="/en-US/docs/Web/JavaScript">JavaScript</a> và <a href="/en-US/docs/Web/HTML">HTML</a> {{HtmlElement("canvas")}} thuộc tính. Nó có thể được sử dụng cho hình động, đồ họa game, trực quan hóa dữ liệu, xử lí ảnh và video trong thời gian thực.</p> + +<p>Canvas API tập trung vào đồ họa 2D. <a href="/en-US/docs/Web/WebGL">WebGL API</a>, nó cũng sử dụng <code><canvas></code> , để vẽ đồ họa 2D và 3D.</p> + +<h2 id="Ví_dụ_đơn_giản">Ví dụ đơn giản</h2> + +<p>This simple example draws a green rectangle onto a canvas.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<p>The {{domxref("Document.getElementById()")}} method gets a reference to the HTML <code><canvas></code> element. Next, the {{domxref("HTMLCanvasElement.getContext()")}} method gets that element's context—the thing onto which the drawing will be rendered.</p> + +<p>The actual drawing is done using the {{domxref("CanvasRenderingContext2D")}} interface. The {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} property makes the rectangle green. The {{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.</p> + +<pre class="brush: js">const canvas = document.getElementById('canvas'); +const ctx = canvas.getContext('2d'); + +ctx.fillStyle = 'green'; +ctx.fillRect(10, 10, 150, 100); +</pre> + +<h3 id="Result">Result</h3> + +<p>{{ EmbedLiveSample('Basic_example', 700, 180) }}</p> + +<h2 id="Reference">Reference</h2> + +<div class="index"> +<ul> + <li>{{domxref("HTMLCanvasElement")}}</li> + <li>{{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasGradient")}}</li> + <li>{{domxref("CanvasImageSource")}}</li> + <li>{{domxref("CanvasPattern")}}</li> + <li>{{domxref("ImageBitmap")}}</li> + <li>{{domxref("ImageData")}}</li> + <li>{{domxref("RenderingContext")}}</li> + <li>{{domxref("TextMetrics")}}</li> + <li>{{domxref("OffscreenCanvas")}} {{experimental_inline}}</li> + <li>{{domxref("Path2D")}} {{experimental_inline}}</li> + <li>{{domxref("ImageBitmapRenderingContext")}} {{experimental_inline}}</li> +</ul> +</div> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> The interfaces related to the <code>WebGLRenderingContext</code> are referenced under <a href="/en-US/docs/Web/WebGL" title="/en-US/docs/Web/WebGL">WebGL</a>.</p> +</div> + +<p>{{domxref("CanvasCaptureMediaStream")}} is a related interface.</p> + +<h2 id="Guides_and_tutorials">Guides and tutorials</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas tutorial</a></dt> + <dd>A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.</dd> + <dt><a href="http://joshondesign.com/p/books/canvasdeepdive/title.html">HTML5 Canvas Deep Dive</a></dt> + <dd>A hands-on, book-length introduction to the Canvas API and WebGL.</dd> + <dt><a href="http://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html">Canvas Handbook</a></dt> + <dd>A handy reference for the Canvas API.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/A_basic_ray-caster">Demo: A basic ray-caster</a></dt> + <dd>A demo of ray-tracing animation using canvas.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas">Manipulating video using canvas</a></dt> + <dd>Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.</dd> +</dl> + +<h2 id="Libraries">Libraries</h2> + +<p>The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.</p> + +<ul> + <li><a href="http://www.createjs.com/easeljs">EaselJS</a> is an open-source canvas library that makes creating games, generative art, and other highly graphical experiences easy.</li> + <li><a href="http://fabricjs.com">Fabric.js</a> is an open-source canvas library with SVG parsing capabilities.</li> + <li><a href="https://www.patrick-wied.at/static/heatmapjs/">heatmap.js</a> is an open-source library for creating canvas-based data heat maps.</li> + <li><a href="http://thejit.org/">JavaScript InfoVis Toolkit</a> creates interactive data visualizations.</li> + <li><a href="https://konvajs.github.io/">Konva.js</a> is a 2D canvas library for desktop and mobile applications.</li> + <li><a href="https://p5js.org/">p5.js </a>has a full set of canvas drawing functionality for artists, designers, educators, and beginners.</li> + <li><a href="http://paperjs.org/">Paper.js</a> is an open-source vector graphics scripting framework that runs on top of the HTML5 Canvas.</li> + <li><a href="https://phaser.io/">Phaser</a> is a fast, free and fun open source framework for Canvas and WebGL powered browser games.</li> + <li><a href="http://processingjs.org">Processing.js</a> is a port of the Processing visualization language.</li> + <li><a href="https://ptsjs.org">Pts.js</a> is a library for creative coding and visualization in canvas and SVG.</li> + <li><a class="link-https" href="https://github.com/jeremyckahn/rekapi">Rekapi</a> is an animation key-framing API for Canvas.</li> + <li><a href="http://scrawl.rikweb.org.uk/">Scrawl-canvas</a> is an open-source JavaScript library for creating and manipulating 2D canvas elements.</li> + <li>The <a href="http://zimjs.com">ZIM</a> framework provides conveniences, components, and controls for coding creativity on the canvas — includes accessibility and hundreds of colorful tutorials.</li> +</ul> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> See the <a href="/en-US/docs/Web/WebGL" title="/en-US/docs/Web/WebGL">WebGL API</a> for 2D and 3D libaries that use WebGL.</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>Mozilla applications gained support for <code><canvas></code> starting with Gecko 1.8 (<a href="/en-US/docs/Mozilla/Firefox/Releases/1.5">Firefox 1.5</a>). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <code><canvas></code> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <code><canvas></code> by including a script from Google's <a href="https://github.com/arv/explorercanvas">Explorer Canvas</a> project. Google Chrome and Opera 9 also support <code><canvas></code>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/WebGL">WebGL</a></li> +</ul> diff --git a/files/vi/web/api/childnode/index.html b/files/vi/web/api/childnode/index.html new file mode 100644 index 0000000000..ff71a15d51 --- /dev/null +++ b/files/vi/web/api/childnode/index.html @@ -0,0 +1,78 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - DOM + - Experimental + - Interface + - NeedsTranslation + - Node + - TopicStub +translation_of: Web/API/ChildNode +--- +<div>{{APIRef("DOM")}}</div> + +<p>The <code><strong>ChildNode</strong></code> interface contains methods that are particular to {{domxref("Node")}} objects that can have a parent.</p> + +<p><code>ChildNode</code> is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("DocumentType")}}, and {{domxref("CharacterData")}} objects.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>There are neither inherited, nor specific properties.</em></p> + +<h2 id="Methods">Methods</h2> + +<p><em>There are no inherited methods.</em></p> + +<dl> + <dt>{{domxref("ChildNode.remove()")}} {{experimental_inline}}</dt> + <dd>Removes this <code>ChildNode</code> from the children list of its parent.</dd> + <dt>{{domxref("ChildNode.before()")}} {{experimental_inline}}</dt> + <dd>Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this <code>ChildNode</code>'s parent, just before this <code>ChildNode</code>. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.</dd> + <dt>{{domxref("ChildNode.after()")}} {{experimental_inline}}</dt> + <dd>Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this <code>ChildNode</code>'s parent, just after this <code>ChildNode</code>. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.</dd> + <dt>{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}</dt> + <dd>Replaces this <code>ChildNode</code> in the children list of its parent with a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Split the <code>ElementTraversal</code> interface in {{domxref("ParentNode")}} and <code>ChildNode</code>. <code>previousElementSibling</code> and <code>nextElementSibling</code> are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. Added the <code>remove()</code>, <code>before()</code>, <code>after()</code> and <code>replaceWith()</code> methods.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Added the initial definition of its properties to the <code>ElementTraversal</code> pure interface and use it on {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Polyfill">Polyfill</h2> + +<p>External on github: <a href="https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js">childNode.js</a></p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.ChildNode")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("ParentNode")}} pure interface.</li> + <li> + <div class="syntaxbox">Object types implementing this pure interface: {{domxref("CharacterData")}}, {{domxref("Element")}}, and {{domxref("DocumentType")}}.</div> + </li> +</ul> diff --git a/files/vi/web/api/childnode/remove/index.html b/files/vi/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..3c0fde3e18 --- /dev/null +++ b/files/vi/web/api/childnode/remove/index.html @@ -0,0 +1,97 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Phương Thức + - Đang thử nghiệm +translation_of: Web/API/ChildNode/remove +--- +<div>{{APIRef("DOM")}}</div> + +<p>Phương thức <code><strong>ChildNode.remove()</strong></code> dùng để loại bỏ chính đối tượng gọi nó ra khỏi cây cấu trúc.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><em>node</em>.remove(); +</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Cách_dùng_remove()">Cách dùng <code>remove()</code></h3> + +<pre class="brush: html"><div id="div-01">Đây là div-01</div> +<div id="div-02">Đây là div-02</div> +<div id="div-03">Đây là div-03</div> +</pre> + +<pre class="brush: js">var el = document.getElementById('div-02'); +el.remove(); // Gỡ bỏ div có id là 'div-02' +</pre> + +<h3 id="ChildNode.remove()_is_unscopable"><code>ChildNode.remove()</code> is unscopable</h3> + +<p>The <code>remove()</code> method is not scoped into the <code>with</code> statement. See {{jsxref("Symbol.unscopables")}} for more information.</p> + +<pre class="brush: js">with(node) { + remove(); +} +// ReferenceError: remove is not defined </pre> + +<h2 id="Giải_pháp_thay_thế">Giải pháp thay thế</h2> + +<p>Ta có thể thay thế phương thức <code>remove()</code> bằng đoạn mã sau để chạy trên Internet Explorer 9 và những đời sau này:</p> + +<pre class="brush: js">// Nguồn: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('remove')) { + return; + } + Object.defineProperty(item, 'remove', { + configurable: true, + enumerable: true, + writable: true, + value: function remove() { + if (this.parentNode !== null) + this.parentNode.removeChild(this); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Lần đầu được định nghĩa.</td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + +<div> + + +<p>{{Compat("api.ChildNode.remove")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>The {{domxref("ChildNode")}} pure interface.</li> + <li> + <div class="syntaxbox">Object types implementing this pure interface: {{domxref("CharacterData")}}, {{domxref("Element")}}, and {{domxref("DocumentType")}}.</div> + </li> +</ul> diff --git a/files/vi/web/api/document_object_model/index.html b/files/vi/web/api/document_object_model/index.html new file mode 100644 index 0000000000..d00ed4aeea --- /dev/null +++ b/files/vi/web/api/document_object_model/index.html @@ -0,0 +1,387 @@ +--- +title: Document Object Model (DOM) +slug: Web/API/Document_Object_Model +tags: + - API + - DOM + - DOM Reference + - Intermediate + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Document_Object_Model +--- +<p>{{DefaultAPISidebar("DOM")}}</p> + +<p>The <strong>Document Object Model (<em>DOM</em>)</strong> is a programming interface for HTML, XML and SVG documents. It provides a structured representation of the document as a tree. The DOM defines methods that allow access to the tree, so that they can change the document structure, style and content. The DOM provides a representation of the document as a structured group of nodes and objects, possessing various properties and methods. Nodes can also have event handlers attached to them, and once an event is triggered, the event handlers get executed. Essentially, it connects web pages to scripts or programming languages.</p> + +<p>Although the DOM is often accessed using JavaScript, it is not a part of the JavaScript language. It can also be accessed by other languages.</p> + +<p>An <a href="/en-US/docs/DOM/DOM_Reference/Introduction">introduction</a> to the DOM is available.</p> + +<h2 id="DOM_interfaces">DOM interfaces</h2> + +<div class="index"> +<ul> + <li>{{domxref("Attr")}}</li> + <li>{{domxref("CharacterData")}}</li> + <li>{{domxref("ChildNode")}} {{experimental_inline}}</li> + <li>{{domxref("Comment")}}</li> + <li>{{domxref("CustomEvent")}}</li> + <li>{{domxref("Document")}}</li> + <li>{{domxref("DocumentFragment")}}</li> + <li>{{domxref("DocumentType")}}</li> + <li>{{domxref("DOMError")}}</li> + <li>{{domxref("DOMException")}}</li> + <li>{{domxref("DOMImplementation")}}</li> + <li>{{domxref("DOMString")}}</li> + <li>{{domxref("DOMTimeStamp")}}</li> + <li>{{domxref("DOMSettableTokenList")}}</li> + <li>{{domxref("DOMStringList")}}</li> + <li>{{domxref("DOMTokenList")}}</li> + <li>{{domxref("Element")}}</li> + <li>{{domxref("Event")}}</li> + <li>{{domxref("EventTarget")}}</li> + <li>{{domxref("HTMLCollection")}}</li> + <li>{{domxref("MutationObserver")}}</li> + <li>{{domxref("MutationRecord")}}</li> + <li>{{domxref("Node")}}</li> + <li>{{domxref("NodeFilter")}}</li> + <li>{{domxref("NodeIterator")}}</li> + <li>{{domxref("NodeList")}}</li> + <li>{{domxref("ParentNode")}} {{experimental_inline}}</li> + <li>{{domxref("ProcessingInstruction")}}</li> + <li>{{domxref("Range")}}</li> + <li>{{domxref("Text")}}</li> + <li>{{domxref("TreeWalker")}}</li> + <li>{{domxref("URL")}}</li> + <li>{{domxref("Window")}}</li> + <li>{{domxref("Worker")}}</li> + <li>{{domxref("XMLDocument")}} {{experimental_inline}}</li> +</ul> +</div> + +<h2 id="Obsolete_DOM_interfaces">Obsolete DOM interfaces</h2> + +<p>The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specification have been removed. It is still not very clear whether some may be reintroduced or not, but for the time being they have to be considered as obsolete and should be avoided:</p> + +<div class="index"> +<ul> + <li>{{domxref("CDATASection")}}</li> + <li>{{domxref("DOMConfiguration")}}</li> + <li>{{domxref("DOMErrorHandler")}}</li> + <li>{{domxref("DOMImplementationList")}}</li> + <li>{{domxref("DOMImplementationRegistry")}}</li> + <li>{{domxref("DOMImplementationSource")}}</li> + <li>{{domxref("DOMLocator")}}</li> + <li>{{domxref("DOMObject")}}</li> + <li>{{domxref("DOMUserData")}}</li> + <li>{{domxref("Entity")}}</li> + <li>{{domxref("EntityReference")}}</li> + <li>{{domxref("NamedNodeMap")}}</li> + <li>{{domxref("NameList")}}</li> + <li>{{domxref("Notation")}}</li> + <li>{{domxref("TypeInfo")}}</li> + <li>{{domxref("UserDataHandler")}}</li> + <li> </li> +</ul> +</div> + +<h2 id="HTML_interfaces">HTML interfaces</h2> + +<p>A document containing HTML is described using the {{domxref("HTMLDocument")}} interface. Note that the HTML specification also extends the {{domxref("Document")}} interface.</p> + +<p>An <code>HTMLDocument</code> object also gives access to various features of browsers like the tab or the window, in which a page is drawn using the {{domxref("Window")}} interface, the {{domxref("window.style", "Style")}} associated to it (usually CSS), the history of the browser relative to the context, {{domxref("window.history", "History")}}. Eventually, {{domxref("Selection")}} is done on the document.</p> + +<h3 id="HTML_element_interfaces">HTML element interfaces</h3> + +<div class="index"> +<ul> + <li>{{domxref("HTMLAnchorElement")}}</li> + <li>{{domxref("HTMLAppletElement")}}</li> + <li>{{domxref("HTMLAreaElement")}}</li> + <li>{{domxref("HTMLAudioElement")}}</li> + <li>{{domxref("HTMLBaseElement")}}</li> + <li>{{domxref("HTMLBodyElement")}}</li> + <li>{{domxref("HTMLBRElement")}}</li> + <li>{{domxref("HTMLButtonElement")}}</li> + <li>{{domxref("HTMLCanvasElement")}}</li> + <li>{{domxref("HTMLDataElement")}}</li> + <li>{{domxref("HTMLDataListElement")}}</li> + <li>{{domxref("HTMLDialogElement")}}</li> + <li>{{domxref("HTMLDirectoryElement")}}</li> + <li>{{domxref("HTMLDivElement")}}</li> + <li>{{domxref("HTMLDListElement")}}</li> + <li>{{domxref("HTMLElement")}}</li> + <li>{{domxref("HTMLEmbedElement")}}</li> + <li>{{domxref("HTMLFieldSetElement")}}</li> + <li>{{domxref("HTMLFontElement")}}</li> + <li>{{domxref("HTMLFormElement")}}</li> + <li>{{domxref("HTMLFrameElement")}}</li> + <li>{{domxref("HTMLFrameSetElement")}}</li> + <li>{{domxref("HTMLHeadElement")}}</li> + <li>{{domxref("HTMLHeadingElement")}}</li> + <li>{{domxref("HTMLHtmlElement")}}</li> + <li>{{domxref("HTMLHRElement")}}</li> + <li>{{domxref("HTMLIFrameElement")}}</li> + <li>{{domxref("HTMLImageElement")}}</li> + <li>{{domxref("HTMLInputElement")}}</li> + <li>{{domxref("HTMLKeygenElement")}}</li> + <li>{{domxref("HTMLLabelElement")}}</li> + <li>{{domxref("HTMLLegendElement")}}</li> + <li>{{domxref("HTMLLIElement")}}</li> + <li>{{domxref("HTMLLinkElement")}}</li> + <li>{{domxref("HTMLMapElement")}}</li> + <li>{{domxref("HTMLMediaElement")}}</li> + <li>{{domxref("HTMLMenuElement")}}</li> + <li>{{domxref("HTMLMetaElement")}}</li> + <li>{{domxref("HTMLMeterElement")}}</li> + <li>{{domxref("HTMLModElement")}}</li> + <li>{{domxref("HTMLObjectElement")}}</li> + <li>{{domxref("HTMLOListElement")}}</li> + <li>{{domxref("HTMLOptGroupElement")}}</li> + <li>{{domxref("HTMLOptionElement")}}</li> + <li>{{domxref("HTMLOutputElement")}}</li> + <li>{{domxref("HTMLParagraphElement")}}</li> + <li>{{domxref("HTMLParamElement")}}</li> + <li>{{domxref("HTMLPreElement")}}</li> + <li>{{domxref("HTMLProgressElement")}}</li> + <li>{{domxref("HTMLQuoteElement")}}</li> + <li>{{domxref("HTMLScriptElement")}}</li> + <li>{{domxref("HTMLSelectElement")}}</li> + <li>{{domxref("HTMLSourceElement")}}</li> + <li>{{domxref("HTMLSpanElement")}}</li> + <li>{{domxref("HTMLStyleElement")}}</li> + <li>{{domxref("HTMLTableElement")}}</li> + <li>{{domxref("HTMLTableCaptionElement")}}</li> + <li>{{domxref("HTMLTableCellElement")}}</li> + <li>{{domxref("HTMLTableDataCellElement")}}</li> + <li>{{domxref("HTMLTableHeaderCellElement")}}</li> + <li>{{domxref("HTMLTableColElement")}}</li> + <li>{{domxref("HTMLTableRowElement")}}</li> + <li>{{domxref("HTMLTableSectionElement")}}</li> + <li>{{domxref("HTMLTextAreaElement")}}</li> + <li>{{domxref("HTMLTimeElement")}}</li> + <li>{{domxref("HTMLTitleElement")}}</li> + <li>{{domxref("HTMLTrackElement")}}</li> + <li>{{domxref("HTMLUListElement")}}</li> + <li>{{domxref("HTMLUnknownElement")}}</li> + <li>{{domxref("HTMLVideoElement")}}</li> +</ul> +</div> + +<h3 id="Other_interfaces">Other interfaces</h3> + +<div class="index"> +<ul> + <li>{{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasGradient")}}</li> + <li>{{domxref("CanvasPattern")}}</li> + <li>{{domxref("TextMetrics")}}</li> + <li>{{domxref("ImageData")}}</li> + <li>{{domxref("CanvasPixelArray")}}</li> + <li>{{domxref("NotifyAudioAvailableEvent")}}</li> + <li>{{domxref("HTMLAllCollection")}}</li> + <li>{{domxref("HTMLFormControlsCollection")}}</li> + <li>{{domxref("HTMLOptionsCollection")}}</li> + <li>{{domxref("HTMLPropertiesCollection")}}</li> + <li>{{domxref("DOMStringMap")}}</li> + <li>{{domxref("RadioNodeList")}}</li> + <li>{{domxref("MediaError")}}</li> +</ul> +</div> + +<h3 id="Obsolete_HTML_interfaces">Obsolete HTML interfaces</h3> + +<div class="index"> +<ul> + <li>{{domxref("HTMLBaseFontElement")}}</li> + <li>{{domxref("HTMLIsIndexElement")}}</li> +</ul> +</div> + +<h2 id="SVG_interfaces">SVG interfaces</h2> + +<h3 id="SVG_element_interfaces">SVG element interfaces</h3> + +<div class="index"> +<ul> + <li>{{domxref("SVGAElement")}}</li> + <li>{{domxref("SVGAltGlyphElement")}}</li> + <li>{{domxref("SVGAltGlyphDefElement")}}</li> + <li>{{domxref("SVGAltGlyphItemElement")}}</li> + <li>{{domxref("SVGAnimationElement")}}</li> + <li>{{domxref("SVGAnimateElement")}}</li> + <li>{{domxref("SVGAnimateColorElement")}}</li> + <li>{{domxref("SVGAnimateMotionElement")}}</li> + <li>{{domxref("SVGAnimateTransformElement")}}</li> + <li>{{domxref("SVGCircleElement")}}</li> + <li>{{domxref("SVGClipPathElement")}}</li> + <li>{{domxref("SVGColorProfileElement")}}</li> + <li>{{domxref("SVGComponentTransferFunctionElement")}}</li> + <li>{{domxref("SVGCursorElement")}}</li> + <li>{{domxref("SVGDefsElement")}}</li> + <li>{{domxref("SVGDescElement")}}</li> + <li>{{domxref("SVGElement")}}</li> + <li>{{domxref("SVGEllipseElement")}}</li> + <li>{{domxref("SVGFEBlendElement")}}</li> + <li>{{domxref("SVGFEColorMatrixElement")}}</li> + <li>{{domxref("SVGFEComponentTransferElement")}}</li> + <li>{{domxref("SVGFECompositeElement")}}</li> + <li>{{domxref("SVGFEConvolveMatrixElement")}}</li> + <li>{{domxref("SVGFEDiffuseLightingElement")}}</li> + <li>{{domxref("SVGFEDisplacementMapElement")}}</li> + <li>{{domxref("SVGFEDistantLightElement")}}</li> + <li>{{domxref("SVGFEFloodElement")}}</li> + <li>{{domxref("SVGFEGaussianBlurElement")}}</li> + <li>{{domxref("SVGFEImageElement")}}</li> + <li>{{domxref("SVGFEMergeElement")}}</li> + <li>{{domxref("SVGFEMergeNodeElement")}}</li> + <li>{{domxref("SVGFEMorphologyElement")}}</li> + <li>{{domxref("SVGFEOffsetElement")}}</li> + <li>{{domxref("SVGFEPointLightElement")}}</li> + <li>{{domxref("SVGFESpecularLightingElement")}}</li> + <li>{{domxref("SVGFESpotLightElement")}}</li> + <li>{{domxref("SVGFETileElement")}}</li> + <li>{{domxref("SVGFETurbulenceElement")}}</li> + <li>{{domxref("SVGFEFuncRElement")}}</li> + <li>{{domxref("SVGFEFuncGElement")}}</li> + <li>{{domxref("SVGFEFuncBElement")}}</li> + <li>{{domxref("SVGFEFuncAElement")}}</li> + <li>{{domxref("SVGFilterElement")}}</li> + <li>{{domxref("SVGFilterPrimitiveStandardAttributes")}}</li> + <li>{{domxref("SVGFontElement")}}</li> + <li>{{domxref("SVGFontFaceElement")}}</li> + <li>{{domxref("SVGFontFaceFormatElement")}}</li> + <li>{{domxref("SVGFontFaceNameElement")}}</li> + <li>{{domxref("SVGFontFaceSrcElement")}}</li> + <li>{{domxref("SVGFontFaceUriElement")}}</li> + <li>{{domxref("SVGForeignObjectElement")}}</li> + <li>{{domxref("SVGGElement")}}</li> + <li>{{domxref("SVGGlyphElement")}}</li> + <li>{{domxref("SVGGlyphRefElement")}}</li> + <li>{{domxref("SVGGradientElement")}}</li> + <li>{{domxref("SVGHKernElement")}}</li> + <li>{{domxref("SVGImageElement")}}</li> + <li>{{domxref("SVGLinearGradientElement")}}</li> + <li>{{domxref("SVGLineElement")}}</li> + <li>{{domxref("SVGMarkerElement")}}</li> + <li>{{domxref("SVGMaskElement")}}</li> + <li>{{domxref("SVGMetadataElement")}}</li> + <li>{{domxref("SVGMissingGlyphElement")}}</li> + <li>{{domxref("SVGMPathElement")}}</li> + <li>{{domxref("SVGPathElement")}}</li> + <li>{{domxref("SVGPatternElement")}}</li> + <li>{{domxref("SVGPolylineElement")}}</li> + <li>{{domxref("SVGPolygonElement")}}</li> + <li>{{domxref("SVGRadialGradientElement")}}</li> + <li>{{domxref("SVGRectElement")}}</li> + <li>{{domxref("SVGScriptElement")}}</li> + <li>{{domxref("SVGSetElement")}}</li> + <li>{{domxref("SVGStopElement")}}</li> + <li>{{domxref("SVGStyleElement")}}</li> + <li>{{domxref("SVGSVGElement")}}</li> + <li>{{domxref("SVGSwitchElement")}}</li> + <li>{{domxref("SVGSymbolElement")}}</li> + <li>{{domxref("SVGTextElement")}}</li> + <li>{{domxref("SVGTextPathElement")}}</li> + <li>{{domxref("SVGTitleElement")}}</li> + <li>{{domxref("SVGTRefElement")}}</li> + <li>{{domxref("SVGTSpanElement")}}</li> + <li>{{domxref("SVGUseElement")}}</li> + <li>{{domxref("SVGViewElement")}}</li> + <li>{{domxref("SVGVKernElement")}}</li> +</ul> +</div> + +<h3 id="SVG_data_type_interfaces">SVG data type interfaces</h3> + +<p>Here are the DOM API for data types used in the definitions of SVG properties and attributes.</p> + +<div class="note"> +<p><strong>Note:</strong> Starting in {{Gecko("5.0")}}, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed ; in addition, they have a length property indicating the number of items in the lists: {{domxref("SVGLengthList")}}, {{domxref("SVGNumberList")}}, {{domxref("SVGPathSegList")}}, and {{domxref("SVGPointList")}}.</p> +</div> + +<h4 id="Static_type">Static type</h4> + +<div class="index"> +<ul> + <li>{{domxref("SVGAngle")}}</li> + <li>{{domxref("SVGColor")}}</li> + <li>{{domxref("SVGICCColor")}}</li> + <li>{{domxref("SVGElementInstance")}}</li> + <li>{{domxref("SVGElementInstanceList")}}</li> + <li>{{domxref("SVGLength")}}</li> + <li>{{domxref("SVGLengthList")}}</li> + <li>{{domxref("SVGMatrix")}}</li> + <li>{{domxref("SVGNumber")}}</li> + <li>{{domxref("SVGNumberList")}}</li> + <li>{{domxref("SVGPaint")}}</li> + <li>{{domxref("SVGPoint")}}</li> + <li>{{domxref("SVGPointList")}}</li> + <li>{{domxref("SVGPreserveAspectRatio")}}</li> + <li>{{domxref("SVGRect")}}</li> + <li>{{domxref("SVGStringList")}}</li> + <li>{{domxref("SVGTransform")}}</li> + <li>{{domxref("SVGTransformList")}}</li> +</ul> +</div> + +<h4 id="Animated_type">Animated type</h4> + +<div class="index"> +<ul> + <li>{{domxref("SVGAnimatedAngle")}}</li> + <li>{{domxref("SVGAnimatedBoolean")}}</li> + <li>{{domxref("SVGAnimatedEnumeration")}}</li> + <li>{{domxref("SVGAnimatedInteger")}}</li> + <li>{{domxref("SVGAnimatedLength")}}</li> + <li>{{domxref("SVGAnimatedLengthList")}}</li> + <li>{{domxref("SVGAnimatedNumber")}}</li> + <li>{{domxref("SVGAnimatedNumberList")}}</li> + <li>{{domxref("SVGAnimatedPreserveAspectRatio")}}</li> + <li>{{domxref("SVGAnimatedRect")}}</li> + <li>{{domxref("SVGAnimatedString")}}</li> + <li>{{domxref("SVGAnimatedTransformList")}}</li> +</ul> +</div> + +<h3 id="SMIL_related_interfaces">SMIL related interfaces</h3> + +<div class="index"> +<ul> + <li>{{domxref("ElementTimeControl")}}</li> + <li>{{domxref("TimeEvent")}}</li> +</ul> +</div> + +<h3 id="Other_SVG_interfaces">Other SVG interfaces</h3> + +<div class="index"> +<ul> + <li>{{domxref("SVGAnimatedPathData")}}</li> + <li>{{domxref("SVGAnimatedPoints")}}</li> + <li>{{domxref("SVGColorProfileRule")}}</li> + <li>{{domxref("SVGCSSRule")}}</li> + <li>{{domxref("SVGExternalResourcesRequired")}}</li> + <li>{{domxref("SVGFitToViewBox")}}</li> + <li>{{domxref("SVGLangSpace")}}</li> + <li>{{domxref("SVGLocatable")}}</li> + <li>{{domxref("SVGRenderingIntent")}}</li> + <li>{{domxref("SVGStylable")}}</li> + <li>{{domxref("SVGTests")}}</li> + <li>{{domxref("SVGTextContentElement")}}</li> + <li>{{domxref("SVGTextPositioningElement")}}</li> + <li>{{domxref("SVGTransformable")}}</li> + <li>{{domxref("SVGUnitTypes")}}</li> + <li>{{domxref("SVGURIReference")}}</li> + <li>{{domxref("SVGViewSpec")}}</li> + <li>{{domxref("SVGZoomAndPan")}}</li> +</ul> +</div> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/DOM/DOM_Reference/Examples">DOM Examples</a></li> +</ul> diff --git a/files/vi/web/api/document_object_model/introduction/index.html b/files/vi/web/api/document_object_model/introduction/index.html new file mode 100644 index 0000000000..7a1ef163ee --- /dev/null +++ b/files/vi/web/api/document_object_model/introduction/index.html @@ -0,0 +1,223 @@ +--- +title: Introduction to the DOM +slug: Web/API/Document_Object_Model/Introduction +translation_of: Web/API/Document_Object_Model/Introduction +--- +<p>Phần này cung cấp một giới thiệu khái niệm ngắn gọn về <a href="https://developer.mozilla.org/en-US/docs/DOM" title="DOM">DOM</a>: nó là gì, nó cung cấp cấu trúc cho HTML và XML như thế nào, bạn có thể truy cập nó thế nào, và API này trình bày thông tin và các ví dụ tham khảo.</p> + +<h2 id="What_is_the_DOM" name="What_is_the_DOM">DOM là gì?</h2> + +<p>The Document Object Model (DOM) là một giao diện lập trình cho tài liệu HTML và XML. Nó cung cấp đại diện cấu trúc của tài liệu và nó xác định con đường mà cấu trúc có thể được truy cập từ các chương trình để chúng có thể thay đổi cấu trúc, phong cách và nội dung tài liệu. DOM cung cấp một sự trình bày của tài liệu như một nhóm cấu trúc của các nút và đối tượng mà có các thuộc tính và phương thức. Về cơ bản, nó kết nối các trang web tới các đoạn mã hay các ngôn ngữ lập trình.</p> + +<p>Một trang Web là một tài liệu. Tài liệu này có thể hoặc là được hiển thị trong cửa sổ trình duyệt hoặc là như mã nguồn HTML. Nhưng nó cùng là tài liệu trong cả hai trường hợp. The Document Object Model (DOM) cung cấp cách khác để hiển thị, lưu trữ và thao tác cùng tài liệu. DOM là một đại diện hướng đối tượng hoàn toàn của trang web, và nó có thể được chỉnh sửa với một ngôn ngữ kịch bản như JavaScript.</p> + +<p>Các tiêu chuẩn <a class="external" href="http://www.w3.org/DOM/">W3C DOM</a> và <a class="external" href="https://dom.spec.whatwg.org">WHATWG DOM</a> tạo thành nền tảng của DOM được thực hiện trong hầu hết các trình duyệt hiện đại . Nhiều trình duyệt cung cấp các mở rộng bên ngoài chuẩn, nên phải cẩn thận khi sử dụng chúng trên web nơi các tài liệu có thể được truy cập bởi các trình duyệt khác nhau với các DOM khác nhau.</p> + +<p>Ví dụ, DOM chuẩn quy định rằng phương thức getElementsByTagName trong code bên dưới phải trả về một danh sách của tất cả phần tử <p> trong tài liệu:</p> + +<pre class="brush: js">var paragraphs = document.getElementsByTagName("P"); +// paragraphs[0] is the first <p> element +// paragraphs[1] is the second <p> element, etc. +alert(paragraphs[0].nodeName); +</pre> + +<p>Tất cả các thuộc tính, phương thức và sự kiện được sử dụng để thao tác và tạo ra các trang web được tổ chức dưới dạng các đối tượng (objects) (vd: đối tượng <code>document</code> đại diện cho trang tài liệu, đối tượng <code>table</code> kế thừa từ <code>HTMLTableElement</code>, một DOM interface đặc thù, cho phép truy cập HTML tables, v.v...). Phần này sẽ giới thiệu từng đối tượng DOM, được kế thừa trong các trình duyệt chạy trên nền Gecko.</p> + +<h2 id="DOM_and_JavaScript" name="DOM_and_JavaScript">DOM and JavaScript</h2> + +<p>The short example above, like nearly all of the examples in this reference, is <a href="/en-US/docs/JavaScript" title="JavaScript">JavaScript</a>. That is to say, it's <em>written</em> in JavaScript, but it <em>uses</em> the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements). Every element in a document—the document as a whole, the head, tables within the document, table headers, text within the table cells—is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like JavaScript.</p> + +<p>In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities. The page content is stored in the DOM and may be accessed and manipulated via JavaScript, so that we may write this approximative equation:</p> + +<p>API (HTML or XML page) = DOM + JS (scripting language)</p> + +<p>The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API. Though we focus exclusively on JavaScript in this reference documentation, implementations of the DOM can be built for any language, as this Python example demonstrates:</p> + +<pre class="brush: python"># Python DOM example +import xml.dom.minidom as m +doc = m.parse("C:\\Projects\\Py\\chap1.xml"); +doc.nodeName # DOM property of document object; +p_list = doc.getElementsByTagName("para"); +</pre> + +<p>For more information on what technologies are involved in writing JavaScript on the web, see <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h2 id="How_Do_I_Access_the_DOM.3F" name="How_Do_I_Access_the_DOM.3F">How Do I Access the DOM?</h2> + +<p>You don't have to do anything special to begin using the DOM. Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance to the actual DOM standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible to script.</p> + +<p>When you create a script–whether it's inline in a <code><script></code> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the <code><a href="/en-US/docs/DOM/document" title="DOM/document">document</a></code> or <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the <code><a href="/en-US/docs/DOM/window.alert" title="DOM/window.alert">alert()</a></code> function from the <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.</p> + +<pre class="brush: html"><body onload="window.alert('Welcome to my home page!');"> +</pre> + +<p>Aside from the <code><script></code> element in which the JavaScript is defined, this JavaScript sets a function to run when the document is loaded (and when the whole DOM is available for use). This function creates a new H1 element, adds text to that element, and then adds the <code>H1</code> to the tree for this document:</p> + +<pre class="brush: html"><html> + <head> + <script> + // run this function when the document is loaded + window.onload = function() { + + // create a couple of elements in an otherwise empty HTML page + var heading = document.createElement("h1"); + var heading_text = document.createTextNode("Big Head!"); + heading.appendChild(heading_text); + document.body.appendChild(heading); + } + </script> + </head> + <body> + </body> +</html> +</pre> + +<h2 id="Important_Data_Types" name="Important_Data_Types">Important Data Types</h2> + +<p>This reference tries to describe the various objects and types in as simple a way as possible. But there are a number of different data types being passed around the API that you should be aware of. For the sake of simplicity, syntax examples in this API reference typically refer to nodes as <code>element</code>s, to arrays of nodes as <code>nodeList</code>s (or simply <code>element</code>s), and to <code>attribute</code> nodes simply as <code>attribute</code>s.</p> + +<p>The following table briefly describes these data types.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>document</code></td> + <td>When a member returns an object of type <code>document</code> (e.g., the <strong><code>ownerDocument</code></strong> property of an element returns the <code>document</code> to which it belongs), this object is the root <code>document</code> object itself. The <a href="/en-US/docs/DOM/document" title="DOM/document">DOM <code>document</code> Reference</a> chapter describes the <code>document</code> object.</td> + </tr> + <tr> + <td><code>element</code></td> + <td><code>element</code> refers to an element or a node of type <code>element</code> returned by a member of the DOM API. Rather than saying, for example, that the <a href="/en-US/docs/Web/API/Document/createElement">document.createElement()</a> method returns an object reference to a <code>node</code>, we just say that this method returns the <code>element</code> that has just been created in the DOM. <code>element</code> objects implement the DOM <code>Element</code> interface and also the more basic <code>Node</code> interface, both of which are included together in this reference.</td> + </tr> + <tr> + <td><code>nodeList</code></td> + <td>A <code>nodeList</code> is an array of elements, like the kind that is returned by the method <a href="/en-US/docs/Web/API/Document/getElementsByTagName">document.getElementsByTagName()</a>. Items in a <code>nodeList</code> are accessed by index in either of two ways: + <ul> + <li>list.item(1)</li> + <li>list[1]</li> + </ul> + These two are equivalent. In the first, <strong><code>item()</code></strong> is the single method on the <code>nodeList</code> object. The latter uses the typical array syntax to fetch the second item in the list.</td> + </tr> + <tr> + <td><code>attribute</code></td> + <td>When an <code>attribute</code> is returned by a member (e.g., by the <strong><code>createAttribute()</code></strong> method), it is an object reference that exposes a special (albeit small) interface for attributes. Attributes are nodes in the DOM just like elements are, though you may rarely use them as such.</td> + </tr> + <tr> + <td><code>namedNodeMap</code></td> + <td>A <code>namedNodeMap</code> is like an array, but the items are accessed by name or index, though this latter case is merely a convenience for enumeration, as they are in no particular order in the list. A <code>namedNodeMap</code> has an item() method for this purpose, and you can also add and remove items from a <code>namedNodeMap</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="DOM_interfaces" name="DOM_interfaces">DOM interfaces</h2> + +<p>This guide is about the objects and the actual <em>things</em> you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the <code>HTML form</code> element gets its <strong><code>name</code></strong> property from the <code>HTMLFormElement</code> interface but its <strong><code>className</code></strong> property from the <code>HTMLElement</code> interface proper. In both cases, the property you want is simply in that form object.</p> + +<p>But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.</p> + +<h3 id="Interfaces_and_Objects" name="Interfaces_and_Objects">Interfaces and Objects</h3> + +<p>Many objects borrow from several different interfaces. The table object, for example, implements a specialized <a href="/en-US/docs/DOM/HTMLTableElement" title="DOM/table">HTML Table Element Interface</a>, which includes such methods as <code>createCaption</code> and <code>insertRow</code>. But since it's also an HTML element, <code>table</code> implements the <code>Element</code> interface described in the <a href="/en-US/docs/DOM/element" title="DOM/element">DOM <code>element</code> Reference</a> chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table element also implements the more basic <code>Node</code> interface, from which <code>Element</code> derives.</p> + +<p>When you get a reference to a <code>table</code> object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.</p> + +<pre class="brush: js">var table = document.getElementById("table"); +var tableAttrs = table.attributes; // Node/Element interface +for (var i = 0; i < tableAttrs.length; i++) { + // HTMLTableElement interface: border attribute + if(tableAttrs[i].nodeName.toLowerCase() == "border") + table.border = "1"; +} +// HTMLTableElement interface: summary attribute +table.summary = "note: increased border"; +</pre> + +<h3 id="Core_Interfaces_in_the_DOM" name="Core_Interfaces_in_the_DOM">Core Interfaces in the DOM</h3> + +<p>This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the <a href="/en-US/docs/Gecko_DOM_Reference/Examples" title="Gecko_DOM_Reference/Examples">DOM Examples</a> chapter at the end of this book.</p> + +<p><code>Document</code> and <code>window</code> objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the <code>window</code> object represents something like the browser, and the <code>document</code> object is the root of the document itself. <code>Element</code> inherits from the generic <code>Node</code> interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the <code>table</code> object example in the previous section.</p> + +<p>The following is a brief list of common APIs in web and XML page scripting using the DOM.</p> + +<ul> + <li><code><a href="/en-US/docs/DOM/document.getElementById" title="DOM/document.getElementById">document.getElementById</a>(id)</code></li> + <li><code>document.<a href="/en-US/docs/Web/API/Element.getElementsByTagName" title="DOM/element.getElementsByTagName">getElementsByTagName</a>(name)</code></li> + <li><code><a href="/en-US/docs/DOM/document.createElement" title="DOM/document.createElement">document.createElement</a>(name)</code></li> + <li><code>parentNode.<a href="/en-US/docs/DOM/Node.appendChild" title="DOM/Node.appendChild">appendChild</a>(node)</code></li> + <li><code>element.<a href="/en-US/docs/DOM/element.innerHTML" title="DOM/element.innerHTML">innerHTML</a></code></li> + <li><code>element.<a href="/en-US/docs/DOM/element.style" title="DOM/element.style">style</a>.left</code></li> + <li><code>element.<a href="/en-US/docs/DOM/element.setAttribute" title="DOM/element.setAttribute">setAttribute</a></code></li> + <li><code>element.<a href="/en-US/docs/DOM/element.getAttribute" title="DOM/element.getAttribute">getAttribute</a></code></li> + <li><code>element.<a href="/en-US/docs/DOM/element.addEventListener" title="DOM/element.addEventListener">addEventListener</a></code></li> + <li><code><a href="/en-US/docs/DOM/window.content" title="DOM/window.content">window.content</a></code></li> + <li><code><a href="/en-US/docs/DOM/window.onload" title="DOM/window.onload">window.onload</a></code></li> + <li><code><a href="/en-US/docs/DOM/window.dump" title="DOM/window.dump">window.dump</a></code></li> + <li><code><a href="/en-US/docs/DOM/window.scrollTo" title="DOM/window.scrollTo">window.scrollTo</a></code></li> +</ul> + +<h2 id="Testing_the_DOM_API" name="Testing_the_DOM_API">Testing the DOM API</h2> + +<p>This document provides samples for every interface that you can use in your own web development. In some cases, the samples are complete HTML pages, with the DOM access in a <code><script></code> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as well. When this is the case, you can cut and paste the example into a new HTML document, save it, and run the example from the browser.</p> + +<p>There are some cases, however, when the examples are more concise. To run examples that only demonstrate the basic relationship of the interface to the HTML elements, you may want to set up a test page in which interfaces can be easily accessed from scripts. The following very simple web page provides a <code><script></code> element in the header in which you can place functions that test the interface, a few HTML elements with attributes that you can retrieve, set, or otherwise manipulate, and the web user interface necessary to call those functions from the browser.</p> + +<p>You can use this test page or create a similar one to test the DOM interfaces you are interested in and see how they work on the browser platform. You can update the contents of the <code>test()</code> function as needed, create more buttons, or add elements as necessary.</p> + +<pre class="brush: html"><html> + <head> + <title>DOM Tests</title> + <script type="application/javascript"> + function setBodyAttr(attr, value){ + if (document.body) eval('document.body.'+attr+'="'+value+'"'); + else notSupported(); + } + </script> + </head> + <body> + <div style="margin: .5in; height: 400;"> + <p><b><tt>text</tt></b></p> + <form> + <select onChange="setBodyAttr('text', + this.options[this.selectedIndex].value);"> + <option value="black">black + <option value="darkblue">darkblue + </select> + <p><b><tt>bgColor</tt></b></p> + <select onChange="setBodyAttr('bgColor', + this.options[this.selectedIndex].value);"> + <option value="white">white + <option value="lightgrey">gray + </select> + <p><b><tt>link</tt></b></p> + <select onChange="setBodyAttr('link', + this.options[this.selectedIndex].value);"> + <option value="blue">blue + <option value="green">green + </select> <small> + <a href="http://www.brownhen.com/dom_api_top.html" id="sample"> + (sample link)</a></small><br> + </form> + <form> + <input type="button" value="version" onclick="ver()" /> + </form> + </div> + </body> +</html> +</pre> + +<p>To test a lot of interfaces in a single page-for example, a "suite" of properties that affect the colors of a web page-you can create a similar test page with a whole console of buttons, textfields, and other HTML elements. The following screenshot gives you some idea of how interfaces can be grouped together for testing.</p> + +<figure> +<figcaption>Figure 0.1 Sample DOM Test Page</figcaption> +<img alt="Image:DOM_Ref_Introduction_to_the_DOM.gif" class="internal" src="/@api/deki/files/173/=DOM_Ref_Introduction_to_the_DOM.gif"></figure> + +<p>In this example, the dropdown menus dynamically update such DOM-accessible aspects of the web page as its background color (<code>bgColor</code>), the color of the hyperlinks (<code>aLink</code>), and color of the text (<code>text</code>). However you design your test pages, testing the interfaces as you read about them is an important part of learning how to use the DOM effectively.</p> + +<h2 id="Subnav">Subnav</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a></li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model/Introduction">Introduction to the DOM</a></li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model/Events">Events and the DOM</a></li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model/Examples">Examples</a></li> +</ul> diff --git a/files/vi/web/api/eventsource/index.html b/files/vi/web/api/eventsource/index.html new file mode 100644 index 0000000000..36a35382dd --- /dev/null +++ b/files/vi/web/api/eventsource/index.html @@ -0,0 +1,127 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Communications + - EventSource + - Interface + - NeedsTranslation + - Reference + - Server Sent Events + - Server-sent events + - TopicStub + - messaging +translation_of: Web/API/EventSource +--- +<div>{{APIRef("Server Sent Events")}}</div> + +<p><span class="seoSummary">The <strong><code>EventSource</code></strong> interface is web content's interface to <a href="/en-US/docs/Web/API/Server-sent_events">server-sent events</a>. An <code>EventSource</code> instance opens a persistent connection to an <a href="/en-US/docs/Web/HTTP">HTTP</a> server, which sends <a href="/en-US/docs/Web/API/Document_Object_Model/Events">events</a> in <code>text/event-stream</code> format.</span> The connection remains open until closed by calling {{domxref("EventSource.close()")}}.</p> + +<p>Once the connection is opened, incoming messages from the server are delivered to your code in the form of {{event("message")}} events.</p> + +<p>Unlike <a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a>, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, <code>EventSource</code> is a useful approach for handling things like social media status updates, news feeds, or delivering data into a <a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">client-side storage</a> mechanism like <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> or <a href="/en-US/docs/Web/API/Web_Storage_API">web storage</a>.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("EventSource.EventSource", "EventSource()")}}</dt> + <dd>Creates a new <code>EventSource</code> to handle receiving server-sent events from a specified URL, optionally in credentials mode.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface also inherits properties from its parent, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("EventSource.readyState")}} {{readonlyinline}}</dt> + <dd>A number representing the state of the connection. Possible values are <code>CONNECTING</code> (<code>0</code>), <code>OPEN</code> (<code>1</code>), or <code>CLOSED</code> (<code>2</code>).</dd> + <dt>{{domxref("EventSource.url")}} {{readonlyinline}}</dt> + <dd>A {{domxref("DOMString")}} representing the URL of the source.</dd> + <dt>{{domxref("EventSource.withCredentials")}} {{readonlyinline}}</dt> + <dd>A {{domxref("Boolean")}} indicating whether the <code>EventSource</code> object was instantiated with cross-origin (<a href="/en-US/docs/Web/HTTP/CORS">CORS</a>) credentials set (<code>true</code>), or not (<code>false</code>, the default).</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("EventSource.onerror")}}</dt> + <dd>Is an {{domxref("EventHandler")}} called when an error occurs and the {{domxref("EventSource/error_event", "error")}} event is dispatched on an <code>EventSource</code> object.</dd> + <dt>{{domxref("EventSource.onmessage")}}</dt> + <dd>Is an {{domxref("EventHandler")}} called when a {{domxref("EventSource/message_event", "message")}} event is received, that is when a message is coming from the source.</dd> + <dt>{{domxref("EventSource.onopen")}}</dt> + <dd>Is an {{domxref("EventHandler")}} called when an {{domxref("EventSource/open_event", "open")}} event is received, that is when the connection was just opened.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface also inherits methods from its parent, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("EventSource.close()")}}</dt> + <dd>Closes the connection, if any, and sets the <code>readyState</code> attribute to <code>CLOSED</code>. If the connection is already closed, the method does nothing.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt>{{domxref("EventSource/error_event", "error")}}</dt> + <dd>Fired when a connection to an event source failed to open.</dd> + <dt>{{domxref("EventSource/message_event", "message")}}</dt> + <dd>Fired when data is received from an event source.</dd> + <dt>{{domxref("EventSource/open_event", "open")}}</dt> + <dd>Fired when a connection to an event source has opened.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>In this basic example, an <code>EventSource</code> is created to receive events from the server; a page with the name <code>sse.php</code> is responsible for generating the events.</p> + +<pre class="brush: js">var evtSource = new EventSource('sse.php'); +var eventList = document.querySelector('ul'); + +evtSource.onmessage = function(e) { + var newElement = document.createElement("li"); + + newElement.textContent = "message: " + e.data; + eventList.appendChild(newElement); +}</pre> + +<p>Each received event causes our <code>EventSource</code> object's <code>onmessage</code> event handler to be run. It, in turn, creates a new {{HTMLElement("li")}} element and writes the message's data into it, then appends the new element to the list element already in the document.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find a full example on GitHub — see <a href="https://github.com/mdn/dom-examples/tree/master/server-sent-events">Simple SSE demo using PHP.</a></p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<ul> +</ul> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.EventSource")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Server-sent_events">Server-sent events</a></li> + <li><a href="/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">Using server-sent events</a></li> +</ul> diff --git a/files/vi/web/api/eventsource/url/index.html b/files/vi/web/api/eventsource/url/index.html new file mode 100644 index 0000000000..2af6554db0 --- /dev/null +++ b/files/vi/web/api/eventsource/url/index.html @@ -0,0 +1,59 @@ +--- +title: EventSource.url +slug: Web/API/EventSource/url +translation_of: Web/API/EventSource/url +--- +<div>{{APIRef('WebSockets API')}}</div> + +<p><code><strong>url</strong></code> là thuộc tính chỉ đọc của giao diện {{domxref("EventSource")}} trả về {{domxref("DOMString")}} đại diện cho URL của nguồn.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">var myUrl = eventSource.url;</pre> + +<h3 id="Giá_trị">Giá trị</h3> + +<p>{{domxref("DOMString")}} đại diện cho URL của nguồn.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">var evtSource = new EventSource('sse.php'); +console.log(evtSource.url);</pre> + +<div class="note"> +<p><strong>Ghi chú: </strong>bạn có thể xem ví dụ đầy đủ trên GitHub — xem <a href="https://github.com/mdn/dom-examples/tree/master/server-sent-events">Simple SSE demo using PHP.</a></p> +</div> + +<h2 id="Thông_số_kĩ_thuật">Thông số kĩ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kĩ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "comms.html#dom-eventsource-url", "url")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Định nghĩa ban đầu</td> + </tr> + </tbody> +</table> + +<ul> +</ul> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<div> + + +<p>{{Compat("api.EventSource.url")}}</p> +</div> + +<h2 id="Liên_quan">Liên quan</h2> + +<ul> + <li>{{domxref("EventSource")}}</li> +</ul> diff --git a/files/vi/web/api/fetch_api/index.html b/files/vi/web/api/fetch_api/index.html new file mode 100644 index 0000000000..cc728a4eb1 --- /dev/null +++ b/files/vi/web/api/fetch_api/index.html @@ -0,0 +1,100 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +translation_of: Web/API/Fetch_API +--- +<div>{{DefaultAPISidebar("Fetch API")}}</div> + +<p class="summary"><span class="seoSummary">The Fetch API cung cấp giao diện để tìm nạp tài nguyên (bao gồm thông qua mạng). It will seem familiar to anyone who has used {{DOMxRef("XMLHttpRequest")}}, but the new API provides a more powerful and flexible feature set.</span></p> + +<h2 id="Concepts_and_usage">Concepts and usage</h2> + +<p>Fetch cung cấp một định nghĩa chung về các đối tượng {{DOMxRef("Request")}} and {{DOMxRef("Response")}} (và mọi thứ khác liên quan đến các request network). Điều này cho phép chúng được sử dụng ở bất cứ nơi nào cần chúng trong tương lai, cho dù đó là service workers, Cache API, và những thứ tương tự khác mà có khả năng xử lý hoặc sửa đổi các request và responses, hoặc bất kỳ trường hợp nào mà yêu cầu bạn tự tạo ra responses trong chương trình của chính mình.</p> + +<p>Nó cũng cung cấp một định nghĩa cho các khái niệm liên quan như CORS and the HTTP Header, thay thế các định nghĩa riêng biệt của chúng ở nơi khác.</p> + +<p>Để thực hiện một request và tìm nạp tài nguyên, use the {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} method. Nó được triển khai trong nhiều interfaces, đặc biệt là {{DOMxRef("Window")}} và {{DOMxRef("WorkerGlobalScope")}}. Điều này làm cho nó có sẵn trong hầu hết mọi ngữ cảnh mà bạn có thể muốn tìm nạp tài nguyên.</p> + +<p>The <code>fetch()</code> method có một đối số bắt buộc, đó chính là đường dẫn đến tài nguyên bạn tìm nạp. Nó returns a {{DOMxRef("Promise")}} thứ mà sẽ giải quyết và đưa ra một {{DOMxRef("Response")}} cho request đó, bất kể là thành công hay thất bại. Bạn có thể tùy chỉnh việc truyền một đối tượng tùy chỉnh init như là một đối số thữ hai (see {{DOMxRef("Request")}}).</p> + +<p>Cho đến khi một {{DOMxRef("Response")}} được truy xuất, có một số methods có sẵn để xác định nội dung body là gì và cách nó được xử lý như thế nào. (see {{DOMxRef("Body")}}).</p> + +<p>Bạn có thể tạo ra một request và response trực tiếp bằng cách sử dụng {{DOMxRef("Request.Request", "Request()")}} và {{DOMxRef("Response.Response", "Response()")}} constructors, nhưng cách làm này là không phổ biến. Thay vào đó, những thứ này có thể được tạo ra bằng cách là kết quả trả về của các hành động API khác (ví dụ, {{DOMxRef("FetchEvent.respondWith()")}} from service workers).</p> + +<h3 id="Differences_from_jQuery">Differences from jQuery</h3> + +<p>The <code>fetch</code> khác với <code>jQuery.ajax()</code> in ba điểm chính sau:</p> + +<ul> + <li>The Promise được trả về từ <code>fetch()</code> <strong>sẽ không từ chối trạng thái lỗi</strong> ngay cả khi response là HTTP <code>404</code> or <code>500</code>. Thay vào đó, nó sẽ xử lý bình thường (với trạng thái OK được set thành <code>false</code>), và nó sẽ chỉ từ chối khi gặp lỗi network hoặc có bất cứ thứ gì ngăn chặn hoàn thành request.</li> + <li><code>fetch()</code> sẽ không nhận<strong> cross-site cookies. </strong>You không thể thiết lập một cross site session bằng <code>fetch()</code>. <code><a href="/en-US/docs/Web/HTTP/Headers/Set-Cookie">Set-Cookie</a></code> headers từ các site khác sẽ âm thầm bị bỏ qua.</li> + <li><code>fetch()</code> sẽ không<strong> send cookies</strong>, trừ khi bạn set the <code><var>credentials</var></code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters">init option</a>. + <ul> + <li>Từ <a href="https://github.com/whatwg/fetch/pull/585" rel="nofollow noopener">Tháng 8 25, 2017</a>: Thông số kĩ thuật đã thay đổi từ thông tin đăng nhập mặc định thành <code>same-origin</code>. Firefox đã thay đổi từ phiên bản 61.0b13.)</li> + </ul> + </li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: Tìm hiểu thêm về cách sử dụng Fetch API tại <a href="/en-US/docs/Web/API/Fetch_API/Using_Fetch">Using Fetch</a>, và học các khái niệm tại <a href="/en-US/docs/Web/API/Fetch_API/Basic_concepts">Fetch basic concepts</a>.</p> +</div> + +<h3 id="Huỷ_bỏ_fetch">Huỷ bỏ fetch</h3> + +<p>Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operations like Fetch and XHR to be aborted if they have not already completed. See the interface pages for more details.</p> + +<h2 id="Fetch_Interfaces">Fetch Interfaces</h2> + +<dl> + <dt>{{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}}</dt> + <dd>The <code>fetch()</code> method được sử dụng để tìm nạp tài nguyên.</dd> + <dt>{{DOMxRef("Headers")}}</dt> + <dd>Đại diện cho các response/request headers, cho phép bạn truy vấn chúng and thực hiện các hành động khác nhau phụ thuộc vào các kết quả..</dd> + <dt>{{DOMxRef("Request")}}</dt> + <dd>Đại điện cho một request tài nguyên.</dd> + <dt>{{DOMxRef("Response")}}</dt> + <dd>Đại điện cho một Response của một Request.</dd> +</dl> + +<h2 id="Fetch_mixin">Fetch mixin</h2> + +<dl> + <dt>{{DOMxRef("Body")}}</dt> + <dd>Cung cấp các methods liên quan đến body của response/request, cho phép bạn khai báo kiểu nội dung của chúng và cách chúng được xử lý.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fetch")}}</td> + <td>{{Spec2("Fetch")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Fetch_API/Using_Fetch">Using Fetch</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> + <li><a href="https://github.com/github/fetch">Fetch polyfill</a></li> + <li><a href="/en-US/docs/Web/API/Fetch_API/Basic_concepts">Fetch basic concepts</a></li> +</ul> diff --git a/files/vi/web/api/file/index.html b/files/vi/web/api/file/index.html new file mode 100644 index 0000000000..3722df4e46 --- /dev/null +++ b/files/vi/web/api/file/index.html @@ -0,0 +1,99 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interface + - Reference + - Web +translation_of: Web/API/File +--- +<div>{{APIRef}}</div> + +<p><strong><code>File</code></strong> cung cấp thông tin về các tệp và cho phép Javascript truy cập nội dung của chúng.</p> + +<p><code>File</code> thường được lấy từ một {{DOMxRef("FileList")}} đối tượng trả về như là kết quả của người dùng chọn files sử dụng phần tử {{HTMLElement("input")}}, từ thao tác kéo và thả đối tượng {{DOMxRef("DataTransfer")}}, hoặc là từ <code>mozGetAsFile()</code> API trên một {{DOMxRef("HTMLCanvasElement")}}.</p> + +<p>Đối tượng file là một loại {{DOMxRef("Blob")}}, và có thể sử dụng trong mọi hoàn cảnh mà Blob có thể sử dụng. Cụ thể, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, và {{DOMxRef("XMLHttpRequest", "", "send()")}} chấp nhận cả <code>Blob</code>s và <code>File</code>s.</p> + +<p>Đọc <a href="/en-US/docs/Using_files_from_web_applications">Using files from web applications</a> để biết thêm thông tin và ví dụ.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{DOMxRef("File.File", "File()")}}</dt> + <dd>Trả về một constructed <code>File mới</code>.</dd> +</dl> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt>{{DOMxRef("File.lastModified")}} {{ReadOnlyInline}}</dt> + <dd>Trả về thời gian sửa đổi cuối cùng của file, tính bằng mili giây kể từ kỉ nguyên UNIX (January 1st, 1970 at Midnight).</dd> + <dt>{{DOMxRef("File.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}}</dt> + <dd>Returns the last modified {{JSxRef("Date")}} of the file referenced by the <code>File</code> object.</dd> + <dt>{{DOMxRef("File.name")}}{{ReadOnlyInline}}</dt> + <dd>Trả về tên của tệp referenced by the <code>File</code> object.</dd> + <dt>{{DOMxRef("File.webkitRelativePath")}} {{Non-standard_Inline}} {{ReadOnlyInline}}</dt> + <dd>Trả về đường dẫn (URL) của {{DOMxRef("File")}} có liên quan.</dd> +</dl> + +<p><code>File</code> bổ sung {{DOMxRef("Blob")}}, Vì vậy, nó cũng có các thuộc tính có sẵn:</p> + +<dl> + <dt>{{DOMxRef("File.size")}} {{ReadOnlyInline}}</dt> + <dd>Trả về kích thước của file (tính bằng bytes)</dd> + <dt>{{DOMxRef("File.type")}} {{ReadOnlyInline}}</dt> + <dd>Trả về thể loại <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME</a> của file file.</dd> +</dl> + +<h2 id="Phương_thức">Phương thức</h2> + +<p><em>File không có phương thức nào, nhưng nó thừa kế từ {{DOMxRef("Blob")}}:</em></p> + +<dl> + <dt>{{DOMxRef("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}</dt> + <dd>Trả về một đối tượng Blob mới có nội dung trong phạm vi bytes chỉ định của Blob</dd> + <dt>{{DOMxRef("Blob.stream()")}}</dt> + <dd>Chuyển đổi file thành {{DOMxRef("ReadableStream")}} vì vậy có thể sử dụng để đọc nội dung file.</dd> + <dt>{{DOMxRef("Blob.text()")}}</dt> + <dd>Chuyển đổi file thành stream và đọc nó để hoàn thành. Nó trả về một promise có thể giải quyết với {{DOMxRef("USVString")}} (text).</dd> + <dt>{{DOMxRef("Blob.arrayBuffer()")}}</dt> + <dd>Chuyển đổi file thành stream và đọc nó để hoàn thành. Nó trả về một promise có thể giải quyết với {{DOMxRef("ArrayBuffer")}}.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API', "#file-section", "The <code>File</code> interface")}}</td> + <td>{{Spec2('File API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden">Bảng tương thích trên trang này được tạo từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp cho dữ liệu, vui lòng xem https://github.com/mdn/browser-compat-data và gửi cho chúng tôi yêu cầu</div> + +<p>{{Compat("api.File")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Using files from web applications</a></li> + <li>{{DOMxRef("FileReader")}}</li> + <li><a href="/en-US/docs/Extensions/Using_the_DOM_File_API_in_chrome_code">Using the DOM File API in chrome code</a> (for privileged code running in Gecko, such as Firefox add-ons)</li> +</ul> diff --git a/files/vi/web/api/geolocation_api/index.html b/files/vi/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..0286a06249 --- /dev/null +++ b/files/vi/web/api/geolocation_api/index.html @@ -0,0 +1,244 @@ +--- +title: Geolocation API +slug: Web/API/Geolocation_API +translation_of: Web/API/Geolocation_API +--- +<p>{{securecontext_header}} {{APIRef("API định vị địa lý")}}</p> + +<p>Các <strong>API Định vị</strong> cho phép người dùng để cung cấp vị trí của họ vào các ứng dụng web nếu họ mong muốn. Vì lý do riêng tư, người dùng được yêu cầu cho phép báo cáo thông tin vị trí.</p> + +<h2 id="Đối_tượng_định_vị_địa_lý">Đối tượng định vị địa lý</h2> + +<p>Các <a href="/en-US/docs/Web/API/Geolocation">Định vị</a> API được công bố thông qua {{domxref( "navigator.geolocation")}} đối tượng.</p> + +<p>Nếu đối tượng tồn tại, dịch vụ định vị địa lý có sẵn. Do đó, bạn có thể kiểm tra sự hiện diện của vị trí địa lý:</p> + +<pre class="brush: js">if ("geolocation" in navigator) { + / * định vị địa lý có sẵn * / +} else { + / * định vị địa lý KHÔNG có sẵn * / +} +</pre> + +<div class="note"> +<p><strong>Lưu ý:</strong> Trên Firefox 24 và các phiên bản cũ hơn, <code>"geolocation" in navigator</code>luôn được trả về <code>true</code>ngay cả khi API bị tắt. Điều này đã được sửa với <a href="/en-US/docs/Mozilla/Firefox/Releases/25/Site_Compatibility">Firefox 25</a> để tuân thủ thông số kỹ thuật. ({{bug(884921)}}).</p> +</div> + +<h3 id="Lấy_vị_trí_hiện_tại">Lấy vị trí hiện tại</h3> + +<p>Để có được vị trí hiện tại của người dùng, bạn có thể gọi phương thức {{domxref("geolocation.getCurrentPosition()", "getCurrentPosition()")}}. Điều này bắt đầu một yêu cầu không đồng bộ để phát hiện vị trí của người dùng và truy vấn phần cứng định vị để có được thông tin cập nhật. Khi vị trí được xác định, chức năng gọi lại được xác định sẽ được thực thi. Bạn có thể tùy chọn cung cấp chức năng gọi lại thứ hai để được thực thi nếu xảy ra lỗi. Tham số thứ ba, tùy chọn, là một đối tượng tùy chọn trong đó bạn có thể đặt tuổi tối đa của vị trí được trả về, thời gian chờ yêu cầu và nếu bạn muốn độ chính xác cao cho vị trí.</p> + +<div class="note"> +<p><strong>Lưu ý:</strong> Theo mặc định, {{domxref("Geolocation.getCurrentPosition ()", "getCurrentPosition()")}} cố gắng trả lời nhanh nhất có thể với kết quả chính xác thấp. Nó rất hữu ích nếu bạn cần một câu trả lời nhanh bất kể độ chính xác. Chẳng hạn, các thiết bị có GPS có thể mất một phút hoặc hơn để sửa lỗi GPS, do đó, dữ liệu kém chính xác hơn(vị trí IP hoặc wifi) có thể được trả về {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition() ")}}.</p> +</div> + +<pre class="brush: js">navigator.geolocation.getCurrentPosition(function(position) { + do_something(location.coords.latitude, location.coords.longitude); +});</pre> + +<p>Ví dụ trên sẽ khiến <code>do_something()</code>hàm thực thi khi lấy được vị trí.</p> + +<h3 id="Xem_vị_trí_hiện_tại">Xem vị trí hiện tại</h3> + +<p>Nếu dữ liệu vị trí thay đổi (theo chuyển động của thiết bị hoặc nếu có thông tin địa lý chính xác hơn), bạn có thể thiết lập chức năng gọi lại được gọi với thông tin vị trí được cập nhật đó. Điều này được thực hiện bằng cách sử dụng hàm {{domxref("Geolocation.watchPocation ()", "watchPosition()")}}, có cùng tham số đầu vào như {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition() ")}}. Chức năng gọi lại được gọi nhiều lần, cho phép trình duyệt cập nhật vị trí của bạn khi bạn di chuyển hoặc cung cấp vị trí chính xác hơn vì các kỹ thuật khác nhau được sử dụng để định vị địa lý cho bạn. Hàm gọi lại lỗi, là tùy chọn giống như đối với {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition()")}}, có thể được gọi lặp lại.</p> + +<div class="note"> +<p><strong>Lưu ý:</strong> Bạn có thể sử dụng {{domxref("Geolocation.watchPosition()", "watchPosition()")}} mà không cần một cuộc gọi {{domxref("Geolocation.getCienPocation ()", "getCienPocation ()")}}.</p> +</div> + +<pre class="brush: js">var watchID = navigator.geolocation.watchPosition(function(location) { + do_something(location.coords.latitude, location.coords.longitude); +});</pre> + +<p>Phương thức {{domxref("Geolocation.watchPosition()", "watchPosition()")}} trả về số ID có thể được sử dụng để xác định duy nhất trình theo dõi vị trí được yêu cầu; bạn sử dụng giá trị này song song với phương thức {{domxref("Geolocation.clearWatch()", "clearWatch()")}} để dừng xem vị trí của người dùng.</p> + +<pre class="brush: js">navigator.geolocation.clearWatch(watchID); +</pre> + +<h3 id="Phản_ứng_tinh_chỉnh">Phản ứng tinh chỉnh</h3> + +<p>Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional <a href="/en-US/docs/Web/API/PositionOptions">PositionOptions</a> object.</p> + +<p>{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}</p> + +<p>A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:</p> + +<pre class="brush: js">function geo_success(position) { + do_something(position.coords.latitude, position.coords.longitude); +} + +function geo_error() { + alert("Sorry, no position available."); +} + +var geo_options = { + enableHighAccuracy: true, + maximumAge : 30000, + timeout : 27000 +}; + +var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);</pre> + +<h2 id="Describing_a_position">Describing a position</h2> + +<p>The user's location is described using a {{domxref("Position")}} object referencing a {{domxref("Coordinates")}} object.</p> + +<p>{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}</p> + +<p>{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}</p> + +<h2 id="Handling_errors">Handling errors</h2> + +<p>The error callback function, if provided when calling <code>getCurrentPosition()</code> or <code>watchPosition()</code>, expects a <a href="/en-US/docs/Web/API/PositionError">PositionError</a> object as its first parameter.</p> + +<pre class="brush: js">function errorCallback(error) { + alert('ERROR(' + error.code + '): ' + error.message); +}; +</pre> + +<p>{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}</p> + +<h2 id="Geolocation_Live_Example">Geolocation Live Example</h2> + +<div class="hidden"> +<pre class="brush: css">body { + padding: 20px; + background-color:#ffffc9 +} + +button { + margin: .5rem 0; +} +</pre> +</div> + +<h3 id="HTML_Content">HTML Content</h3> + +<pre class="brush: html;"><button id = "find-me">Show my location</button><br/> +<p id = "status"></p> +<a id = "map-link" target="_blank"></a> +</pre> + +<h3 id="JavaScript_Content">JavaScript Content</h3> + +<pre class="brush: js">function geoFindMe() { + + const status = document.querySelector('#status'); + const mapLink = document.querySelector('#map-link'); + + mapLink.href = ''; + mapLink.textContent = ''; + + function success(position) { + const latitude = position.coords.latitude; + const longitude = position.coords.longitude; + + status.textContent = ''; + mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`; + mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`; + } + + function error() { + status.textContent = 'Unable to retrieve your location'; + } + + if (!navigator.geolocation) { + status.textContent = 'Geolocation is not supported by your browser'; + } else { + status.textContent = 'Locating…'; + navigator.geolocation.getCurrentPosition(success, error); + } + +} + +document.querySelector('#find-me').addEventListener('click', geoFindMe); +</pre> + +<h3 id="Live_Result">Live Result</h3> + +<p>{{EmbedLiveSample('Geolocation_Live_Example', 350, 150, "", "", "", "geolocation")}}</p> + +<h2 id="Prompting_for_permission">Prompting for permission</h2> + +<p>Any add-on hosted on <a href="https://addons.mozilla.org/">addons.mozilla.org</a> which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the <code>pref</code> parameter, if applicable. The function provided in the <code>callback</code> parameter will be called with a boolean value indicating the user's response. If <code>true</code>, the add-on may access geolocation data.</p> + +<pre class="brush: js">function prompt(window, pref, message, callback) { + let branch = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + if (branch.getPrefType(pref) === branch.PREF_STRING) { + switch (branch.getCharPref(pref)) { + case "always": + return callback(true); + case "never": + return callback(false); + } + } + + let done = false; + + function remember(value, result) { + return function() { + done = true; + branch.setCharPref(pref, value); + callback(result); + } + } + + let self = window.PopupNotifications.show( + window.gBrowser.selectedBrowser, + "geolocation", + message, + "geo-notification-icon", + { + label: "Share Location", + accessKey: "S", + callback: function(notification) { + done = true; + callback(true); + } + }, [ + { + label: "Always Share", + accessKey: "A", + callback: remember("always", true) + }, + { + label: "Never Share", + accessKey: "N", + callback: remember("never", false) + } + ], { + eventCallback: function(event) { + if (event === "dismissed") { + if (!done) callback(false); + done = true; + window.PopupNotifications.remove(self); + } + }, + persistWhileVisible: true + }); +} + +prompt(window, + "extensions.foo-addon.allowGeolocation", + "Foo Add-on wants to know your location.", + function callback(allowed) { alert(allowed); }); +</pre> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("api.Geolocation")}}</p> + +<h3 id="khả_dụng">khả dụng</h3> + +<p>Vì định vị dựa trên WiFi thường được cung cấp bởi Google, API định vị vanilla có thể không khả dụng ở Trung Quốc. Bạn có thể sử dụng các nhà cung cấp bên thứ ba địa phương như <a href="http://lbsyun.baidu.com/index.php?title=jspopular/guide/geolocation">Baidu</a> , <a href="https://lbs.amap.com/api/javascript-api/guide/services/geolocation#geolocation">Autonavi</a> hoặc <a href="http://lbs.qq.com/tool/component-geolocation.html">Tencent</a> . Các dịch vụ này sử dụng địa chỉ IP của người dùng và / hoặc ứng dụng cục bộ để cung cấp định vị nâng cao.</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{domxref("navigator.geolocation")}}</li> + <li><a href="/en-US/Apps/Build/gather_and_modify_data/Plotting_yourself_on_the_map">Vẽ sơ đồ trên bản đồ</a></li> + <li><a href="https://www.w3.org/TR/geolocation-API/" rel="external">API định vị địa lý trên w3.org</a></li> + <li><a href="https://hacks.mozilla.org/2013/10/who-moved-my-geolocation/">Ai đã di chuyển vị trí địa lý của tôi? </a>(Blog hack)</li> +</ul> diff --git a/files/vi/web/api/htmlcanvaselement/getcontext/index.html b/files/vi/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..b2478fba5d --- /dev/null +++ b/files/vi/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,140 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - TV +translation_of: Web/API/HTMLCanvasElement/getContext +--- +<div>{{APIRef("Canvas API")}}</div> + +<p><span class="seoSummary">The <strong><code>HTMLCanvasElement.getContext()</code></strong> method returns a drawing context on the canvas, or {{jsxref("null")}} if the context identifier is not supported.</span></p> + +<p>Later calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same <code>contextType</code> argument. To get a different drawing context object you need to pass a different <code>contextType</code> or call the method on a different canvas element. </p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var <em>ctx</em> = <em>canvas</em>.getContext(<em>contextType</em>); +var <em>ctx</em> = <em>canvas</em>.getContext(<em>contextType</em>, <em>contextAttributes</em>); +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>contextType</code></dt> + <dd>Is a {{domxref("DOMString")}} containing the context identifier defining the drawing context associated to the canvas. Possible values are: + <ul> + <li><code>"2d"</code>, leading to the creation of a {{domxref("CanvasRenderingContext2D")}} object representing a two-dimensional rendering context.</li> + <li><code>"webgl"</code> (or <code>"experimental-webgl"</code>) which will create a {{domxref("WebGLRenderingContext")}} object representing a three-dimensional rendering context. This context is only available on browsers that implement <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL">WebGL</a> version 1 (OpenGL ES 2.0).</li> + <li><code>"webgl2"</code> which will create a {{domxref("WebGL2RenderingContext")}} object representing a three-dimensional rendering context. This context is only available on browsers that implement <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL">WebGL</a> version 2 (OpenGL ES 3.0). {{experimental_inline}}</li> + <li><code>"bitmaprenderer"</code> which will create an {{domxref("ImageBitmapRenderingContext")}} which only provides functionality to replace the content of the canvas with a given {{domxref("ImageBitmap")}}.</li> + </ul> + + <div class="note"> + <p><strong>Note</strong>: The identifier <code>"experimental-webgl"</code> is used in new implementations of WebGL. These implementations have either not reached test suite conformance, or the graphics drivers on the platform are not yet stable. The <a href="https://www.khronos.org/">Khronos Group</a> certifies WebGL implementations under certain <a href="https://www.khronos.org/registry/webgl/sdk/tests/CONFORMANCE_RULES.txt">conformance rules</a>.</p> + </div> + </dd> + <dt><code>contextAttributes</code></dt> + <dd> + <p>You can use several context attributes when creating your rendering context, for example:</p> + + <pre class="brush: js">const gl = canvas.getContext('webgl', { + antialias: false, + depth: false +});</pre> + 2d context attributes: + + <ul> + <li><strong><code>alpha</code></strong>: Boolean that indicates if the canvas contains an alpha channel. If set to <code>false</code>, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images.</li> + <li>{{non-standard_inline}} (Gecko only) <strong><code>willReadFrequently</code></strong>: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} frequently. This option is only available, if the flag <code>gfx.canvas.willReadFrequently.enable</code> is set to <code>true</code> (which, by default, is only the case for B2G/Firefox OS).</li> + <li>{{non-standard_inline}} (Blink only) <strong><code>storage</code></strong>: String that indicates which storage is used ("persistent" by default).</li> + </ul> + WebGL context attributes: + + <ul> + <li><strong><code>alpha</code></strong>: Boolean that indicates if the canvas contains an alpha buffer.</li> + <li><strong><code>antialias</code></strong>: Boolean that indicates whether or not to perform anti-aliasing.</li> + <li><strong><code>depth</code></strong>: Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits.</li> + <li><code><strong>failIfMajorPerformanceCaveat</strong></code>: Boolean that indicates if a context will be created if the system performance is low.</li> + <li><code><strong>powerPreference</strong></code>: A hint to the user agent indicating what configuration of GPU is suitable for the WebGL context. Possible values are: + <ul> + <li><code>"default"</code>: Let the user agent decide which GPU configuration is most suitable. This is the default value.</li> + <li><code>"high-performance"</code>: Prioritizes rendering performance over power consumption.</li> + <li><code>"low-power"</code>: Prioritizes power saving over rendering performance.</li> + </ul> + </li> + <li><strong><code>premultipliedAlpha</code></strong>: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha.</li> + <li><strong><code>preserveDrawingBuffer</code></strong>: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.</li> + <li><strong><code>stencil</code></strong>: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits.</li> + </ul> + </dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A {{domxref("RenderingContext")}} which is either a</p> + +<ul> + <li>{{domxref("CanvasRenderingContext2D")}} for <code>"2d"</code>,</li> + <li>{{domxref("WebGLRenderingContext")}} for <code>"webgl"</code> and <code>"experimental-webgl"</code>,</li> + <li>{{domxref("WebGL2RenderingContext")}} for <code>"webgl2"</code> or</li> + <li>{{domxref("ImageBitmapRenderingContext")}} for <code>"bitmaprenderer"</code>.</li> +</ul> + +<p>If the <code>contextType</code> doesn't match a possible drawing context, <code>null</code> is returned.</p> + +<h2 id="Examples">Examples</h2> + +<p>Given this {{HTMLElement("canvas")}} element:</p> + +<pre class="brush: html"><canvas id="canvas" width="300" height="300"></canvas> +</pre> + +<p>You can get a <code>2d</code> context of the canvas with the following code:</p> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); +console.log(ctx); // CanvasRenderingContext2D { ... } +</pre> + +<p>Now you have the <a href="/en-US/docs/Web/API/CanvasRenderingContext2D">2D rendering context</a> for a canvas and you can draw within it.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since the latest snapshot, {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "semantics-scripting.html#dom-htmlcanvaselement-getcontext", "HTMLCanvasElement.getContext")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.HTMLCanvasElement.getContext")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The interface defining it, {{domxref("HTMLCanvasElement")}}.</li> + <li>{{domxref("OffscreenCanvas.getContext()")}}</li> + <li>Available rendering contexts: {{domxref("CanvasRenderingContext2D")}}, {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} and {{domxref("ImageBitmapRenderingContext")}}.</li> +</ul> diff --git a/files/vi/web/api/htmlcanvaselement/index.html b/files/vi/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..50b2592322 --- /dev/null +++ b/files/vi/web/api/htmlcanvaselement/index.html @@ -0,0 +1,114 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLCanvasElement +--- +<div> +<div>{{APIRef("Canvas API")}}</div> +</div> + +<p>The <strong><code>HTMLCanvasElement</code></strong> interface provides properties and methods for manipulating the layout and presentation of {{HtmlElement("canvas")}} elements. The <code>HTMLCanvasElement</code> interface also inherits the properties and methods of the {{domxref("HTMLElement")}} interface.</p> + +<p>{{InheritanceDiagram(600, 120)}}</p> + +<h2 id="Properties">Properties</h2> + +<p><em>Inherits properties from its parent, </em><em>{{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLCanvasElement.height")}}</dt> + <dd>Is a positive <code>integer</code> reflecting the {{htmlattrxref("height", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of <code>150</code> is used.</dd> + <dt>{{domxref("HTMLCanvasElement.width")}}</dt> + <dd>Is a positive <code>integer</code> reflecting the {{htmlattrxref("width", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of <code>300</code> is used.</dd> + <dt>{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Is a {{jsxref("Boolean")}} reflecting the {{htmlattrxref("moz-opaque", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported in Mozilla-based browsers; use the standardized {{domxref("HTMLCanvasElement.getContext()", "canvas.getContext('2d', { alpha: false })")}} instead.</dd> + <dt>{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}</dt> + <dd>Is a <code>function</code> that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the <a href="https://searchfox.org/mozilla-central/search?q=interface MozCanvasPrintState&path=HTMLCanvasElement.webidl">MozCanvasPrintState</a> interface. The callback can get the context to draw to from the printState object and must then call done() on it when finished. The purpose of <code>mozPrintCallback</code> is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. <a href="https://blog.mozilla.org/labs/2012/09/a-new-way-to-control-printing-output/">See this blog post.</a></dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parent, </em><em>{{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}</dt> + <dd>Returns a {{domxref("CanvasCaptureMediaStream")}} that is a real-time video capture of the surface of the canvas.</dd> + <dt>{{domxref("HTMLCanvasElement.getContext()")}}</dt> + <dd>Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with <code>"2d"</code> returns a {{domxref("CanvasRenderingContext2D")}} object, whereas calling it with <code>"webgl"</code> (or <code>"experimental-webgl"</code>) returns a {{domxref("WebGLRenderingContext")}} object. This context is only available on browsers that implement <a href="/en-US/docs/Web/WebGL">WebGL</a>.</dd> + <dt>{{domxref("HTMLCanvasElement.toDataURL()")}}</dt> + <dd>Returns a data-URL containing a representation of the image in the format specified by the <code>type</code> parameter (defaults to <code>png</code>). The returned image is in a resolution of 96dpi.</dd> + <dt>{{domxref("HTMLCanvasElement.toBlob()")}}</dt> + <dd>Creates a {{domxref("Blob")}} object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.</dd> + <dt>{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}</dt> + <dd>Transfers control to an {{domxref("OffscreenCanvas")}} object, either on the main thread or on a worker.</dd> + <dt>{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns a {{domxref("File")}} object representing the image contained in the canvas; this file is a memory-based file, with the specified <code>name</code>. If <code>type</code> is not specified, the image type is <code>image/png</code>.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<p>Listen to these events using <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>.</p> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/HTMLCanvasElement/webglcontextcreationerror_event">webglcontextcreationerror</a></code></dt> + <dd>Fired if the user agent is unable to create a <code>WebGLRenderingContext</code> or <code>WebGL2RenderingContext</code> context.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event">webglcontextlost</a></code></dt> + <dd>Fired if the user agent detects that the drawing buffer associated with a <code>WebGLRenderingContext</code> or <code>WebGL2RenderingContext</code> object has been lost.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event">webglcontextrestored</a></code></dt> + <dd>Fired if the user agent restores the drawing buffer for a <code>WebGLRenderingContext</code> or <code>WebGL2RenderingContext</code> object.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}</td> + <td>{{Spec2('Media Capture DOM Elements')}}</td> + <td>Adds the method <code>captureStream()</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#htmlcanvaselement", "HTMLCanvasElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>The method <code>getContext()</code> now returns a {{domxref("RenderingContext")}} rather than an opaque <code>object</code>.<br> + The <code>transferControlToOffscreen()</code>method has been added.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.HTMLCanvasElement")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>HTML element implementing this interface: {{HTMLElement("canvas")}}</li> +</ul> diff --git a/files/vi/web/api/htmlelement/dataset/index.html b/files/vi/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..44ce2c7393 --- /dev/null +++ b/files/vi/web/api/htmlelement/dataset/index.html @@ -0,0 +1,139 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +tags: + - API + - HTML DOM + - HTMLElement + - Tham khảo + - Thuộc tính + - dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p><span class="seoSummary">The <code><strong>dataset</strong></code> property on the {{domxref("HTMLElement")}} interface provides read/write access to all the <a href="/en/HTML/Global_attributes#attr-data-*" title="https://developer.mozilla.org/en/HTML/Global_attributes#attr-data-*">custom data attributes</a> (<code>data-*</code>) set on the element.</span> This access is available both in HTML and within the DOM. It is a <a href="/en/DOM/DOMStringMap" title="en/DOM/DOMStringMap">map of DOMString</a>, one entry for each custom data attribute. Note that the<strong> </strong><code>dataset</code><strong> </strong>property itself can be read, but not directly written. Instead, all writes must be to the individual properties within the <code>dataset</code>, which in turn represent the data attributes. Note also that an HTML <code><strong>data-</strong></code><em>attribute</em> and its corresponding DOM<strong> </strong><code>dataset.</code><em>property</em> do not share the same name, but they are always similar:</p> + +<ul> + <li>The name of a custom data attribute in HTML begins with <code>data-</code>. It must contain only letters, numbers and the following characters: dash (<code>-</code>), dot (<code>.</code>), colon (<code>:</code>), underscore (<code>_</code>) -- but NOT any ASCII capital letters (<code>A</code> to <code>Z</code>).</li> + <li>The name of a custom data attribute in JavaScript is the name of the same HTML attribute but in camelCase and with no dashes, dots, etc.</li> +</ul> + +<p>In addition to the information below, you'll find a how-to guide for using HTML data attributes in our article <a href="/en-US/docs/Learn/HTML/Howto/Use_data_attributes">Using data attributes.</a></p> + +<h3 id="Chuyển_đổi_tên">Chuyển đổi tên</h3> + +<p>Từ <code>dash-style</code> (kiểu-gạch-nối) sang <code>camelCase</code> (bướuLạcĐà): Tên thuộc tính dữ liệu tùy biến được chuyển đổi thành khóa cho {{ domxref("DOMStringMap") }} dự trên quy định sau:</p> + +<ul> + <li>Loại bỏ tiền tố <code>data-</code> (cùng gạch nối);</li> + <li>những gạch nối (<code>U+002D</code>) theo sau chữ cái in thường ASCII, từ <code>a</code><span style="line-height: 1.5;"> tới </span><code>z</code><span style="line-height: 1.5;">, sẽ bị loại bỏ và chữ cái đó sẽ chuyển đổi thành dạng in hoa;</span></li> + <li>những ký tự còn lại (bao gồm gạch nối khác) được giữ nguyên.</li> +</ul> + +<p>Từ <code>camelCase</code> (bướuLạcĐà) sang <code>dash-style</code> (kiểu-gạch-nối): Cách chuyển đổi ngược lại, dò theo khóa để tìm ra tên thuộc tính, bằng quy định sau:</p> + +<ul> + <li>Rằng buộc: Gạch nối bị cấm đi liền đuôi chữ cái (từ <code>a</code> đến <code>z</code>) ở dạng in thường ASCII (trước khi biến đổi);</li> + <li>thêm tiền tố <code>data-</code>;</li> + <li>bất cứ chữ cái in hoa ASCII từ <code>A</code> tới <code>Z</code> sẽ được đổi thành gạch nối theo sau chữ cái dạng in thường tương ứng.</li> + <li>những ký tự còn lại không đổi.</li> +</ul> + +<p>Việc có rằng buộc trong quy định trên nhằm đảm bảo việc chuyển đổi có thể đảo ngược cho nhau.</p> + +<p>Ví dụ, thuộc tính có tên <code>data-abc-def</code> sẽ có khóa tương ứng <code>abcDef</code>.</p> + +<ul> +</ul> + +<h3 id="Truy_cập_giá_trị">Truy cập giá trị</h3> + +<ul> + <li>Attributes can be set and read by using the camelCase name (the key) like an object property of the dataset, as in <em>element.</em>dataset.<em>keyname</em></li> + <li>Attributes can also be set and read using the object-properties bracket-syntax, as in <em>element.</em>dataset[<em>keyname</em>]</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/in">Toán tử in</a> có thể dùng để kiểm tra xem thuộc tính đó có (tồn tại) hay không.</li> +</ul> + +<h3 id="Loại_giá_trị">Loại giá trị</h3> + +<ul> + <li>Khi một thuộc tính được gán, giá trị dữ liệu đó sẽ luôn được chuyển đổi thành định dạng chuỗi. Ví dụ, <code>null</code> sẽ được chuyển thành chuỗi <code>"null"</code>.</li> + <li>Phòng khi cần xóa thuộc tính, ta có thể dùng <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">toán tử delete</a>. (tiếng Anh)</li> +</ul> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<ul> + <li><em>string</em> = <em>element</em>.<strong>dataset</strong>.<em>camelCasedName</em>;</li> + <li><em>element.</em><strong>dataset</strong>.<em>camelCasedName</em> = <em>string</em>;</li> + <br> + <li><em>string</em> = <em>element</em>.<strong>dataset[<em>camelCasedName</em>]</strong>;</li> + <li><em>element</em>.<strong>dataset[<em>camelCasedName</em>]</strong> = <em>string</em>;</li> + <br> + <li>Thuộc tính dữ liệu tùy biến cũng có thể gán trực tiếp bằng thẻ HTML, nhưng tên thuộc tính buộc phải dùng cú pháp <code>data-</code> như trên.</li> +</ul> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: html"><div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div></pre> + +<pre class="brush: js">const el = document.querySelector('#user'); + +// el.id == 'user' +// el.dataset.id === '1234567890' +// el.dataset.user === 'johndoe' +// el.dataset.dateOfBirth === '' + +// gán dữ liệu cho thuộc tính data +el.dataset.dateOfBirth = '1960-10-03'; +// Kết quả: el.dataset.dateOfBirth === 1960-10-03 + +delete el.dataset.dateOfBirth; +// Kết quả: el.dataset.dateOfBirth === undefined + +// 'someDataAttr' in el.dataset === false +el.dataset.someDataAttr = 'mydata'; +// Kết quả: 'someDataAttr' in el.dataset === true +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from latest snapshot, {{SpecName('HTML5.1')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}}, initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + + + +<p>{{Compat("api.HTMLElement.dataset")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>Lớp HTML <code><a href="/en-US/docs/Web/HTML/Global_attributes/data-*"><strong>data-*</strong></a></code> của thuộc tính phổ thông (global).</li> + <li><a href="/en-US/docs/Learn/HTML/Howto/Use_data_attributes">Using data attributes</a> (Tiếng Anh)</li> + <li>{{domxref("Element.getAttribute()")}} và {{domxref("Element.setAttribute()")}}</li> +</ul> diff --git a/files/vi/web/api/htmlelement/index.html b/files/vi/web/api/htmlelement/index.html new file mode 100644 index 0000000000..1a625a2a5b --- /dev/null +++ b/files/vi/web/api/htmlelement/index.html @@ -0,0 +1,268 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +tags: + - API + - HTML DOM + - Interface +translation_of: Web/API/HTMLElement +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>Interface <strong><code>HTMLElement</code></strong> đại diện cho mọi phần tử <a href="/en-US/docs/Web/HTML" title="/en-US/docs/Web/HTML">HTML</a>. Một vài phần tử sử dụng trực tiếp interface này, một vài phần tử khác lại sử dụng nó thông qua các lớp khác kế thừa nó.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Các_thuộc_tính">Các thuộc tính</h2> + +<p><em>Được kế thừa từ {{domxref("Element")}}, và sử dụng chúng từ {{domxref("GlobalEventHandlers")}} và {{domxref("TouchEventHandlers")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLElement.accessKey")}}</dt> + <dd>Là một {{domxref("DOMString")}} trả về từ khoá truy cập được gán cho phần tử.</dd> + <dt>{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}</dt> + <dd>Trả về một {{domxref("DOMString")}} chứa các từ khoá truy cập đã được gán của phần tử.</dd> + <dt>{{domxref("HTMLElement.contentEditable")}}</dt> + <dd>Là một {{domxref("DOMString")}}, nếu giá trị là <code>"true"</code>, ta có thể chỉnh sửa phần tử này và ngược lại nếu giá trị là <code>"false"</code>.</dd> + <dt>{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}</dt> + <dd>Trả về giá trị {{domxref("Boolean")}} cho biết nội dung của phần tử có được phép chỉnh sửa hay không.</dd> + <dt>{{domxref("HTMLElement.contextMenu")}} {{deprecated_inline}}</dt> + <dd>Là một {{domxref("HTMLMenuElement")}} trả về một menu tóm lược liên kết các phần tử. Giá trị có thể là <code>null</code>.</dd> + <dt>{{domxref("HTMLElement.dataset")}} {{readonlyInline}}</dt> + <dd>Trả về một {{domxref("DOMStringMap")}} cho phép ta thao tác với <a href="/en-US/docs/Web/Guide/HTML/Using_data_attributes">các thuộc tính dữ liệu tùy biến</a> của phần tử (<code>data-*</code>) .</dd> + <dt>{{domxref("HTMLElement.dir")}}</dt> + <dd>Là một {{domxref("DOMString")}}, tương tự với thuộc tính global <code>dir</code>, đại diện cho hướng hiển thị của phần tử. Các giá trị cho phép là <code>"ltr"</code>, <code>"rtl"</code>, và <code>"auto"</code>.</dd> + <dt>{{domxref("HTMLElement.draggable")}}</dt> + <dd>Có kiểu {{jsxref("Boolean")}} cho ta biết phần tử có thể được kéo (drag) hay không.</dd> + <dt>{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}</dt> + <dd>Trả về một {{domxref("DOMSettableTokenList")}} tương tự với thuộc tính global <code>dropzone</code> mô tả hành vi của phần tử liên quan đến hành động thả (drop).</dd> + <dt>{{domxref("HTMLElement.hidden")}}</dt> + <dd>Có kiểu {{jsxref("Boolean")}} cho ta biết phần tử có ẩn hay không.</dd> + <dt>{{domxref("HTMLElement.inert")}}</dt> + <dd>Có kiểu {{jsxref("Boolean")}} cho ta biết <a href="https://en.wikipedia.org/wiki/User_agent">user agent</a> must act as though the given node is absent đối với các sự kiện tương tác của người dùng, tìm kiếm văn bản trong trang, và lựa chọn văn bản.</dd> + <dt>{{domxref("HTMLElement.innerText")}}</dt> + <dd>Trả về nội dung văn bản được "render" từ một node và phần tử con của nó. Điều này tương tự với việc người dùng bôi đen văn bản và sao chép chúng.</dd> + <dt>{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}</dt> + <dd>Có kiểu {{jsxref("Boolean")}} cho biết scope của item.</dd> + <dt>{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Trả về một {{domxref("DOMSettableTokenList")}}…</dd> + <dt>{{domxref("HTMLElement.itemId")}} {{experimental_inline}}</dt> + <dd>Là một {{domxref("DOMString")}} cho biết ID của item.</dd> + <dt>{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Là một {{domxref("DOMSettableTokenList")}}…</dd> + <dt>{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Trả về một {{domxref("DOMSettableTokenList")}}…</dd> + <dt>{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}</dt> + <dd>Trả về một {{jsxref("Object")}} cho biết giá trị của item.</dd> + <dt>{{domxref("HTMLElement.lang")}}</dt> + <dd>Là một {{domxref("DOMString")}} cho biết ngôn ngữ của thuộc tính của một phần tử, của văn bản và của nội dung phần tử đó.</dd> + <dt>{{domxref("HTMLElement.noModule")}}</dt> + <dd>Có kiểu {{jsxref("Boolean")}} cho biết rằng việc nhúng đoạn script có thể được thực thi bởi <a href="https://en.wikipedia.org/wiki/User_agent">user agent</a> (có hỗ trợ module scripts) hay không.</dd> + <dt>{{domxref("HTMLElement.nonce")}}</dt> + <dd>Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.</dd> + <dt>{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a <code>double</code> containing the height of an element, relative to the layout.</dd> + <dt>{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a <code>double</code>, the distance from this element's left border to its <code>offsetParent</code>'s left border.</dd> + <dt>{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("Element")}} that is the element from which all offset calculations are currently computed.</dd> + <dt>{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a <code>double</code>, the distance from this element's top border to its <code>offsetParent</code>'s top border.</dd> + <dt>{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a <code>double</code> containing the width of an element, relative to the layout.</dd> + <dt>{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("HTMLPropertiesCollection")}}…</dd> + <dt>{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}</dt> + <dd>Is a {{jsxref("Boolean")}} that controls <a href="/en-US/docs/HTML/Controlling_spell_checking_in_HTML_forms" title="en/Controlling_spell_checking_in_HTML_forms">spell-checking</a>. It is present on all HTML elements, though it doesn't have an effect on all of them.</dd> + <dt>{{domxref("HTMLElement.style")}}</dt> + <dd>Is a {{domxref("CSSStyleDeclaration")}}, an object representing the declarations of an element's style attributes.</dd> + <dt>{{domxref("HTMLElement.tabIndex")}}</dt> + <dd>Is a <code>long</code> representing the position of the element in the tabbing order.</dd> + <dt>{{domxref("HTMLElement.title")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the text that appears in a popup box when mouse is over the element.</dd> + <dt>{{domxref("HTMLElement.translate")}} {{experimental_inline}}</dt> + <dd>Is a {{jsxref("Boolean")}} representing the translation.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<p>Most event handler properties, of the form <code>onXYZ</code>, are defined on the {{domxref("GlobalEventHandlers")}} or {{domxref("TouchEventHandlers")}} interfaces and implemented by <code>HTMLElement</code>. In addition, the following handlers are specific to <code>HTMLElement</code>.</p> + +<dl> + <dt>{{ domxref("HTMLElement.oncopy") }} {{ non-standard_inline() }}</dt> + <dd>Returns the event handling code for the <code>copy</code> event ({{bug("280959")}}).</dd> + <dt>{{ domxref("HTMLElement.oncut") }} {{ non-standard_inline() }}</dt> + <dd>Returns the event handling code for the <code>cut</code> event ({{bug("280959")}}).</dd> + <dt>{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}</dt> + <dd>Returns the event handling code for the <code>paste</code> event ({{bug("280959")}}).</dd> + <dt>{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchstart")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchend")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchmove")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchenter")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchleave")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchcancel")}} event.</dd> +</dl> + +<h2 id="Các_phương_thức">Các phương thức</h2> + +<p><em>Được kế thừa từ {{domxref("Element")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLElement.blur()")}}</dt> + <dd>Bỏ truy cập phần tử hiện tại.</dd> + <dt>{{domxref("HTMLElement.click()")}}</dt> + <dd>Gửi một sự kiện click chuột đến phần tử.</dd> + <dt>{{domxref("HTMLElement.focus()")}}</dt> + <dd>Truy cập đến phần tử hiện tại (truy cập bằng cách click vào phần tử hoặc nhấn phím <kbd>Tab</kbd> để di chuyển đến).</dd> + <dt>{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}</dt> + <dd>Kiểm tra chính tả nội dung của phần tử.</dd> +</dl> + +<h2 id="Các_sự_kiện">Các sự kiện</h2> + +<p>Bắt các sự kiện bằng cách sự dụng phương thức <code>addEventListener()</code> hoặc bằng cách gán một thuộc tính sự sự kiện <code>on_tên_sự_kiện</code> dựa trên interface này.</p> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/invalid_event">invalid</a></code></dt> + <dd>Được gọi khi một phần tử không thỏa điều kiện khi đang xác minh (validation) thông tin.<br> + Dùng tương tự với thuộc tính <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/oninvalid">oninvalid</a></code>.</dd> +</dl> + +<h3 id="Các_sự_kiện_animation">Các sự kiện animation</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/animationcancel_event">animationcancel</a></code></dt> + <dd>Được gọi khi một animation dừng đột ngột.<br> + Dùng tương tự với thuộc tính <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationcancel">onanimationcancel</a></code>.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/animationend_event">animationend</a></code></dt> + <dd>Được gọi khi một animation kết thúc.<br> + Dùng tương tự với thuộc tính <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationend">onanimationend</a></code>.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/animationiteration_event">animationiteration</a></code></dt> + <dd>Được gọi khi một vòng lặp animation kết thúc.<br> + Dùng tương tự với thuộc tính <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationiteration">onanimationiteration</a></code>.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/animationstart_event">animationstart</a></code></dt> + <dd>Fired when an animation starts.<br> + Dùng tương tự với thuộc tính <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationstart">onanimationstart</a></code>.</dd> +</dl> + +<h3 id="Các_sự_kiện_input">Các sự kiện input</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/beforeinput_event">beforeinput</a></code></dt> + <dd>Được gọi khi giá trị của một phần tử {{HTMLElement("input")}}, {{HTMLElement("select")}}, hoặc {{HTMLElement("textarea")}} sắp được chỉnh sửa.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/input_event">input</a></code></dt> + <dd>Được gọi khi giá trị của một phần tử {{HTMLElement("input")}}, {{HTMLElement("select")}}, hoặc {{HTMLElement("textarea")}} đã được chỉnh sửa.<br> + Dùng tương tự với thuộc tính <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/oninput">oninput</a></code>.</dd> +</dl> + +<h3 id="Pointer_events">Pointer events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/gotpointercapture_event">gotpointercapture</a></code></dt> + <dd>Fired when an element captures a pointer using <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/setPointerCapture">setPointerCapture()</a></code>.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/ongotpointercapture">ongotpointercapture</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/lostpointercapture_event">lostpointercapture</a></code></dt> + <dd>Fired when a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events#Pointer_capture">captured pointer</a> is released.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onlostpointercapture">onlostpointercapture</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointercancel_event">pointercancel</a></code></dt> + <dd>Fired when a pointer event is canceled.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointercancel">onpointercancel</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointerdown_event">pointerdown</a></code></dt> + <dd>Fired when a pointer becomes active.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointerdown">onpointerdown</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointerenter_event">pointerenter</a></code></dt> + <dd>Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointerenter">onpointerenter</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointerleave_event">pointerleave</a></code></dt> + <dd>Fired when a pointer is moved out of the hit test boundaries of an element.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointerleave">onpointerleave</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointermove_event">pointermove</a></code></dt> + <dd>Fired when a pointer changes coordinates.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointermove">onpointermove</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointerout_event">pointerout</a></code></dt> + <dd>Fired when a pointer is moved out of the <em>hit test</em> boundaries of an element (among other reasons).<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointerout">onpointerout</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointerover_event">pointerover</a></code></dt> + <dd>Fired when a pointer is moved into an element's hit test boundaries.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointerover">onpointerover</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLElement/pointerup_event">pointerup</a></code></dt> + <dd>Fired when a pointer is no longer active.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onpointerup">onpointerup</a></code> property.</dd> +</dl> + +<h3 class="highlight-spanned" id="Các_sự_kiện_transition"><span class="highlight-span">Các sự kiện transition</span></h3> + +<dl> + <dt><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitioncancel_event">transitioncancel</a></code></dt> + <dd>Được gọi khi một <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> bị hủy.<br> + Dùng tương tự với thuộc tính <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/ontransitioncancel">ontransitioncancel</a></code>.</dd> + <dt><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitionend_event">transitionend</a></code></dt> + <dd>Được gọi khi một <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> hoàn thành.<br> + Dùng tương tự với thuộc tính <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/ontransitionend">ontransitionend</a></code>.</dd> + <dt><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitionrun_event">transitionrun</a></code></dt> + <dd>Được gọi khi một <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> được tạo ra đầu tiên.<br> + Dùng tương tự với thuộc tính <code><a class="new" href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/ontransitionrun" rel="nofollow">ontransitionrun</a></code>.</dd> + <dt><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitionstart_event">transitionstart</a></code></dt> + <dd>Được gọi khi một <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> thực sự bắt đầu.<br> + Dùng tương tự với thuộc tính <code><a class="new" href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/ontransitionstart" rel="nofollow">ontransitionstart</a></code>.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Added the following properties: <code>offsetParent</code>, <code>offsetTop</code>, <code>offsetLeft</code>, <code>offsetWidth</code>, and <code>offsetHeight</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Added the following properties: <code>translate</code>, <code>itemScope</code>, <code>itemType</code>, <code>itemId</code>, <code>itemRef</code>, <code>itemProp</code>, <code>properties</code>, and <code>itemValue</code>.<br> + Added the following method: <code>forceSpellcheck()</code>.<br> + Moved the <code>onXYZ</code> attributes to the {{domxref("GlobalEventHandlers")}} interface and added an inheritance from it.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Added the following properties: <code>dataset</code>, <code>hidden</code>, <code>tabindex</code>, <code>accessKey</code>, <code>accessKeyLabel</code>, <code>draggable</code>, <code>dropzone</code>, <code>contentEditable</code>, <code>isContentEditable</code>, <code>contextMenu</code>, <code>spellcheck</code>, <code>commandType</code>, <code>commandLabel</code>, <code>commandIcon</code>, <code>commandHidden</code>, <code>commandDisabled</code>, <code>commandChecked</code>, <code>style</code>, and all the <code>onXYZ</code> properties.<br> + Moved the <code>id</code> and <code>className</code> properties to the {{domxref("Element")}} interface.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>No change from {{SpecName('DOM2 HTML')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_của_trình_duyệt">Khả năng tương thích của trình duyệt</h2> + + + +<p>{{Compat("api.HTMLElement")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{domxref("Element")}}</li> +</ul> diff --git a/files/vi/web/api/htmlformelement/index.html b/files/vi/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..1df37a6657 --- /dev/null +++ b/files/vi/web/api/htmlformelement/index.html @@ -0,0 +1,246 @@ +--- +title: HTMLFormElement +slug: Web/API/HTMLFormElement +tags: + - API + - DOM + - Form Element + - Forms + - HTML + - HTML DOM + - HTML Form Element + - HTML forms + - HTMLFormElement + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLFormElement +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><span class="seoSummary">The <strong>{{domxref("HTMLFormElement")}}</strong> interface represents a {{HTMLElement("form")}} element in the DOM; it allows access to and in some cases modification of aspects of the form, as well as access to its component elements.</span></p> + +<p>{{InheritanceDiagram(600,120)}}</p> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface also inherits properties from its parent, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLFormElement.elements")}} {{ReadOnlyInline}}</dt> + <dd>A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.</dd> + <dt>{{domxref("HTMLFormElement.length")}}{{ReadOnlyInline}}</dt> + <dd>A <code>long</code> reflecting the number of controls in the form.</dd> + <dt>{{domxref("HTMLFormElement.name")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.</dd> + <dt>{{domxref("HTMLFormElement.method")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.</dd> + <dt>{{domxref("HTMLFormElement.target")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.</dd> + <dt>{{domxref("HTMLFormElement.action")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.</dd> + <dt>{{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("enctype", "form") }} HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.</dd> + <dt>{{domxref("HTMLFormElement.acceptCharset")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("accept-charset", "form") }} HTML attribute, representing the character encoding that the server accepts.</dd> + <dt>{{domxref("HTMLFormElement.autocomplete")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("autocomplete", "form") }} HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.</dd> + <dt>{{domxref("HTMLFormElement.noValidate")}}</dt> + <dd>A {{jsxref("Boolean")}} reflecting the value of the form's {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating whether the form should not be validated.</dd> +</dl> + +<p>Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named <code>action</code> will have its <code>action</code> property return that input instead of the form's {{ htmlattrxref("action", "form") }} HTML attribute).</p> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface also inherits methods from its parent, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLFormElement.submit()")}}</dt> + <dd>Submits the form to the server.</dd> + <dt>{{domxref("HTMLFormElement.reset()")}}</dt> + <dd>Resets the form to its initial state.</dd> + <dt>{{domxref("HTMLFormElement.checkValidity()")}}</dt> + <dd>Returns <code>true</code> if the element's child controls are subject to <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">constraint validation</a> and satisfy those contraints; returns <code>false</code> if some controls do not satisfy their constraints. Fires an event named {{event("invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to <code>false</code>.</dd> + <dt>{{domxref("HTMLFormElement.reportValidity()")}}</dt> + <dd>Returns <code>true</code> if the element's child controls satisfy their <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">validation constraints</a>. When <code>false</code> is returned, cancelable {{Event("invalid")}} events are fired for each invalid child and validation problems are reported to the user.</dd> + <dt>{{domxref("HTMLFormElement.requestAutocomplete()")}} {{obsolete_inline}}</dt> + <dd>Triggers a native browser interface to assist the user in completing the fields which have an <a href="https://html.spec.whatwg.org/#autofill-field-name">autofill field name</a> value that is not <code>off</code> or <code>on</code>. The form will receive an event once the user has finished with the interface, the event will either be {{event("autocomplete")}} when the fields have been filled or {{event("autocompleteerror")}} when there was a problem. <strong>This method has been removed from Chrome and Firefox — see {{bug(1270740)}} for background information on why.</strong></dd> +</dl> + +<h2 id="Events">Events</h2> + +<p>Listen to these events using <code>addEventListener()</code> or by assigning an event listener to the <code>on<em>eventname</em></code> property of this interface.</p> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/HTMLFormElement/reset_event">reset</a></code></dt> + <dd><span style="display: none;"> </span>The <code>reset</code> event fires when a form is reset.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onreset">onreset</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/HTMLFormElement/submit_event">submit</a></code></dt> + <dd>The <code>submit</code> event fires when a form is submitted.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onsubmit">onsubmit</a></code> property.</dd> +</dl> + +<h2 id="Usage_notes">Usage notes</h2> + +<h3 id="Obtaining_a_form_element_object">Obtaining a form element object</h3> + +<p>To obtain an <code>HTMLFormElement</code> object, you can use a <a href="/en-US/docs/Web/CSS/CSS_Selectors">CSS selector</a> with {{domxref("ParentNode.querySelector", "querySelector()")}}, or you can get a list of all of the forms in the document using its {{domxref("Document.forms", "forms")}} property.</p> + +<p>{{domxref("Document.forms")}} returns an array of <code>HTMLFormElement</code> objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:</p> + +<dl> + <dt><code>document.forms[<em>index</em>]</code></dt> + <dd>Returns the form at the specified <code>index</code> into the array of forms.</dd> + <dt><code>document.forms[<em>id</em>]</code></dt> + <dd>Returns the form whose ID is <code>id</code>.</dd> + <dt><code>document.forms[<em>name</em>]</code></dt> + <dd>Returns the form whose {{domxref("Element.name", "name")}} attribute's value is <code>name</code>.</dd> +</dl> + +<h3 id="Accessing_the_forms_elements">Accessing the form's elements</h3> + +<p>You can access the list of the form's data-containing elements by examining the form's {{domxref("HTMLFormElement.elements", "elements")}} property. This returns an {{domxref("HTMLFormControlsCollection")}} listing all of the form's user data entry elements, both those which are descendants of the <code><form></code> and those which are made members of the form using their <code>form</code> attributes.</p> + +<h3 id="Elements_that_are_considered_form_controls">Elements that are considered form controls</h3> + +<p>The elements which are included by <code>HTMLFormElement.elements</code> and <code>HTMLFormElement.length</code> are:</p> + +<ul> + <li>{{HTMLElement("button")}}</li> + <li>{{HTMLElement("fieldset")}}</li> + <li>{{HTMLElement("input")}} (with the exception that any whose {{htmlattrxref("type", "input")}} is <code>"image"</code> are omitted for historical reasons)</li> + <li>{{HTMLElement("object")}}</li> + <li>{{HTMLElement("output")}}</li> + <li>{{HTMLElement("select")}}</li> + <li>{{HTMLElement("textarea")}}</li> +</ul> + +<p>No other elements are included in the list returned by <code>elements</code>, which makes it an excellent way to get at the elements most important when processing forms.</p> + +<h2 id="Examples">Examples</h2> + +<p>Creating a new form element, modifying its attributes, then submitting it:</p> + +<pre class="brush: js">var f = document.createElement("form");// Create a form +document.body.appendChild(f); // Add it to the document body +f.action = "/cgi-bin/some.cgi"; // Add action and method attributes +f.method = "POST"; +f.submit(); // Call the form's submit method +</pre> + +<p>Extract information from a form element and set some of its attributes:</p> + +<pre class="brush: html"><form name="formA" action="/cgi-bin/test" method="post"> + <p>Press "Info" for form details, or "Set" to change those details.</p> + <p> + <button type="button" onclick="getFormInfo();">Info</button> + <button type="button" onclick="setFormInfo(this.form);">Set</button> + <button type="reset">Reset</button> + </p> + + <textarea id="form-info" rows="15" cols="20"></textarea> +</form> + +<script> + function getFormInfo(){ + // Get a reference to the form via its name + var f = document.forms["formA"]; + // The form properties we're interested in + var properties = [ 'elements', 'length', 'name', 'charset', 'action', 'acceptCharset', 'action', 'enctype', 'method', 'target' ]; + // Iterate over the properties, turning them into a string that we can display to the user + var info = properties.map(function(property) { return property + ": " + f[property] }).join("\n"); + + // Set the form's <textarea> to display the form's properties + document.forms["formA"].elements['form-info'].value = info; + } + + function setFormInfo(f){ // Argument should be a form element reference. + f.action = "a-different-url.cgi"; + f.name = "a-different-name"; + } +</script> +</pre> + +<p>Submit a form into a new window:</p> + +<pre class="brush: html"><!doctype html> +<html> +<head> +<meta charset="utf-8"> +<title>Example new-window form submission</title> +</head> +<body> + +<form action="test.php" target="_blank"> + <p><label>First name: <input type="text" name="firstname"></label></p> + <p><label>Last name: <input type="text" name="lastname"></label></p> + <p><label><input type="password" name="pwd"></label></p> + + <fieldset> + <legend>Pet preference</legend> + <p><label><input type="radio" name="pet" value="cat"> Cat</label></p> + <p><label><input type="radio" name="pet" value="dog"> Dog</label></p> + </fieldset> + + <fieldset> + <legend>Owned vehicles</legend> + + <p><label><input type="checkbox" name="vehicle" value="Bike">I have a bike</label></p> + <p><label><input type="checkbox" name="vehicle" value="Car">I have a car</label></p> + </fieldset> + + <p><button>Submit</button></p> +</form> + +</body> +</html></pre> + +<h3 id="Submitting_forms_and_uploading_files_using_XMLHttpRequest">Submitting forms and uploading files using <code>XMLHttpRequest</code></h3> + +<p>If you want to know how to serialize and submit a form using the {{domxref("XMLHttpRequest")}} API, please read <a href="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files">this paragraph</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#htmlformelement", "HTMLFormElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>The following method has been added: <code>requestAutocomplete()</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "forms.html#the-form-element", "HTMLFormElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>The elements properties returns an {{domxref("HTMLFormControlsCollection")}} instead of a raw {{domxref("HTMLCollection")}}. This is mainly a technical change. The following method has been added: <code>checkValidity()</code>. The following properties have been added: <code>autocomplete</code>, <code>noValidate</code>, and <code>encoding</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-40002357', 'HTMLFormElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>No change</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-40002357', 'HTMLFormElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.HTMLFormElement")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The HTML element implementing this interface: {{ HTMLElement("form") }}.</li> +</ul> diff --git a/files/vi/web/api/htmlformelement/reset/index.html b/files/vi/web/api/htmlformelement/reset/index.html new file mode 100644 index 0000000000..dc68298cab --- /dev/null +++ b/files/vi/web/api/htmlformelement/reset/index.html @@ -0,0 +1,28 @@ +--- +title: HTMLFormElement.reset() +slug: Web/API/HTMLFormElement/reset +translation_of: Web/API/HTMLFormElement/reset +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>Phương thức HTMLFormEuity.reset () khôi phục các giá trị mặc định của thành phần biểu mẫu. Phương pháp này thực hiện tương tự như nhấp vào nút đặt lại của biểu mẫu</p> + +<p>Nếu một điều khiển biểu mẫu (chẳng hạn như nút đặt lại) có tên hoặc id của thiết lập lại, nó sẽ che dấu phương thức đặt lại của biểu mẫu. Nó không thiết lập lại các thuộc tính khác trong đầu vào, chẳng hạn như bị vô hiệu hóa.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>HTMLFormElement</em>.reset() +</pre> + +<h2 id="Example" name="Example">Example</h2> + +<pre class="brush: js">document.getElementById('myform').reset(); +</pre> + +<h2 id="Specification" name="Specification">Specification</h2> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.HTMLFormElement.reset")}}</p> diff --git a/files/vi/web/api/index.html b/files/vi/web/api/index.html new file mode 100644 index 0000000000..71e6573815 --- /dev/null +++ b/files/vi/web/api/index.html @@ -0,0 +1,34 @@ +--- +title: Web API Interfaces +slug: Web/API +tags: + - API + - Apps + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/API +--- +<p class="summary"><span class="seoSummary">Có rất nhiều API tốt khi viết Web bằng Javascript. Dưới đây là danh sách những interfaces (những kiểu object) mà bạn có thể sử dụng khi phát triển Web app hay Website.</span></p> + +<p>Web APIs thường được viết bởi JavaScript, nhưng không phải luôn là như vậy.</p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<p>Đây là danh sách tất cả những API sẵn có.</p> + +<div>{{ListGroups}}</div> + +<h2 id="Interfaces">Interfaces</h2> + +<p>Đây là danh sách tất cả những interfaces (những kiểu object) sẵn có.</p> + +<div>{{APIListAlpha}}</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/Events">Web API event reference</a></li> +</ul> diff --git a/files/vi/web/api/navigator/geolocation/index.html b/files/vi/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..4881071171 --- /dev/null +++ b/files/vi/web/api/navigator/geolocation/index.html @@ -0,0 +1,53 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +tags: + - API + - Bất động sản + - Geolocation API + - Tham khảo +translation_of: Web/API/Navigator/geolocation +--- +<div>{{securecontext_header}}{{APIRef("Geolocation API")}}</div> + +<p><strong><code>Navigator.geolocation</code></strong> với đặc tính chỉ cho đọc trả lại một đối tượng {{domxref("Geolocation")}} cho phép trang web truy cập thông tin địa điểm của thiết bị. Việc này cho phép trang web hoặc phần mềm đưa ra đề nghị chào hàng dựa trên vị trí của người dùng.</p> + +<div class="note"> +<p><strong>Ghi chú:</strong> Vì lý do bảo mật, khi một trang web cố gắng truy cập vị trí, người dùng sẽ được thông báo và hỏi cấp yêu cầu cho phép. Hãy cẩn thận vì mỗi trình duyệt web có chính sách và phương pháp khác nhau.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>geo</var> = <var>navigator</var>.geolocation +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Chi tiết kỹ thuật</th> + <th scope="col">Tình trạng</th> + <th scope="col">Ghi chú</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Geolocation', '#navi-geo', 'Navigator.geolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_vơi_trình_duyệt">Tương thích vơi trình duyệt</h2> + +<div class="hidden">Bảng tương thích ở trang này được tạo ra từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp dữ liệu, hãy truy cập <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi chúng tôi một đề nghị thi hành.</div> + +<p>{{Compat("api.Navigator.geolocation")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/WebAPI/Using_geolocation">Using geolocation</a></li> +</ul> diff --git a/files/vi/web/api/navigator/index.html b/files/vi/web/api/navigator/index.html new file mode 100644 index 0000000000..e9ab7a7b29 --- /dev/null +++ b/files/vi/web/api/navigator/index.html @@ -0,0 +1,186 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - DOM4 + - Interface + - Navigator + - NeedsTranslation + - Reference + - TopicStub + - Web + - Web Performance +translation_of: Web/API/Navigator +--- +<div>{{APIRef("DOM4")}}</div> + +<p>The <code><strong>Navigator</strong></code> interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.</p> + +<p>A <code>Navigator</code> object can be retrieved using the read-only {{domxref("window.navigator")}} property.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>Doesn't inherit any properties, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorage")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, and {{domxref("NavigatorUserMedia")}}.</em></p> + +<h3 id="Standard">Standard</h3> + +<dl> + <dt>{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is <code>true</code>).</dd> + <dt>{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.</dd> + <dt>{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.</dd> + <dt>{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.</dd> + <dt>{{domxref("Navigator.battery")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.</dd> + <dt>{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Provides a {{domxref("NetworkInformation")}} object containing information about the network connection of a device.</dd> + <dt>{{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}</dt> + <dd>Returns false if setting a cookie will be ignored and true otherwise.</dd> + <dt>{{domxref("Navigator.geolocation")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.</dd> + <dt>{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}</dt> + <dd>Returns the number of logical processor cores available.</dd> + <dt>{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.</dd> + <dt>{{domxref('Navigator.keyboard')}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns a {{domxref('Keyboard')}} object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.</dd> + <dt>{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The <code>null</code> value is returned when this is unknown.</dd> + <dt>{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}</dt> + <dd>Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.</dd> + <dt>{{domxref("Navigator.locks")}} {{readonlyinline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("LockManager")}} object which provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing {{domxref('Lock')}} object</dd> + <dt>{{domxref("Navigator.mediaCapabilities")}} {{readonlyinline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("MediaCapabilities")}} object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.</dd> + <dt>{{domxref("Navigator.maxTouchPoints")}} {{readonlyInline}}</dt> + <dd>Returns the maximum number of simultaneous touch contact points are supported by the current device.</dd> + <dt>{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.</dd> + <dt>{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating whether the browser is working online.</dd> + <dt>{{domxref("Navigator.oscpu")}}</dt> + <dd>Returns a string that represents the current operating system.</dd> + <dt>{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the <a href="/en-US/docs/Web/API/Permissions_API">Permissions API</a>.</dd> + <dt>{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.</dd> + <dt>{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.</dd> + <dt>{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}</dt> + <dd>Always returns <code>'Gecko'</code>, on any browser. This property is kept only for compatibility purpose.</dd> + <dt>{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">associated document</a>.</dd> + <dt>{{domxref("NavigatorStorage.storage")}} {{readonlyinline}}</dt> + <dd>Returns the singleton {{domxref('StorageManager')}} object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis.</dd> + <dt>{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}</dt> + <dd>Returns the user agent string for the current browser.</dd> + <dt>{{domxref("Navigator.webdriver")}} {{readonlyInline}} {{experimental_inline}}</dt> + <dd>Indicates whether the user agent is controlled by automation.</dd> +</dl> + +<h3 id="Methods" name="Methods">Non-standard</h3> + +<dl> + <dt>{{domxref("Navigator.buildID")}} {{non-standard_inline}}</dt> + <dd>Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. <code>20181001000000</code> in Firefox 64 onwards.</dd> + <dt>{{domxref("Navigator.credentials")}} {{non-standard_inline}}</dt> + <dd>Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. </dd> + <dt>{{domxref("Navigator.deviceMemory")}} {{readonlyInline}} {{non-standard_inline}}</dt> + <dd>Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024.</dd> + <dt>{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}</dt> + <dd>Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.</dd> + <dt>{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}</dt> + <dd>Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.</dd> + <dt>{{domxref("Navigator.mozNotification")}} {{obsolete_inline}} {{deprecated_inline("22")}} {{non-standard_inline}}<br> + {{domxref("Navigator.webkitNotification")}} {{obsolete_inline}}</dt> + <dd>Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.</dd> + <dt>{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}</dt> + <dd>The Object, returned by the <code>navigator.mozSocial</code> property, is available within the social media provider's panel to provide functionality it may need.</dd> + <dt>{{domxref("Navigator.presentation")}} {{non-standard_inline}}</dt> + <dd>Returns a reference to the {{domxref("Presentation")}} API.</dd> + <dt>{{domxref("Navigator.productSub")}} {{non-standard_inline}}</dt> + <dd>Returns the build number of the current browser (e.g., "20060909").</dd> + <dt>{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}</dt> + <dd>Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".</dd> + <dt>{{domxref("Navigator.standalone")}} {{non-standard_inline}}</dt> + <dd>Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.</dd> + <dt>{{domxref("Navigator.storageQuota")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns a {{domxref('StorageQuota')}} interface which provides means to query and request storage usage and quota information.</dd> + <dt>{{domxref("Navigator.vendor")}} {{non-standard_inline}}</dt> + <dd>Returns the vendor name of the current browser (e.g., "Netscape6").</dd> + <dt>{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}</dt> + <dd>Returns the vendor version number (e.g. "6.1").</dd> + <dt>{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}</dt> + <dd>Returns a PointerLock object for the <a href="/en-US/docs/API/Pointer_Lock_API" title="Mouse Lock API">Mouse Lock API</a>.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods</h2> + +<p><em>Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, <em>{{domxref("NavigatorUserMedia")}}, </em>and {{domxref("NavigatorStorageUtils")}}.</em></p> + +<h3 id="Standard_2">Standard</h3> + +<dl> + <dt>{{domxref("Navigator.canShare()")}} {{experimental_inline}}</dt> + <dd>Returns <code>true</code> if a call to <code>Navigator.share()</code> would succeed.</dd> + <dt>{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}</dt> + <dd>Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.</dd> + <dt>{{domxref("Navigator.getUserMedia", "Navigator.getUserMedia()")}} {{experimental_inline}}</dt> + <dd>After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.</dd> + <dt>{{domxref("Navigator.registerContentHandler()")}} {{Obsolete_inline(59)}}</dt> + <dd>Allows web sites to register themselves as a possible handler for a given MIME type.</dd> + <dt>{{domxref("Navigator.registerProtocolHandler()")}}</dt> + <dd>Allows web sites to register themselves as a possible handler for a given protocol.</dd> + <dt>{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}</dt> + <dd>Returns a <span style="line-height: 19.0909080505371px;">{{jsxref("Promise")}} for a MediaKeySystemAccess object.</span></dd> + <dt>{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}</dt> + <dd>Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.</dd> + <dt>{{domxref("Navigator.share()")}}{{experimental_inline}}</dt> + <dd>Invokes the native sharing mechanism of the current platform.</dd> + <dt>{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}</dt> + <dd>Returns <code>false</code>. JavaScript taint/untaint functions removed in JavaScript 1.2.</dd> + <dt>{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}</dt> + <dd>Causes vibration on devices with support for it. Does nothing if vibration support isn't available.</dd> +</dl> + +<h3 id="Non-standard">Non-standard</h3> + +<div class="note"> +<p>Firefox OS devices adds more non-standard methods. You can consult them on the <a href="/en-US/docs/Mozilla/Firefox_OS/API/Navigator">Firefox OS Navigator extensions article</a>.</p> +</div> + +<dl> + <dt>{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}</dt> + <dd>Lets code check to see if the document at a given URI is available without using the network.</dd> + <dt>{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}</dt> + <dd>Allows in-app payment.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#the-navigator-object', 'the Navigator object')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<div>{{Compat("api.Navigator")}}</div> diff --git a/files/vi/web/api/navigator/sendbeacon-vi/index.html b/files/vi/web/api/navigator/sendbeacon-vi/index.html new file mode 100644 index 0000000000..a91adf05fd --- /dev/null +++ b/files/vi/web/api/navigator/sendbeacon-vi/index.html @@ -0,0 +1,104 @@ +--- +title: Navigator.sendBeacon() +slug: Web/API/Navigator/sendBeacon-vi +tags: + - API + - Beacon + - Navigator + - sendBeacon + - web perfomance +translation_of: Web/API/Navigator/sendBeacon +--- +<div><span class="seoSummary">Phương thức <code><strong>navigator.sendBeacon()</strong></code> gửi </span>{{glossary("Asynchronous", "bất đồng bộ")}} 1 lượng nhỏ dữ liệu đến máy chủ (web server) thông qua giao thức {{Glossary("HTTP")}} .</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate">navigator.sendBeacon(<var>url</var>, <var>data</var>); +</pre> + +<h3 id="Tham_Số">Tham Số</h3> + +<dl> + <dt><code><var>url</var></code></dt> + <dd>Đường dẫn để nhận dữ liệu (Tạo request). Có thể là đường dẫn tuyệt đối hoặc tương đối.</dd> + <dt><code><var>data</var></code></dt> + <dd>Một đối tượng chứa dữ liệu để gửi đi có thể là 1 {{domxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("DOMString")}}, {{domxref("FormData")}}, hoặc {{domxref("URLSearchParams")}}.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Phương thức <code><strong>sendBeacon()</strong></code> trả về <code>true</code> nếu như {{glossary("user agent")}} (tác nhân người dùng hay web browser) xếp <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">dữ liệu (data)</span></font> để gửi đi thành công. Nếu không, sẽ trả về <code>false</code>.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức này dùng cho phân tích và chuẩn đoán cần gửi dữ liệu về máy chủ trước thời điểm đóng trang, nếu như gửi sớm hơn, có thể sẽ bị thiếu thông tin cần thu thập. Ví dụ, đường dẫn nào người dùng nhấn vào trước khi chuyển đến trang khác và đóng trang.</p> + +<p>Việc đảm bảo rằng dữ liệu được gửi đi trong khi đóng trang (unload) trước đây thường rất khó để thực hiện, bởi user agents (web browser) luôn bỏ qua những {{domxref("XMLHttpRequest")}} bất đồng bộ được chạy trong sự kiện {{domxref("Window/unload_event", "unload")}}.</p> + +<p>Trước đây, người ta thường làm trễ thời gian tải lại trang đủ lâu để gửi được dữ liệu đi bằng 1 số cách sau:</p> + +<ul> + <li>Gửi dữ liệu với 1 <code>XMLHttpRequest</code> đồng bộ, chặn các xử lý khác, được gọi trong sự kiện <code>unload</code> hoặc {{domxref("Window/beforeunload_event", "beforeunload")}}.</li> + <li>Tạo 1 thẻ {{HTMLElement("img")}} và đặt thuộc tính <code>src</code> trong khi xử lý <code>unload</code>. Hầu hết các user agents (trình duyệt) sẽ làm trễ việc tải lại trang cho đến khi tải xong ảnh.</li> + <li><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Tạo vòng lặp không xử lý gì chạy trong vài giây khi </span></font>unload</code>.</li> +</ul> + +<p>Tất cả những phương thức đó đều chặn quá trình tải lại trang, làm chậm việc chuyển đến trang tiếp theo. Trang tiếp theo không thể làm gì để ngăn chặn việc này, vì vậy trang mới sẽ có vẻ chậm đi, mặc dù đó là lỗi từ trang trước.</p> + +<p>Ví dụ sau đây là 1 đoạn code mẫu để gửi dữ liệu về server bằng 1 <code>XMLHttpRequest</code> đồng bộ trong khi xử lý <code>unload</code>. Điều này làm trễ việc tải trang tiếp theo.</p> + +<pre class="brush: js notranslate">window.addEventListener("unload", function logData() { + var xhr = new XMLHttpRequest(); + xhr.open("POST", "/log", false); // tham số thứ 3 là `false` để gửi request bất đồng bộ + xhr.send(analyticsData); +}); +</pre> + +<p>Đây là những gì <code><strong>sendBeacon()</strong></code> thay thế. Với phương thức <code>sendBeacon()</code>, dữ liệu sẽ được gửi đi bất đồng bộ, User Agent (trình duyệt) có thể làm thế mà không tạo trễ khi tải lại trang hoặc chuyển đến trang tiếp theo. <strong>Điều này giải quyết tất cả vấn đề với việc gửi các dữ liệu phân tích:</strong></p> + +<ul> + <li>Dữ liệu được gửi đi đáng tin cậy</li> + <li>Dữ liệu được gửi bất đồng bộ</li> + <li>Không ảnh hưởng đến việc tải trang tiếp theo</li> + <li>Hơn nữa, code đơn giản hơn so với tất cả các cách trước đây</li> +</ul> + +<p>Ví dụ sau đây là 1 đoạn code mẫu để gửi dữ liệu về server sử dụng phương thức <code style="">sendBeacon()</code>.</p> + +<pre class="brush: js notranslate">window.addEventListener("unload", function logData() { + navigator.sendBeacon("/log", analyticsData); +}); +</pre> + +<p>sendBeacon tạo 1 HTTP request với phương thức POST, kèm theo tất cả cookies liên quan khi được gọi.</p> + +<h2 id="Tài_liệu_chi_tiết">Tài liệu chi tiết</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Tài liệu</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Beacon', '#sendbeacon-method', 'sendBeacon()')}}</td> + <td>{{Spec2('Beacon')}}</td> + <td>Định nghĩa đầu tiên</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_với_trình_duyệt">Tương thích với trình duyệt</h2> + + + +<p>{{Compat("api.Navigator.sendBeacon")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{domxref("navigator", "navigator")}}</li> +</ul> diff --git a/files/vi/web/api/node/index.html b/files/vi/web/api/node/index.html new file mode 100644 index 0000000000..0d23b9445d --- /dev/null +++ b/files/vi/web/api/node/index.html @@ -0,0 +1,373 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - DOM Reference + - NeedsTranslation + - Reference + - TopicStub + - WebAPI +translation_of: Web/API/Node +--- +<div>{{APIRef("DOM")}}</div> + +<p>A <strong><code>Node</code></strong> is an interface from which a number of DOM types inherit, and allows these various types to be treated (or tested) similarly.</p> + +<p>The following interfaces all inherit from <code>Node</code> its methods and properties: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (which {{domxref("Text")}}, {{domxref("Comment")}}, and {{domxref("CDATASection")}} inherit), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}</p> + +<p>These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>Inherits properties from its parents {{domxref("EventTarget")}}</em>.<sup>[1]</sup></p> + +<dl> + <dt>{{domxref("Node.baseURI")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last <code>'/'</code>.</dd> + <dt>{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}</dt> + <dd>(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.</dd> + <dt>{{domxref("Node.childNodes")}} {{readonlyInline}}</dt> + <dd>Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the <code>Node</code> change, the {{domxref("NodeList")}} object is automatically updated.</dd> + <dt>{{domxref("Node.firstChild")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the first direct child node of the node, or <code>null</code> if the node has no child.</dd> + <dt>{{domxref("Node.lastChild")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the last direct child node of the node, or <code>null</code> if the node has no child.</dd> + <dt>{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}<br> + Though recent specifications require <code>localName</code> to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.</dd> + <dt>{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}</dt> + <dd>The namespace URI of this node, or <code>null</code> if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the <code><a class="linkification-ext external" href="http://www.w3.org/1999/xhtml" title="Linkification: http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a></code> namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}<br> + Though recent specifications require <code>namespaceURI</code> to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.</dd> + <dt>{{domxref("Node.nextSibling")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the next node in the tree, or <code>null</code> if there isn't such node.</dd> + <dt>{{domxref("Node.nodeName")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} containing the name of the <code>Node</code>. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like <code>'audio'</code> for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the <code>'#text'</code> string, or a {{domxref("Document")}} node will have the <code>'#document'</code> string.</dd> + <dt>{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}</dt> + <dd>A {{ Interface("nsIPrincipal") }} representing the node principal.</dd> + <dt>{{domxref("Node.nodeType")}}{{readonlyInline}}</dt> + <dd>Returns an <code>unsigned short</code> representing the type of the node. Possible values are: + <table class="standard-table"> + <tbody> + <tr> + <th scope="col">Name</th> + <th scope="col">Value</th> + </tr> + <tr> + <td><code>ELEMENT_NODE</code></td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>ATTRIBUTE_NODE</code> {{deprecated_inline()}}</td> + <td><code>2</code></td> + </tr> + <tr> + <td><code>TEXT_NODE</code></td> + <td><code>3</code></td> + </tr> + <tr> + <td><code>CDATA_SECTION_NODE</code> {{deprecated_inline()}}</td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>ENTITY_REFERENCE_NODE</code> {{deprecated_inline()}}</td> + <td><code>5</code></td> + </tr> + <tr> + <td><code>ENTITY_NODE</code> {{deprecated_inline()}}</td> + <td><code>6</code></td> + </tr> + <tr> + <td><code>PROCESSING_INSTRUCTION_NODE</code></td> + <td><code>7</code></td> + </tr> + <tr> + <td><code>COMMENT_NODE</code></td> + <td><code>8</code></td> + </tr> + <tr> + <td><code>DOCUMENT_NODE</code></td> + <td><code>9</code></td> + </tr> + <tr> + <td><code>DOCUMENT_TYPE_NODE</code></td> + <td><code>10</code></td> + </tr> + <tr> + <td><code>DOCUMENT_FRAGMENT_NODE</code></td> + <td><code>11</code></td> + </tr> + <tr> + <td><code>NOTATION_NODE</code> {{deprecated_inline()}}</td> + <td><code>12</code></td> + </tr> + </tbody> + </table> + </dd> + <dt>{{domxref("Node.nodeValue")}}</dt> + <dd>Is a {{domxref("DOMString")}} representing the value of an object. For most <code>Node</code> types, this returns <code>null</code> and any set operation is ignored. For nodes of type <code>TEXT_NODE</code> ({{domxref("Text")}} objects), <code>COMMENT_NODE</code> ({{domxref("Comment")}} objects), and <code>PROCESSING_INSTRUCTION_NODE</code> ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.</dd> + <dt>{{domxref("Node.ownerDocument")}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns <code>null</code>.</dd> + <dt>{{domxref("Node.parentNode")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns <code>null</code>.</dd> + <dt>{{domxref("Node.parentElement")}} {{readonlyInline}}</dt> + <dd>Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns <code>null</code>.</dd> + <dt>{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}</dt> + <dd>Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or <code>null</code> if no prefix is specified.<br> + Though recent specifications require <code>prefix</code> to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.</dd> + <dt>{{domxref("Node.previousSibling")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the previous node in the tree, or <code>null</code> if there isn't such node.</dd> + <dt>{{domxref("Node.textContent")}}</dt> + <dd>Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parents {{domxref("EventTarget")}}</em>.<sup>[1]</sup></p> + +<dl> + <dt>{{domxref("Node.appendChild()")}}</dt> + <dd>Insert a {{domxref("Node")}} as the last child node of this element.</dd> + <dt>{{domxref("Node.cloneNode()")}}</dt> + <dd>Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.</dd> + <dt>{{domxref("Node.compareDocumentPosition()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.contains()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.getFeature()")}} {{obsolete_inline}}</dt> + <dd>...</dd> + <dt>{{domxref("Node.getUserData()")}} {{obsolete_inline}}</dt> + <dd>Allows a user to get some {{domxref("DOMUserData")}} from the node.</dd> + <dt>{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.</dd> + <dt>{{domxref("Node.hasChildNodes()")}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.</dd> + <dt>{{domxref("Node.insertBefore()")}}</dt> + <dd>Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.</dd> + <dt>{{domxref("Node.isDefaultNamespace()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.isEqualNode()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.isSameNode()")}} {{obsolete_inline}}</dt> + <dd> </dd> + <dt>{{domxref("Node.isSupported()")}} {{obsolete_inline}}</dt> + <dd>Returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a> flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.</dd> + <dt>{{domxref("Node.lookupPrefix()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.lookupNamespaceURI()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.normalize()")}}</dt> + <dd>Clean up all the text nodes under this element (merge adjacent, remove empty).</dd> + <dt>{{domxref("Node.removeChild()")}}</dt> + <dd>Removes a child node from the current element, which must be a child of the current node.</dd> + <dt>{{domxref("Node.replaceChild()")}}</dt> + <dd>Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.</dd> + <dt>{{domxref("Node.setUserData()")}} {{obsolete_inline}}</dt> + <dd>Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.</dd> + <dd> </dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Browse_all_child_nodes">Browse all child nodes</h3> + +<p>The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).</p> + +<pre class="brush: js">function DOMComb (oParent, oCallback) { + if (oParent.hasChildNodes()) { + for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) { + DOMComb(oNode, oCallback); + } + } + oCallback.call(oParent); +}</pre> + +<h4 id="Syntax">Syntax</h4> + +<pre>DOMComb(parentNode, callbackFunction);</pre> + +<h4 id="Description">Description</h4> + +<p>Recursively cycle all child nodes of <code>parentNode</code> and <code>parentNode</code> itself and execute the <code>callbackFunction</code> upon them as <a href="/en-US/docs/JavaScript/Reference/Operators/this" title="en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a> objects.</p> + +<h4 id="Parameters">Parameters</h4> + +<dl> + <dt><code>parentNode</code></dt> + <dd>The parent node (<code><strong>Node</strong> <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object" title="en-US/docs/JavaScript/Reference/Global_Objects/Object">Object</a></code>).</dd> + <dt><code>callbackFunction</code></dt> + <dd>The callback function (<a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="en-US/docs/JavaScript/Reference/Global_Objects/Function"><code>Function</code></a>).</dd> +</dl> + +<h4 id="Sample_usage">Sample usage</h4> + +<p>The following example send to the <code>console.log</code> the text content of the body:</p> + +<pre class="brush: js">function printContent () { + if (this.nodeValue) { console.log(this.nodeValue); } +} + +onload = function () { + DOMComb(document.body, printContent); +};</pre> + +<h3 id="Remove_all_children_nested_within_a_node">Remove all children nested within a node</h3> + +<pre class="brush: js">Element.prototype.removeAll = function () { + while (this.firstChild) { this.removeChild(this.firstChild); } + return this; +};</pre> + +<h4 id="Sample_usage_2">Sample usage</h4> + +<pre class="brush: js">/* ... an alternative to document.body.innerHTML = "" ... */ +document.body.removeAll();</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Removed the following properties: <code>attributes</code>, <code>namespaceURI</code>, <code>prefix</code>, and <code>localName</code>.<br> + Removed the following methods: <code>isSupported()</code>, <code>hasAttributes()</code>, <code>isSameNode()</code>, <code>getFeature()</code>, <code>setUserData()</code>, and <code>getUserData()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>The methods <code>insertBefore()</code>, <code>replaceChild()</code>, <code>removeChild()</code>, and <code>appendChild()</code> returns one more kind of error (<code>NOT_SUPPORTED_ERR</code>) if called on a {{domxref("Document")}}.<br> + The <code>normalize()</code> method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.<br> + Added the following methods: <code>compareDocumentPosition()</code>, <code>isSameNode()</code>, <code>lookupPrefix()</code>, <code>isDefaultNamespace()</code>, <code>lookupNamespaceURI()</code>, <code>isEqualNode()</code>, <code>getFeature()</code>, <code>setUserData()</code>, and <code>getUserData().</code><br> + Added the following properties: <code>baseURI</code> and <code>textContent</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>The <code>ownerDocument</code> property was slightly modified so that {{domxref("DocumentFragment")}} also returns <code>null</code>.<br> + Added the following properties: <code>namespaceURI</code>, <code>prefix</code>, and <code>localName</code>.<br> + Added the following methods: <code>normalize()</code>, <code>isSupported()</code> and <code>hasAttributes()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<p> </p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getFeature()</code>{{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.<br> + Removed in {{CompatGeckoDesktop("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getUserData()</code>, <code>setUserData()</code> and <code>hasAttributes()</code> {{deprecated_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.<br> + Removed in {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>isSameNode()</code> {{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("9.0")}}.<br> + Removed in {{CompatGeckoDesktop("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>isSupported()</code> {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.<br> + Removed in {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>attributes</code></td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.<br> + Moved to {{domxref("Element")}} in {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getFeature()</code>{{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.<br> + Removed in {{CompatGeckoDesktop("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Webkit and Blink incorrectly do not make <code>Node</code> inherit from {{domxref("EventTarget")}}.</p> diff --git a/files/vi/web/api/node/insertbefore/index.html b/files/vi/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..f60a35f3e7 --- /dev/null +++ b/files/vi/web/api/node/insertbefore/index.html @@ -0,0 +1,166 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +<div>{{APIRef("DOM")}}</div> + +<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Phương thức </span></font><strong>Node.insertBefore()</strong></code> chèn một nút trước nút tài liệu tham khảo như một đối tượng con của một đối tượng gốc (đối tượng bố mẹ) cụ thể . Nếu đối tượng con đã cho là một tham chiếu tới tới một đối tượng node đang tồn tại trong tài liệu , <code>insertBefore()</code> chuyển nó từ vị trí hiện tại tới vị trí mới (không có yêu cầu nào phải xoá cái nút từ node gốc của nó trước khi thêm nó vào mấy nút khác).</p> + +<p>Vậy có nghĩa là một node thì không thể đồng thời ở tại hai điểm của tài liệu . Vậy, nếu node đã có nguồn gốc của nó rồi thì đối tượng node sẽ bị chuyển đi trước tiên rồi sau đó bị chèn vào ở vị trí mới . {{domxref("Node.cloneNode()")}} có thể được sử dụng để tạo một bản sao của đối tượng node trước khi thêm nó vào dưới phần tử gốc mới. Hãy lưu ý rằng những bản sao được tạo nên cùng <code>cloneNode()</code> sẽ không được tự động đồng bộ hoá.</p> + +<p>Nếu tài liệu ttham chiếu node là <code>null thì</code> node cụ thể được thêm vào đuôi của danh sách tập con của đối tượng node gốc.</p> + +<p>Nếu đối tượng con đã cho là một {{domxref("DocumentFragment")}} thì toàn bộ nội dung của <code>DocumentFragment</code> sẽ được chuyển đến danh sách tập con của đối tượng gốc cụ thể.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">var <em>insertedNode</em> = <em>parentNode</em>.insertBefore(<em>newNode</em>, <em>referenceNode</em>); +</pre> + +<ul> + <li><code>insertedNode</code> đối tượng node đã bị chèn vào bởi <code>newNode</code></li> + <li><code>parentNode</code> đối tượng phần tử gốc mới được chèn node vào.</li> + <li><code>newNode</code> đối tượng node bị chèn</li> + <li><code>referenceNode</code> đối tượng node lúc trước mà <code>newNode</code> bị chèn vào.</li> +</ul> + +<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Nếu </span></font>referenceNode</code> là <code>null</code> thì <code>newNode</code> isẽ được chèn vào đuôi của danh sách các đối tượng tập con nodes .</p> + +<div class="note"> +<p><code>referenceNode</code> <strong>không phải </strong> là một tham số có thể tuỳ chọn -- bạn phải đưa ra một <code>Node</code> hoặc <code>null</code>. Việc cung cấp nó thất bại hoặc đưa ra những giá trị không hợp lệ có thể sẽ <a href="https://code.google.com/p/chromium/issues/detail?id=419780">behave</a> <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=119489">differently</a>( hành xử khác nhau) trong mỗi phiên bản công cụ tìm kiếm khác nhau.</p> +</div> + +<h3 id="Return_value">Return value</h3> + +<p>Giá trị được trả về sẽ là một phần tử con trừ khi <code>newNode</code> là một {{domxref("DocumentFragment")}}, trong trường hợp {{domxref("DocumentFragment")}} rỗng được trả về.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Example_1">Example 1</h3> + +<pre class="brush: html"><div id="parentElement"> + <span id="childElement">foo bar</span> +</div> + +<script> +// Create the new node to insert +var newNode = document.createElement("span"); + +// Get a reference to the parent node +var parentDiv = document.getElementById("childElement").parentNode; + +// Begin test case [ 1 ] : Exist a childElement --> All working correctly +var sp2 = document.getElementById("childElement"); +parentDiv.insertBefore(newNode, sp2); +// End test case [ 1 ] + +// Begin test case [ 2 ] : childElement is of Type undefined +var sp2 = undefined; // Not exist a node of id "childElement" +parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node +// End test case [ 2 ] + +// Begin test case [ 3 ] : childElement is of Type "undefined" ( string ) +var sp2 = "undefined"; // Not exist a node of id "childElement" +parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument" +// End test case [ 3 ] +</script> +</pre> + +<h3 id="Example_2">Example 2</h3> + +<pre class="brush:html"><div id="parentElement"> + <span id="childElement">foo bar</span> +</div> + +<script> +// Create a new, plain <span> element +var sp1 = document.createElement("span"); + +// Get a reference to the element, before we want to insert the element +var sp2 = document.getElementById("childElement"); +// Get a reference to the parent element +var parentDiv = sp2.parentNode; + +// Insert the new element into the DOM before sp2 +parentDiv.insertBefore(sp1, sp2); +</script></pre> + +<p>Không hề có phương thức <span style="background-color: #ffffff; font-family: Arial,x-locale-body,sans-serif; font-size: 1rem; letter-spacing: -0.00278rem;"> </span><code style="font-size: 1rem; letter-spacing: -0.00278rem;">insertAfter()</code><span style="background-color: #ffffff; font-family: Arial,x-locale-body,sans-serif; font-size: 1rem; letter-spacing: -0.00278rem;"> nào cả. Nó có thể được mô phỏng bởi phương thức </span><code style="font-size: 1rem; letter-spacing: -0.00278rem;">insertBefore</code><span style="background-color: #ffffff; font-family: Arial,x-locale-body,sans-serif; font-size: 1rem; letter-spacing: -0.00278rem;"> cùng với {{domxref("Node.nextSibling")}}.</span></p> + +<p>Trong ví dụ trước, <code>sp1</code> đã chèn được vào sau <code>sp2</code> bằng cách dùng :</p> + +<pre class="brush: js"><code>parentDiv.insertBefore(sp1, sp2.nextSibling);</code></pre> + +<p>Nếu <code>sp2</code> không có đối tượng anh em nào tiếp nữa , thì nó hẳn phải là đối tượng con cuối cùng — <code>sp2.nextSibling</code> trả về <code>null</code>, và <code>sp1</code> sẽ được chèn vào cuối cùng của danh sách tập node con (ngay sau <code>sp2</code>).</p> + +<h3 id="Example_3">Example 3</h3> + +<p>Chèn một phần tử vào phần tử con đứng đầu bằng cách dùng đặc tính <a href="/en-US/docs/DOM/Node.firstChild" title="Node.firstChild">firstChild</a>.</p> + +<pre class="brush:js">// Get a reference to the element in which we want to insert a new node +var parentElement = document.getElementById('parentElement'); +// Get a reference to the first child +var theFirstChild = parentElement.firstChild; + +// Create a new element +var newElement = document.createElement("div"); + +// Insert the new element before the first child +parentElement.insertBefore(newElement, theFirstChild);</pre> + +<p class="brush:js">Khi phần tử không có con cả (đối tượng con đầu tiên) thì <code>firstChild</code> là <code>null</code>. Phần tử vẫn được thêm vào bố mẹ đối tượng gốc, sau con út (đối tượng con cuối cùng). Bởi bố mẹ không có con cả nên nó cũng không có con út luôn. Như vậy, phần tử mới sẽ là phần tử duy nhất sau việc chia cắt.</p> + +<h2 id="Khả_năng_tương_thích_của_công_cụ_tìm_kiếm">Khả năng tương thích của công cụ tìm kiếm</h2> + +<div class="hidden">Mục khả năng tương thích trên trang này được tạo bởi dữ liệu được kết cấu. Nếu bạn muốn đóng góp tới dữ liệu, xin hãy truy cập thử <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi một pull request cho chúng tôi.</div> + +<p>{{Compat("api.Node.insertBefore")}}</p> + +<h2 id="Chi_tiết">Chi tiết</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Fixes errors in the insertion algorithm</td> + </tr> + <tr> + <td>{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}</td> + <td>{{Spec2('DOM4')}}</td> + <td>Describes the algorithm in more detail</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>No notable changes</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>No notable changes</td> + </tr> + <tr> + <td>{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Introduced</td> + </tr> + </tbody> +</table> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{domxref("Node.removeChild()")}}</li> + <li>{{domxref("Node.replaceChild()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.hasChildNodes()")}}</li> + <li>{{domxref("Element.insertAdjacentElement()")}}</li> + <li>{{domxref("ParentNode.prepend()")}}</li> +</ul> diff --git a/files/vi/web/api/node/parentelement/index.html b/files/vi/web/api/node/parentelement/index.html new file mode 100644 index 0000000000..7e1e081325 --- /dev/null +++ b/files/vi/web/api/node/parentelement/index.html @@ -0,0 +1,50 @@ +--- +title: Node.parentElement +slug: Web/API/Node/parentElement +tags: + - API + - Cần tương thích trình duyệt + - Mô hình Đối tượng Văn bản + - Nút + - Thuộc tính +translation_of: Web/API/Node/parentElement +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>Thuộc tính chỉ-đọc <code><strong>Node.parentElement</strong></code> trả về cha của nút DOM {{domxref("Element")}}, hoặc<code>null</code> nếu nút không có cha hoặc cha của nó không là {{domxref("Element")}} DOM.</p> + +<h2 id="Syntax" name="Syntax">Cú pháp</h2> + +<pre class="syntaxbox"><em>parentElement</em> = <em>node</em>.parentElement</pre> + +<p><code>parentElement</code> là thành phần cha của nút hiện tại. Nó luôn luôn là một đối tượng {{domxref("Element")}} DOM, hoặc <code>null</code>.</p> + +<h2 id="Example" name="Example">Ví dụ</h2> + +<pre class="brush:js">if (node.parentElement) { + node.parentElement.style.color = "red"; +}</pre> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<p>Trên một vài trình duyệt, thuộc tính <code>parentElement</code> chỉ được xác định trên những nút mà chính nó là một {{domxref("Element")}}. Đặc biệt, nó không xác định trên các nút văn bản.</p> + +<div> + + +<p>{{Compat("api.Node.parentElement")}}</p> +</div> + +<h2 id="Specification" name="Specification">Thông số</h2> + +<ul> + <li>{{spec("http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#parent-element", "DOM Level 4: Node.parentElement", "WD")}}</li> +</ul> + +<h2 id="See_also" name="See_also">Xem thêm</h2> + +<ul> + <li>{{domxref("Node.parentNode")}}</li> +</ul> diff --git a/files/vi/web/api/node/parentnode/index.html b/files/vi/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..a93e4d8ac9 --- /dev/null +++ b/files/vi/web/api/node/parentnode/index.html @@ -0,0 +1,63 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +tags: + - API + - Gecko + - Mô hình Đối tượng Tài liệu + - Thuộc tính +translation_of: Web/API/Node/parentNode +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p> </p> + +<p>Thuộc tính chỉ-đọc <code><strong>Node.parentNode</strong></code> trả về cha của một nút xác định trong DOM.</p> + +<h2 id="Syntax" name="Syntax">Cú pháp</h2> + +<pre class="syntaxbox"><em>parentNode</em> = <em>node</em>.parentNode +</pre> + +<p><code>parentNode</code> là cha của nút hiện tại. Cha của một phần tử là một nút <code>Element</code>,một nút <code>Document</code>, hoặc một nút <code>DocumentFragment</code>.</p> + +<h2 id="Example" name="Example">Ví dụ</h2> + +<pre class="brush:js">if (node.parentNode) { + // loại bỏ một nút khỏi cây, trừ khi + // nó không nằm trong cây + node.parentNode.removeChild(node); +}</pre> + +<h2 id="Notes" name="Notes">Chú ý</h2> + +<p>Các <a href="/en-US/docs/DOM/Node.nodeType" title="DOM/Node.nodeType">nodes</a> <code>Document</code> và <code>DocumentFragment</code> có thể không có cha, vì vậy <code>parentNode</code> có thể luôn trả về giá trị <code>null</code>.</p> + +<p>Nó cũng trả về <code>null</code> nếu nút vừa được tạo và chưa được đính vào cây.</p> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + + + +<p>{{Compat("api.Node.parentNode")}}</p> + +<h2 id="Specification" name="Specification">Thông số</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1060184317">DOM Level 2 Core: Node.parentNode</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1060184317">DOM Level 3 Core: Node.parentNode</a></li> +</ul> + +<h2 id="See_also" name="See_also">Xem thêm</h2> + +<ul> + <li>{{Domxref("Node.firstChild")}}</li> + <li>{{Domxref("Node.lastChild")}}</li> + <li>{{Domxref("Node.childNodes")}}</li> + <li>{{Domxref("Node.nextSibling")}}</li> + <li>{{Domxref("Node.parentElement")}}</li> + <li>{{Domxref("Node.previousSibling")}}</li> + <li>{{Domxref("Node.removeChild")}}</li> +</ul> diff --git a/files/vi/web/api/notification/index.html b/files/vi/web/api/notification/index.html new file mode 100644 index 0000000000..829159b490 --- /dev/null +++ b/files/vi/web/api/notification/index.html @@ -0,0 +1,408 @@ +--- +title: Notification +slug: Web/API/notification +translation_of: Web/API/Notification +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>The <code>Notification</code> interface of the <a href="/en-US/docs/Web/API/Notifications_API">Notifications API</a> is used to configure and display desktop notifications to the user.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Hàm_khởi_tạo">Hàm khởi tạo</h2> + +<dl> + <dt>{{domxref("Notification.Notification", "Notification()")}}</dt> + <dd>Creates a new instance of the {{domxref('Notification')}} object.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<h3 id="Static_properties">Static properties</h3> + +<p>These properties are available only on the <code>Notification</code> object itself.</p> + +<dl> + <dt>{{domxref("Notification.permission")}} {{readonlyinline}}</dt> + <dd>A string representing the current permission to display notifications. Possible value are: <code>denied</code> (the user refuses to have notifications displayed), <code>granted</code> (the user accepts having notifications displayed), or <code>default</code> (the user choice is unknown and therefore the browser will act as if the value were denied).</dd> +</dl> + +<h3 id="Instance_properties">Instance properties</h3> + +<p>These properties are available only on instances of the <code>Notification</code> object.</p> + +<dl> + <dt>{{domxref("Notification.title")}} {{readonlyinline}}</dt> + <dd>The title of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.dir")}} {{readonlyinline}}</dt> + <dd>The text direction of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.lang")}} {{readonlyinline}}</dt> + <dd>The language code of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.body")}} {{readonlyinline}}</dt> + <dd>The body string of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.tag")}} {{readonlyinline}}</dt> + <dd>The ID of the notification (if any) as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.icon")}} {{readonlyinline}}</dt> + <dd>The URL of the image used as an icon of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.data")}} {{readonlyinline}}</dt> + <dd>Returns a structured clone of the notification’s data.</dd> + <dt>{{domxref("Notification.requireInteraction")}} {{readonlyinline}}</dt> + <dd>A {{jsxref("Boolean")}} indicating that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it.</dd> + <dt>{{domxref("Notification.silent")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification should be silent, i.e. no sounds or vibrations should be issued, regardless of the device settings.</dd> + <dt>{{domxref("Notification.timestamp")}} {{readonlyinline}}</dt> + <dd>Specifies the time at which a notification is created or applicable (past, present, or future).</dd> +</dl> + +<h4 id="Unsupported_properties">Unsupported properties</h4> + +<p>The following properties are listed in the most up-to-date spec, but are not supported in any browsers yet. It is advisable to keep checking back regularly to see if the status of these has updated, and let us know if you find any out of date information.</p> + +<dl> + <dt>{{domxref("Notification.noscreen")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification firing should enable the device's screen or not.</dd> + <dt>{{domxref("Notification.renotify")}} {{readonlyinline}}</dt> + <dd>Specifies whether the user should be notified after a new notification replaces an old one.</dd> + <dt>{{domxref("Notification.sound")}} {{readonlyinline}}</dt> + <dd>Specifies a sound resource to play when the notification fires, in place of the default system notification sound.</dd> + <dt>{{domxref("Notification.sticky")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification should be 'sticky', i.e. not easily clearable by the user.</dd> + <dt>{{domxref("Notification.vibrate")}} {{readonlyinline}}</dt> + <dd>Specifies a vibration pattern for devices with vibration hardware to emit.</dd> +</dl> + +<h4 id="Event_handlers">Event handlers</h4> + +<dl> + <dt>{{domxref("Notification.onclick")}}</dt> + <dd>A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.</dd> + <dt>{{domxref("Notification.onerror")}}</dt> + <dd>A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.</dd> +</dl> + +<h4 id="Obsolete_handlers">Obsolete handlers</h4> + +<p>The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. I is safe therefore to assume they are obsolete, and may stop working in future browser versions.</p> + +<dl> + <dt>{{domxref("Notification.onclose")}}</dt> + <dd>A handler for the {{event("close")}} event. It is triggered when the user closes the notification.</dd> + <dt>{{domxref("Notification.onshow")}}</dt> + <dd>A handler for the {{event("show")}} event. It is triggered when the notification is displayed.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<h3 id="Static_methods">Static methods</h3> + +<p>These methods are available only on the <code>Notification</code> object itself.</p> + +<dl> + <dt>{{domxref("Notification.requestPermission()")}}</dt> + <dd>Requests permission from the user to display notifications.</dd> +</dl> + +<h3 id="Instance_methods">Instance methods</h3> + +<p>These properties are available only on an instance of the <code>Notification</code> object or through its <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain"><code>prototype</code></a>. The <code>Notification</code> object also inherits from the {{domxref("EventTarget")}} interface.</p> + +<dl> + <dt>{{domxref("Notification.close()")}}</dt> + <dd>Programmatically closes a notification.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>Assume this basic HTML:</p> + +<pre class="brush: html"><button onclick="notifyMe()">Notify me!</button></pre> + +<p>It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.</p> + +<pre class="brush: js">function notifyMe() { + // Let's check if the browser supports notifications + if (!("Notification" in window)) { + alert("This browser does not support desktop notification"); + } + + // Let's check whether notification permissions have already been granted + else if (Notification.permission === "granted") { + // If it's okay let's create a notification + var notification = new Notification("Hi there!"); + } + + // Otherwise, we need to ask the user for permission + else if (Notification.permission !== 'denied') { + Notification.requestPermission(function (permission) { + // If the user accepts, let's create a notification + if (permission === "granted") { + var notification = new Notification("Hi there!"); + } + }); + } + + // At last, if the user has denied notifications, and you + // want to be respectful there is no need to bother them any more. +}</pre> + +<p>{{EmbedLiveSample('Example', '100%', 30)}}</p> + +<p>In many cases, you don't need to be this verbose. For example, in our <a href="http://mdn.github.io/emogotchi/">Emogotchi demo</a> (<a href="https://github.com/mdn/emogotchi">see source code</a>), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications (this uses the newer promise-based method syntax):</p> + +<pre class="brush: js">Notification.requestPermission().then(function(result) { + console.log(result); +});</pre> + +<p>Then we run a simple <code>spawnNotification()</code> function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary <code>options</code> object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.</p> + +<pre class="brush: js">function spawnNotification(theBody,theIcon,theTitle) { + var options = { + body: theBody, + icon: theIcon + } + var n = new Notification(theTitle,options); +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>5{{property_prefix("webkit")}}<sup>[1]</sup><br> + 22</td> + <td>4.0 {{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>6<sup>[3]</sup></td> + </tr> + <tr> + <td><code>icon</code></td> + <td>5{{property_prefix("webkit")}}<sup>[1]</sup><br> + 22</td> + <td>4.0 {{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>silent</code></td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>noscreen</code>, <code>sticky</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sound</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>renotify</code></td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Promise-based <code>Notification.requestPermission()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("47.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>4.0{{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>1.0.1{{property_prefix("moz")}}<sup>[2]</sup><br> + 1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + <tr> + <td><code>icon</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0{{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>1.0.1{{property_prefix("moz")}}<sup>[2]</sup><br> + 1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>silent</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + <tr> + <td><code>noscreen</code>, <code>sticky</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sound</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>renotify</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Promise-based <code>Notification.requestPermission()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("47.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Before Chrome 22, the support for notification followed an <a href="http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification">old prefixed version of the specification</a> and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification.</p> + +<p>Before Chrome 32, {{domxref("Notification.permission")}} was not supported.</p> + +<p>Before Chrome 42, service worker additions were not supported.</p> + +<p>Starting in Chrome 49, notifications do not work in incognito mode.</p> + +<p>[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification must be done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its <code>createNotification</code> method.</p> + +<p>Prior to Firefox 22 (Firefox OS <1.2), the Notification was displayed when calling the <code>show</code> method and supported only the <code>click</code> and <code>close</code> events.</p> + +<p>Nick Desaulniers wrote a <a href="https://github.com/nickdesaulniers/fxos-irc/blob/master/js/notification.js">Notification shim</a> to cover both newer and older implementations.</p> + +<p>One particular Firefox OS issue is that you can <a href="https://github.com/nickdesaulniers/fxos-irc/blob/0160cf6c3a2b5c9fe33822aaf6bcba3b7e846da9/my.js#L171">pass a path to an icon</a> to use in the notification, but if the app is packaged you cannot use a relative path like <code>/my_icon.png</code>. You also can't use <code>window.location.origin + "/my_icon.png"</code> because <code>window.location.origin</code> is null in packaged apps. The <a href="https://developer.mozilla.org/en-US/Apps/Developing/Manifest#origin">manifest origin field</a> fixes this, but it is only available in Firefox OS 1.1+. A potential solution for supporting Firefox OS <1.1 is to <a href="https://github.com/nickdesaulniers/fxos-irc/blob/0160cf6c3a2b5c9fe33822aaf6bcba3b7e846da9/my.js#L168">pass an absolute URL to an externally hosted version of the icon</a>. This is less than ideal as the notification is displayed immediately without the icon, then the icon is fetched, but it works on all versions of Firefox OS.</p> + +<p>When using notifications in a Firefox OS app, be sure to add the <code>desktop-notification</code> permission in your manifest file. Notifications can be used at any permission level, hosted or above: <code>"permissions": { "desktop-notification": {} }</code></p> + +<p>[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a></li> +</ul> diff --git a/files/vi/web/api/touch_events/index.html b/files/vi/web/api/touch_events/index.html new file mode 100644 index 0000000000..f723a4f971 --- /dev/null +++ b/files/vi/web/api/touch_events/index.html @@ -0,0 +1,340 @@ +--- +title: Touch events +slug: Web/API/Touch_events +tags: + - Advanced + - DOM + - Event + - Guide + - Mobile + - NeedsTranslation + - Overview + - TopicStub + - touch +translation_of: Web/API/Touch_events +--- +<div>{{DefaultAPISidebar("Touch Events")}}</div> + +<p><span class="seoSummary">In order to provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.</span></p> + +<p>The touch events interfaces are relatively low-level APIs that can be used to support application specific multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move and end phases.</p> + +<p>Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface. The {{domxref("TouchEvent")}} interface encapsulates all of the touch points that are currently active. The {{domxref("Touch")}} interface, which represents a single touch point, includes information such as the position of the touch point relative to the browser viewport.</p> + +<h2 id="Definitions">Definitions</h2> + +<dl> + <dt>Surface</dt> + <dd>The touch-sensitive surface. This may be a screen or trackpad.</dd> +</dl> + +<dl> + <dt>Touch point</dt> + <dd>A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("TouchEvent")}}</dt> + <dd>Represents an event that occurs when the state of touches on the surface changes.</dd> + <dt>{{domxref("Touch")}}</dt> + <dd>Represents a single point of contact between the user and the touch surface.</dd> + <dt>{{domxref("TouchList")}}</dt> + <dd>Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>This example tracks multiple touch points at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.</p> + +<div class="note"><strong>Note:</strong> The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.</div> + +<h3 id="Create_a_canvas">Create a canvas</h3> + +<pre class="brush: html"><canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> + Your browser does not support canvas element. +</canvas> +<br> +<button onclick="startup()">Initialize</button> +<br> +Log: <pre id="log" style="border: 1px solid #ccc;"></pre> +</pre> + +<h3 id="Setting_up_the_event_handlers">Setting up the event handlers</h3> + +<p>When the page loads, the <code>startup()</code> function shown below should be called by our {{HTMLElement("body")}} element's <code>onload</code> attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).</p> + +<pre class="brush: js">function startup() { + var el = document.getElementsByTagName("canvas")[0]; + el.addEventListener("touchstart", handleStart, false); + el.addEventListener("touchend", handleEnd, false); + el.addEventListener("touchcancel", handleCancel, false); + el.addEventListener("touchmove", handleMove, false); + console.log("initialized."); +} +</pre> + +<p>This simply sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.</p> + +<h4 id="Tracking_new_touches">Tracking new touches</h4> + +<p>We'll keep track of the touches in-progress.</p> + +<pre class="brush: js">var ongoingTouches = []; +</pre> + +<p>When a {{event("touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the <code>handleStart()</code> function below is called.</p> + +<pre class="brush: js">function handleStart(evt) { + evt.preventDefault(); + console.log("touchstart."); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + console.log("touchstart:" + i + "..."); + ongoingTouches.push(copyTouch(touches[i])); + var color = colorForTouch(touches[i]); + ctx.beginPath(); + ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false); // a circle at the start + ctx.fillStyle = color; + ctx.fill(); + console.log("touchstart:" + i + "."); + } +} +</pre> + +<p>This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.</p> + +<p>After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.</p> + +<h4 id="Drawing_as_the_touches_move">Drawing as the touches move</h4> + +<p>Each time one or more fingers moves, a {{event("touchmove")}} event is delivered, resulting in our <code>handleMove()</code> function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.</p> + +<pre class="brush: js">function handleMove(evt) { + evt.preventDefault(); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + var color = colorForTouch(touches[i]); + var idx = ongoingTouchIndexById(touches[i].identifier); + + if (idx >= 0) { + console.log("continuing touch "+idx); + ctx.beginPath(); + console.log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");"); + ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); + console.log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");"); + ctx.lineTo(touches[i].pageX, touches[i].pageY); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + + ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record + console.log("."); + } else { + console.log("can't figure out which touch to continue"); + } + } +} +</pre> + +<p>This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.</p> + +<p>This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.</p> + +<p>After drawing the line, we call <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"><code>Array.splice()</code></a> to replace the previous information about the touch point with the current information in the <code>ongoingTouches</code> array.</p> + +<h4 id="Handling_the_end_of_a_touch">Handling the end of a touch</h4> + +<p>When the user lifts a finger off the surface, a {{event("touchend")}} event is sent. We handle this by calling the <code>handleEnd()</code> function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.</p> + +<pre class="brush: js">function handleEnd(evt) { + evt.preventDefault(); + log("touchend"); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + var color = colorForTouch(touches[i]); + var idx = ongoingTouchIndexById(touches[i].identifier); + + if (idx >= 0) { + ctx.lineWidth = 4; + ctx.fillStyle = color; + ctx.beginPath(); + ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); + ctx.lineTo(touches[i].pageX, touches[i].pageY); + ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8); // and a square at the end + ongoingTouches.splice(idx, 1); // remove it; we're done + } else { + console.log("can't figure out which touch to end"); + } + } +} +</pre> + +<p>This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"><code>Array.splice()</code></a>, we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.</p> + +<h4 id="Handling_canceled_touches">Handling canceled touches</h4> + +<p>If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{event("touchcancel")}} event is sent, and we call the <code>handleCancel()</code> function below.</p> + +<pre class="brush: js">function handleCancel(evt) { + evt.preventDefault(); + console.log("touchcancel."); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + var idx = ongoingTouchIndexById(touches[i].identifier); + ongoingTouches.splice(idx, 1); // remove it; we're done + } +} +</pre> + +<p>Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.</p> + +<h3 id="Convenience_functions">Convenience functions</h3> + +<p>This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.</p> + +<h4 id="Selecting_a_color_for_each_touch">Selecting a color for each touch</h4> + +<p>In order to make each touch's drawing look different, the <code>colorForTouch()</code> function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.</p> + +<pre class="brush: js">function colorForTouch(touch) { + var r = touch.identifier % 16; + var g = Math.floor(touch.identifier / 3) % 16; + var b = Math.floor(touch.identifier / 7) % 16; + r = r.toString(16); // make it a hex digit + g = g.toString(16); // make it a hex digit + b = b.toString(16); // make it a hex digit + var color = "#" + r + g + b; + console.log("color for touch with identifier " + touch.identifier + " = " + color); + return color; +} +</pre> + +<p>The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#aaa".</p> + +<h4 id="Copying_a_touch_object">Copying a touch object</h4> + +<p>Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.</p> + +<pre class="brush: js">function copyTouch(touch) { + return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY }; +}</pre> + +<h4 id="Finding_an_ongoing_touch">Finding an ongoing touch</h4> + +<p>The <code>ongoingTouchIndexById()</code> function below scans through the <code>ongoingTouches</code> array to find the touch matching the given identifier, then returns that touch's index into the array.</p> + +<pre class="brush: js">function ongoingTouchIndexById(idToFind) { + for (var i = 0; i < ongoingTouches.length; i++) { + var id = ongoingTouches[i].identifier; + + if (id == idToFind) { + return i; + } + } + return -1; // not found +} +</pre> + +<h4 id="Showing_what's_going_on">Showing what's going on</h4> + +<pre class="brush: js">function log(msg) { + var p = document.getElementById('log'); + p.innerHTML = msg + "\n" + p.innerHTML; +}</pre> + +<p>If your browser supports it, you can {{LiveSampleLink('Example', 'see it live')}}.</p> + +<p><a href="http://jsfiddle.net/Darbicus/z3Xdx/10/">jsFiddle example</a></p> + +<h2 id="Additional_tips">Additional tips</h2> + +<p>This section provides additional tips on how to handle touch events in your web application.</p> + +<h3 id="Handling_clicks">Handling clicks</h3> + +<p>Since calling <code>preventDefault()</code> on a {{event("touchstart")}} or the first {{event("touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call <code>preventDefault()</code> on {{event("touchmove")}} rather than {{event("touchstart")}}. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)</p> + +<pre class="brush: js">function onTouch(evt) { + evt.preventDefault(); + if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0)) + return; + + var newEvt = document.createEvent("MouseEvents"); + var type = null; + var touch = null; + + switch (evt.type) { + case "touchstart": + type = "mousedown"; + touch = evt.changedTouches[0]; + break; + case "touchmove": + type = "mousemove"; + touch = evt.changedTouches[0]; + break; + case "touchend": + type = "mouseup"; + touch = evt.changedTouches[0]; + break; + } + + newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0, + touch.screenX, touch.screenY, touch.clientX, touch.clientY, + evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null); + evt.originalTarget.dispatchEvent(newEvt); +} +</pre> + +<h3 id="Calling_preventDefault()_only_on_a_second_touch">Calling preventDefault() only on a second touch</h3> + +<p>One technique for preventing things like <code>pinchZoom</code> on a page is to call <code>preventDefault()</code> on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}</td> + <td>{{Spec2('Touch Events 2')}}</td> + <td>Added <code>radiusX</code>, <code>radiusY</code>, <code>rotationAngle</code>, <code>force</code> properties</td> + </tr> + <tr> + <td>{{SpecName('Touch Events', '#touch-interface', 'Touch')}}</td> + <td>{{Spec2('Touch Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<h3 id="Touch"><code>Touch</code></h3> + + + +<p>{{Compat("api.Touch")}}</p> + +<h3 id="Firefox_touch_events_and_multiprocess_(e10s)">Firefox, touch events, and multiprocess (e10s)</h3> + +<p>In Firefox, touch events are disabled when e10s (electrolysis; <a href="/en-US/docs/Mozilla/Firefox/Multiprocess_Firefox">multiprocess Firefox</a>) is disabled. e10s is on by default in Firefox, but can end up becoming disabled in certain situations, for example when certain accessibility tools or Firefox add-ons are installed that require e10s to be disabled to work. This means that even on a touchscreen-enabled desktop/laptop, touch events won't be enabled.</p> + +<p>You can test whether e10s is disabled by going to <code>about:support</code> and looking at the "Multiprocess Windows" entry in the "Application Basics" section. 1/1 means it is enabled, 0/1 means disabled.</p> + +<p>If you want to force e10s to be on — to explicitly re-enable touch events support — you need to go to <code>about:config</code> and create a new Boolean preference <code>browser.tabs.remote.force-enable</code>. Set it to <code>true</code>, restart the browser, and e10s will be enabled regardless of any other settings.</p> diff --git a/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html b/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html new file mode 100644 index 0000000000..33ca3f4490 --- /dev/null +++ b/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html @@ -0,0 +1,61 @@ +--- +title: Supporting both TouchEvent and MouseEvent +slug: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent +translation_of: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent +--- +<p>{{DefaultAPISidebar("Touch Events")}}</p> + +<p>{{domxref("Touch_events","touch")}} interface cho phép cung cấp các tương tác với ứng dụng trên thiết bị. Tuy nhiên, sự thật là đa số các web hiện tại được thiết kế để làm việc với trỏ chuột. Thậm chí, khi trình duyệt hổ trợ touch, trình duyệt vẫn phải <em>giả lập</em> sự kiện của chuột.</p> + +<h2 id="Event_firing">Event firing</h2> + +<p>Touch event đưa ra vài yêu cầu cho trình duyệt (xem <a href="https://w3c.github.io/touch-events/#mouse-events"><em>Interaction with Mouse Events and click</em></a> để xem chi tiết), lưu ý răng <em>trình duyệt có thể fire cả 2 sự kiện touch và mouse để đáp lại cùng một tương tác của user</em>. </p> + +<p>Nếu trình duyệt fire cả 2 sự kiện touch và mouse cho cùng tương tác, trình duyệt <em>phải </em> fire {{event("touchstart")}} trước khi fire sự kiện mouse. Vì vậy, nếu ứng dụng không muốn sử dụng sự kiện mouse trên một element {{domxref("Touch.target","target")}}, chúng ta phải gọi {{domxref("Event.preventDefault()","preventDefault()")}}.</p> + +<p>Đây là một snippet code dùng {{event("touchmove")}} event handler và gọi <code>preventDefault()</code>.</p> + +<pre class="brush: js">// touchmove handler +function process_touchmove(ev) { + // Call preventDefault() to prevent any further handling + ev.preventDefault(); +} +</pre> + +<h2 id="Thứ_tự_Event">Thứ tự Event</h2> + +<p>Thứ tự của các sự kiện touch và mouse được định nghĩa như sau:</p> + +<ul> + <li><code>touchstart</code></li> + <li>Zero hoặc các sự kiện <code>touchmove</code> tiếp tục, tùy thuộc user có tiếp tục kéo ngón tay không</li> + <li><code>touchend</code></li> + <li><code>mousemove</code></li> + <li><code>mousedown</code></li> + <li><code>mouseup</code></li> + <li><code>click</code></li> +</ul> + +<p>Nếu {{event("touchstart")}}, {{event("touchmove")}} hoặc {{event("touchend")}} được hủy, sẽ không có sự mouse hoặc click nào được fire, thứ tự sẽ là:</p> + +<ul> + <li><code>touchstart</code></li> + <li>Zero hoặc các sự kiện <code>touchmove</code> tiếp tục, tùy thuộc user có tiếp tục kéo ngón tay không</li> + <li><code>touchend</code></li> +</ul> + +<h2 id="Community">Community</h2> + +<ul> + <li><a href="https://github.com/w3c/touch-events">Touch Events Community Group</a></li> + <li><a href="https://lists.w3.org/Archives/Public/public-touchevents/">Mail list</a></li> + <li><a href="irc://irc.w3.org:6667/">W3C #touchevents IRC channel</a></li> +</ul> + +<h2 id="Related_topics_and_resources">Related topics and resources</h2> + +<ul> + <li><a href="/Web/API/Touch_events">Touch Events Overview</a></li> + <li><a href="/Web/API/Touch_events/Using_Touch_Events">Using Touch Events</a></li> + <li><a href="http://www.html5rocks.com/en/mobile/touchandmouse/">Touch and Mouse (Together Again for the First Time)</a></li> +</ul> diff --git a/files/vi/web/api/url_api/index.html b/files/vi/web/api/url_api/index.html new file mode 100644 index 0000000000..71626f5c4a --- /dev/null +++ b/files/vi/web/api/url_api/index.html @@ -0,0 +1,122 @@ +--- +title: URL API +slug: Web/API/URL_API +translation_of: Web/API/URL_API +--- +<p>{{DefaultAPISidebar("URL API")}}</p> + +<p><span class="seoSummary">The URL API is a component of the URL standard, which defines what constitutes a valid {{Glossary("URL", "Uniform Resource Locator")}} and the API that accesses and manipulates URLs.</span> The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy <code>application/x-www-form-urlencoded</code> {{Glossary("MIME type")}} used to submit web forms' contents as a set of key/value pairs.</p> + +<h2 id="Mô_hình_URL_và_cách_sử_dụng">Mô hình URL và cách sử dụng</h2> + +<p><span class="tlid-translation translation" lang="vi"><span title="">Phần lớn tiêu chuẩn URL được lấy theo <a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL">định nghĩa của URL</a> cùng cấu trúc và phân tích cú pháp.</span> <span title="">Nó cũng bao gồm các định nghĩa về các thuật ngữ khác nhau liên quan đến việc đánh địa chỉ các máy tính trên mạng, các thuật toán để phân tích địa chỉ IP và địa chỉ DOM được chỉ định.</span></span></p> + +<h3 id="Truy_cập_component_URL">Truy cập component URL</h3> + +<p>Tạo object {{domxref("URL")}} <span class="tlid-translation translation" lang="vi"><span title="">đối với một URL đã cho sẽ phân tích cú pháp URL và cung cấp quyền truy cập nhanh vào các thành phần của nó.</span></span></p> + +<pre class="brush: js notranslate">let addr = new URL("https://wiki.developer.mozilla.org/vi/docs/Web/API/URL_API"); +let host = addr.host; +let path = addr.pathname; +</pre> + +<p>Mã trên tạo ra 1 object <code>URL</code> cho bài viết bạn đang đọc, rồi lấy thuộc tính {{domxref("URL.host", "host")}} và {{domxref("URL.pathname", "pathname")}}. Trong tình huống trên, các giá trị tương ứng lần lượt là <code>wiki.developer.mozilla.org</code> và <code>/vi/docs/Web/API/URL_API</code>.</p> + +<h3 id="Thay_đổi_URL">Thay đổi URL</h3> + +<p><span class="tlid-translation translation" lang="vi"><span title="">Hầu hết các thuộc tính của URL là cố định;</span> <span title="">bạn có thể viết các giá trị mới cho chúng để thay đổi URL.</span> <span title="">Ví dụ: để tạo URL mới và đặt tên người dùng:</span></span></p> + +<pre class="brush: js notranslate">let myUsername = "someguy"; +let addr = new URL("https://mysite.com/login"); +addr.username = myUsername; +</pre> + +<p>Đặt giá trị của {{domxref("URL.username", "username")}} không chỉ thay đổi giá trị của thuộc tính, mà còn thay đổi cả đường dẫn URL. Sau khi thực thi đoạn code, giá trị trả về của {{domxref("URL.href", "addr.href")}} là <code>https://someguy@mysite.com/login</code>. Điều này đúng với mọi thuộc tính có thể ghi.</p> + +<h3 id="Truy_vấn">Truy vấn</h3> + +<p>Thuộc tính {{domxref("URL.search", "search")}} trong <code>URL</code> chứa các giá trị truy vấn của URL. Lấy ví dụ, nếu đường dẫn URL là <code>https://mysite.com/login?user=someguy&page=news</code>, thì giá trị của thuộc tính <code>search</code> là <code>?user=someguy&page=news</code>. Bạn có thể kiểm tra các giá trị của mỗi tham số với {{domxref("URLSearchParams")}} là object của phương thức {{domxref("URLSearchParams.get", "get()")}}:</p> + +<pre class="brush: js notranslate">let addr = new URL("https://mysite.com/login?user=someguy&page=news"); +try { + loginUser(addr.searchParams.get("user")); + gotoPage(addr.searchParams.get("page")); +} catch(err) { + showErrorMessage(err); +} +</pre> + +<p>Với ví dụ trên, username và trang đích được lấy từ query và chuyển vào trong function được dùng để điều hướng người dùng đăng nhập và chuyển tới trang đích mong muốn.</p> + +<p>Other functions within <code>URLSearchParams</code> let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.</p> + +<h2 id="URL_API_interfaces">URL API interfaces</h2> + +<p>The URL API is a simple one, with only a couple of interfaces to its name:</p> + +<div class="index"> +<ul> + <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/URL"><code>URL</code></a></span></span></li> + <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/URLSearchParams"><code>URLSearchParams</code></a></span></span></li> +</ul> +</div> + +<p>Older versions of the specification included an interface called {{domxref("URLUtilsReadOnly")}}, which has since been merged into the {{domxref("WorkerLocation")}} interface.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<p>If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a <code>URL</code> object to do it for you. The <code>fillTableWithParameters()</code> function below takes as input a {{domxref("HTMLTableElement")}} object representing a {{HTMLElement("table")}}. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.</p> + +<p>Note the call to {{domxref("URLSearchParams.sort()")}} to sort the parameter list before generating the table.</p> + +<pre class="brush: js notranslate">function fillTableWithParameters(tbl) { + let url = new URL(document.location.href); + url.searchParams.sort(); + let keys = url.searchParams.keys(); + + for (let key of keys) { + let val = url.searchParams.get(key); + let row = document.createElement("tr"); + let cell = document.createElement("td"); + cell.innerText = key; + row.appendChild(cell); + cell = document.createElement("td"); + cell.innerText = val; + row.appendChild(cell); + tbl.appendChild(row); + }; +}</pre> + +<p>A working version of this example can be <a href="https://url-api.glitch.me">found on Glitch</a>. Just add parameters to the URL when loading the page to see them in the table. For instance, try <code><a href="https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable">https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable</a></code>.</p> + +<h2 id="Quy_chuẩn">Quy chuẩn</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('URL')}}</td> + <td>{{Spec2('URL')}}</td> + <td>WHATWG specification</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("api.URL")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li> + <li>CSS {{cssxref("<url>")}} type</li> +</ul> diff --git a/files/vi/web/api/webrtc_api/index.html b/files/vi/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..508df4945f --- /dev/null +++ b/files/vi/web/api/webrtc_api/index.html @@ -0,0 +1,233 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +tags: + - API + - Audio + - Conferencing + - Landing + - Media + - NeedsTranslation + - Networking + - TopicStub + - Video + - WebRTC + - WebRTC API + - streaming +translation_of: Web/API/WebRTC_API +--- +<div>{{WebRTCSidebar}}</div> + +<p><span class="seoSummary"><strong>WebRTC</strong> (Web Real-Time Communication) is a technology which enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary.</span> The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user installs plug-ins or any other third-party software.</p> + +<p>WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more.</p> + +<h2 id="Interoperability">Interoperability</h2> + +<p>Because implementations of WebRTC are still evolving, and because each browser has <a href="/en-US/docs/Web/Media/Formats/WebRTC_codecs">different levels of support for codecs</a> and WebRTC features, you should <em>strongly</em> consider making use of <a href="https://github.com/webrtcHacks/adapter">the Adapter.js library</a> provided by Google before you begin to write your code.</p> + +<p>Adapter.js uses shims and polyfills to smooth over the differences among the WebRTC implementations across the environments supporting it. Adapter.js also handles prefixes and other naming differences to make the entire WebRTC development process easier, with more broadly compatible results. The library is also <a href="https://www.npmjs.com/package/webrtc-adapter">available as an NPM package</a>.</p> + +<p>To learn more about Adapter.js, see <a href="/en-US/docs/Web/API/WebRTC_API/adapter.js">Improving compatibility using WebRTC adapter.js</a>.</p> + +<h2 id="WebRTC_concepts_and_usage">WebRTC concepts and usage</h2> + +<p>WebRTC serves multiple purposes; together with the <a href="/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams API</a>, they provide powerful multimedia capabilities to the Web, including support for audio and video conferencing, file exchange, screen sharing, identity management, and interfacing with legacy telephone systems including support for sending {{Glossary("DTMF")}} (touch-tone dialing) signals. Connections between peers can be made without requiring any special drivers or plug-ins, and can often be made without any intermediary servers.</p> + +<p>Connections between two peers are represented by the {{DOMxRef("RTCPeerConnection")}} interface. Once a connection has been established and opened using <code>RTCPeerConnection</code>, media streams ({{DOMxRef("MediaStream")}}s) and/or data channels ({{DOMxRef("RTCDataChannel")}}s) can be added to the connection.</p> + +<p>Media streams can consist of any number of tracks of media information; tracks, which are represented by objects based on the {{DOMxRef("MediaStreamTrack")}} interface, may contain one of a number of types of media data, including audio, video, and text (such as subtitles or even chapter names). Most streams consist of at least one audio track and likely also a video track, and can be used to send and receive both live media or stored media information (such as a streamed movie).</p> + +<p>You can also use the connection between two peers to exchange arbitrary binary data using the {{DOMxRef("RTCDataChannel")}} interface. This can be used for back-channel information, metadata exchange, game status packets, file transfers, or even as a primary channel for data transfer.</p> + +<p><em><strong>more details and links to relevant guides and tutorials needed</strong></em></p> + +<h2 id="WebRTC_interfaces">WebRTC interfaces</h2> + +<p>Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the interfaces in the list below by category. Please see the sidebar for an alphabetical list.</p> + +<h3 id="Connection_setup_and_management">Connection setup and management</h3> + +<p>These interfaces are used to set up, open, and manage WebRTC connections. Included are interfaces representing peer media connections, data channels, and interfaces used when exchanging information on the capabilities of each peer in order to select the best possible configuration for a two-way media connection..</p> + +<dl> + <dt>{{DOMxRef("RTCPeerConnection")}}</dt> + <dd>Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.</dd> + <dt>{{DOMxRef("RTCDataChannel")}}</dt> + <dd>Represents a bi-directional data channel between two peers of a connection.</dd> + <dt>{{DOMxRef("RTCDataChannelEvent")}}</dt> + <dd>Represents events that occur while attaching a {{DOMxRef("RTCDataChannel")}} to a {{DOMxRef("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.</dd> + <dt>{{DOMxRef("RTCSessionDescription")}}</dt> + <dd>Represents the parameters of a session. Each <code>RTCSessionDescription</code> consists of a description {{DOMxRef("RTCSessionDescription.type", "type")}} indicating which part of the offer/answer negotiation process it describes and of the {{Glossary("SDP")}} descriptor of the session.</dd> + <dt>{{DOMxRef("RTCSessionDescriptionCallback")}}</dt> + <dd>The RTCSessionDescriptionCallback is passed into the {{DOMxRef("RTCPeerConnection")}} object when requesting it to create offers or answers.</dd> + <dt>{{DOMxRef("RTCStatsReport")}}</dt> + <dd>Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{DOMxRef("RTCPeerConnection.getStats()")}}. Details about using WebRTC statistics can be found in <a href="/en-US/docs/Web/API/WebRTC_Statistics_API">WebRTC Statistics API</a>.</dd> + <dt>{{DOMxRef("RTCIceCandidate")}}</dt> + <dd>Represents a candidate Internet Connectivity Establishment ({{Glossary("ICE")}}) server for establishing an {{DOMxRef("RTCPeerConnection")}}.</dd> + <dt>{{DOMxRef("RTCIceTransport")}}</dt> + <dd>Represents information about an ICE transport.</dd> + <dt>{{DOMxRef("RTCIceServer")}}</dt> + <dd>Defines how to connect to a single ICE server (such as a {{Glossary("STUN")}} or {{Glossary("TURN")}} server).</dd> + <dt>{{DOMxRef("RTCPeerConnectionIceEvent")}}</dt> + <dd>Represents events that occur in relation to ICE candidates with the target, usually an {{DOMxRef("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.</dd> + <dt>{{DOMxRef("RTCRtpSender")}}</dt> + <dd>Manages the encoding and transmission of data for a {{DOMxRef("MediaStreamTrack")}} on an {{DOMxRef("RTCPeerConnection")}}.</dd> + <dt>{{DOMxRef("RTCRtpReceiver")}}</dt> + <dd>Manages the reception and decoding of data for a {{DOMxRef("MediaStreamTrack")}} on an {{DOMxRef("RTCPeerConnection")}}.</dd> + <dt>{{DOMxRef("RTCRtpContributingSource")}}</dt> + <dd>Contains information about a given contributing source (CSRC) including the most recent time a packet that the source contributed was played out.</dd> + <dt>{{DOMxRef("RTCTrackEvent")}}</dt> + <dd>The interface used to represent a {{domxref("RTCPeerConnection.track_event", "track")}} event, which indicates that an {{DOMxRef("RTCRtpReceiver")}} object was added to the {{DOMxRef("RTCPeerConnection")}} object, indicating that a new incoming {{DOMxRef("MediaStreamTrack")}} was created and added to the <code>RTCPeerConnection</code>.</dd> + <dt>{{DOMxRef("RTCConfiguration")}}</dt> + <dd>Used to provide configuration options for an <a href="https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection" title="The RTCPeerConnection interface represents a WebRTC connection between the local computer and a remote peer. It provides methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed."><code>RTCPeerConnection</code></a>.</dd> +</dl> + +<dl> + <dt>{{DOMxRef("RTCSctpTransport")}}</dt> + <dd>Provides information which describes a Stream Control Transmission Protocol (<strong>{{Glossary("SCTP")}}</strong>) transport and also provides a way to access the underlying Datagram Transport Layer Security (<strong>{{Glossary("DTLS")}}</strong>) transport over which SCTP packets for all of an <a href="/en-US/docs/Web/API/RTCPeerConnection" title="The RTCPeerConnection interface represents a WebRTC connection between the local computer and a remote peer. It provides methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed."><code>RTCPeerConnection</code></a>'s data channels are sent and received.</dd> + <dt>{{DOMxRef("RTCSctpTransportState")}}</dt> + <dd>Indicates the state of an {{DOMxRef("RTCSctpTransport")}} instance.</dd> +</dl> + +<h3 id="Identity_and_security">Identity and security</h3> + +<p>The WebRTC API includes a number of interfaces which are used to manage security and identity.</p> + +<dl> + <dt>{{DOMxRef("RTCIdentityProvider")}}</dt> + <dd>Enables a user agent is able to request that an identity assertion be generated or validated.</dd> + <dt>{{DOMxRef("RTCIdentityAssertion")}}</dt> + <dd>Represents the identity of the remote peer of the current connection. If no peer has yet been set and verified this interface returns <code>null</code>. Once set it can't be changed.</dd> + <dt>{{DOMxRef("RTCIdentityProviderRegistrar")}}</dt> + <dd>Registers an identity provider (idP).</dd> + <dt>{{DOMxRef("RTCIdentityEvent")}}</dt> + <dd>Represents an identity assertion generated by an identity provider (idP). This is usually for an {{DOMxRef("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.</dd> + <dt>{{DOMxRef("RTCIdentityErrorEvent")}}</dt> + <dd>Represents an error associated with the identity provider (idP). This is usually for an {{DOMxRef("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.</dd> + <dt>{{DOMxRef("RTCCertificate")}}</dt> + <dd>Represents a certificate that an {{DOMxRef("RTCPeerConnection")}} uses to authenticate.</dd> +</dl> + +<h3 id="Telephony">Telephony</h3> + +<p>These interfaces are related to interactivity with Public-Switched Telephone Networks (PTSNs).</p> + +<dl> + <dt>{{DOMxRef("RTCDTMFSender")}}</dt> + <dd>Manages the encoding and transmission of Dual-Tone Multi-Frequency ({{Glossary("DTMF")}}) signaling for an {{DOMxRef("RTCPeerConnection")}}.</dd> + <dt>{{DOMxRef("RTCDTMFToneChangeEvent")}}</dt> + <dd>Used by the {{domxref("RTCDTMFSender.tonechange_event", "tonechange")}} event to indicate that a DTMF tone has either begun or ended. This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).</dd> +</dl> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Protocols">Introduction to WebRTC protocols</a></dt> + <dd>This article introduces the protocols on top of which the WebRTC API is built.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Connectivity">WebRTC connectivity</a></dt> + <dd>A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Session_lifetime">Lifetime of a WebRTC session</a></dt> + <dd>WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation">Establishing a connection: The perfect negotiation pattern</a></dt> + <dd><strong>Perfect negotiation</strong> is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling">Signaling and two-way video calling</a></dt> + <dd>A tutorial and example which turns a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.</dd> + <dt><a href="/en-US/docs/Web/Media/Formats/WebRTC_codecs">Codecs used by WebRTC</a></dt> + <dd>A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Using_data_channels">Using WebRTC data channels</a></dt> + <dd>This guide covers how you can use a peer connection and an associated {{DOMxRef("RTCDataChannel")}} to exchange arbitrary data between two peers.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Using_DTMF">Using DTMF with WebRTC</a></dt> + <dd>WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{DOMxRef("RTCDTMFSender")}} interface. This guide shows how to do so.</dd> +</dl> + +<h2 id="Tutorials">Tutorials</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/adapter.js">Improving compatibility using WebRTC adapter.js</a></dt> + <dd>The WebRTC organization <a href="https://github.com/webrtc/adapter/">provides on GitHub the WebRTC adapter</a> to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Taking_still_photos">Taking still photos with WebRTC</a></dt> + <dd>This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample">A simple RTCDataChannel sample</a></dt> + <dd>The {{DOMxRef("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the <a href="/en-US/docs/Web/API/WebSocket_API">WebSocket API</a>, so that the same programming model can be used for each.</dd> +</dl> + +<h2 id="Resources">Resources</h2> + +<h3 id="Protocols">Protocols</h3> + +<h4 id="WebRTC-proper_protocols">WebRTC-proper protocols</h4> + +<ul> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-alpn/"><cite>Application Layer Protocol Negotiation for Web Real-Time Communications</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-audio/"><cite>WebRTC Audio Codec and Processing Requirements</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-channel/"><cite>RTCWeb Data Channels</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-protocol/"><cite>RTCWeb Data Channel Protocol</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-rtp-usage/"><cite>Web Real-Time Communication (WebRTC): Media Transport and Use of RTP</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-security-arch/"><cite>WebRTC Security Architecture</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-transports/"><cite>Transports for RTCWEB</cite></a></li> +</ul> + +<h4 id="Related_supporting_protocols">Related supporting protocols</h4> + +<ul> + <li><a href="https://tools.ietf.org/html/rfc5245">Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocol</a></li> + <li><a href="https://tools.ietf.org/html/rfc5389"><cite>Session Traversal Utilities for NAT (STUN)</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7064"><cite>URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7065"><cite>Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc3264"><cite>An Offer/Answer Model with Session Description Protocol (SDP)</cite></a></li> + <li><a href="https://datatracker.ietf.org/doc/draft-ietf-tram-turn-third-party-authz/"><cite>Session Traversal Utilities for NAT (STUN) Extension for Third Party Authorization</cite></a></li> +</ul> + +<h4 id="WebRTC_statistics"><cite>WebRTC statistics</cite></h4> + +<ul> + <li><a href="/en-US/docs/Web/API/WebRTC_Statistics_API">WebRTC Statistics API</a></li> +</ul> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebRTC 1.0')}}</td> + <td>{{Spec2('WebRTC 1.0')}}</td> + <td>The initial definition of the API of WebRTC.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>The initial definition of the object conveying the stream of media content.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture DOM Elements')}}</td> + <td>{{Spec2('Media Capture DOM Elements')}}</td> + <td>The initial definition on how to obtain stream of content from DOM Elements</td> + </tr> + </tbody> +</table> + +<p>In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under <a href="#Protocols">resources</a>.</p> + +<h2 class="Related_Topics" id="See_also">See also</h2> + +<ul> + <li>{{DOMxRef("MediaDevices")}}</li> + <li>{{DOMxRef("MediaStreamEvent")}}</li> + <li>{{DOMxRef("MediaStreamConstraints")}}</li> + <li>{{DOMxRef("MediaStreamTrack")}}</li> + <li>{{DOMxRef("MessageEvent")}}</li> + <li>{{DOMxRef("MediaStream")}}</li> + <li><a href="/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams API</a></li> + <li><a href="https://hacks.mozilla.org/2015/06/firefox-multistream-and-renegotiation-for-jitsi-videobridge/">Firefox multistream and renegotiation for Jitsi Videobridge</a></li> + <li><a href="https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/">Peering Through the WebRTC Fog with SocketPeer</a></li> + <li><a href="https://hacks.mozilla.org/2014/04/inside-the-party-bus-building-a-web-app-with-multiple-live-video-streams-interactive-graphics/">Inside the Party Bus: Building a Web App with Multiple Live Video Streams + Interactive Graphics</a></li> + <li><a href="/en-US/docs/Web/Media">Web media technologies</a></li> +</ul> diff --git a/files/vi/web/api/webrtc_api/protocols/index.html b/files/vi/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..8d3bcb81e4 --- /dev/null +++ b/files/vi/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,57 @@ +--- +title: Introduction to WebRTC protocols +slug: Web/API/WebRTC_API/Protocols +translation_of: Web/API/WebRTC_API/Protocols +--- +<div>{{WebRTCSidebar}}{{draft}}</div> + +<p>Bài viết này giới thiệu các giao thức của WebRTC API được đã được xây dựng.</p> + +<h2 id="ICE">ICE</h2> + +<p><a href="http://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment">Interactive Connectivity Establishment (ICE)</a> là một khuân mẫu cho phép trình duyệt của bạn kết nối với các trình duyệt khác. Có rất nhiều lý do tại sao việc kết nối trực tiếp từ A đến B một cách đơn giản sẽ không làm việc. Nó cần vượt qua firewall cái đã ngăn chặn mở môt cuộc kết nối trực tiếp, nó cung cấp cho bạn một địa chỉ duy nhất, trong hầu hết các trường hợp thiết bị của bạn không có địa chỉ public I, và chuyển tiếp dữ liệu thông qua một server nếu bộ định tuyến (router) của bạn không cho phép bạn kết nối một cách trực tiếp với browser khác. ICE sử dụng STUN hoặc TURN hay cả hai server để hoàn thành việc này như đã mô tả ở trên.</p> + +<h2 id="STUN">STUN</h2> + +<p><a href="http://en.wikipedia.org/wiki/STUN">Session Traversal Utilities for <u>NAT</u> (STU<u>N</u>)</a> (Từ viết tắt trong một từ viết tắt) là một giao thức để phát hiện ra địa chỉ IP pubic của bạn và xác định bất cứ hạn chế nào trong bộ định tuyến (router) của bạn đã ngăn chặn một cuộc kết nối trực tiếp với các browsers.</p> + +<p>Client sẽ gửi một yêu cầu tới STUN server thông qua internet, STUN server sẽ phản hồi địa chỉ IP public và client có thể có hoặc không truy cập được phìa sau bộ định tuyến NAT.</p> + +<p><img alt="An interaction between two users of a WebRTC application involving a STUN server." src="https://mdn.mozillademos.org/files/6115/webrtc-stun.png" style="display: block; height: 378px; margin: 0px auto; width: 259px;"></p> + +<h2 id="NAT">NAT</h2> + +<p><a href="https://en.wikipedia.org/wiki/Network_address_translation">Network Address Translation (NAT)</a> được sử dụng để cung cấp cho thiết bị của bạn một địa chỉ IP public. Một bộ định tuyến (router) sẽ có một đia chỉ IP public và mỗi thiết bị được kết nối đến router sẽ có một đia chỉ IP private. Các requests sẽ được chuyển đổi từ địa chỉ IP private sang địa chỉ IP pubic với một cổng (port) duy nhất. Với cách này bạn không cần một địa chỉ IP public riêng cho từng thiết bị nhưng vẫn có thể được phát hiện trên internet.</p> + +<p>Một vài bộ định tuyến (routers) sẽ có những ngăn cản kết nối tới những thiết bị trên network. Điều này có nghĩa là ngay cả việc chúng ta có địa chỉ IP public đã được tìm ra bở STUN server, nhưng không một ai có thể tạo ra một kết nối. Trong tình huốn này chúng ta cần chuyển sang TURN.</p> + +<h2 id="TURN">TURN</h2> + +<p>Một vài bộ định tuyến (routers) sử dụng NAT được gọi là 'Symmetric NAT'. Nghĩa là bộ định tuyến (router) chỉ chấp nhận kết nối từ những peer mà bạn đã kết nối trước đó.</p> + +<p><a href="http://en.wikipedia.org/wiki/TURN">Traversal Using Relays around NAT (TURN)</a> có nghĩa là vượt qua hạn chế Symmetric NAT bằng các mở một kết nối với TURN server và truyền tải tất cả thông tin thông qua TURN server. Bạn sẽ tạo một kết nối với một TURN server và nói với tất cả các peer để gửi những gói tin đến server để sau đó nó sẽ chuyển lại cho bạn. Điều này rõ ràng đi kèm với các loại chi phí vì vậy nó chỉ được sử dụng nếu không có lựa chon nào thay thế.</p> + +<p><img alt="An interaction between two users of a WebRTC application involving STUN and TURN servers." src="https://mdn.mozillademos.org/files/6117/webrtc-turn.png" style="display: block; height: 297px; margin: 0px auto; width: 295px;"></p> + +<h2 id="SDP">SDP</h2> + +<p><a href="http://en.wikipedia.org/wiki/Session_Description_Protocol">Session Description Protocol (SDP)</a> là một tiêu chuẩn mô tả cho những nội dung đa phương tiện của một kết nối như độ phân giản (resolution), định dạn (formats), mã (codecs), mã hóa (encryption), v.v. cho nên tất cả các peers có thể hiểu những loại dữ liệu đang gửi đi. Vì vậy đây là siêu dữ liệu mô tả nội dung chứ không phải chính nội dung đa phương tiện.</p> + +<p>Về mặt kỹ thuận, SDP không thực sự là một protocol, nhưng định dạng data được sử dụng để mô tả kết nối chia sẻ đa phương tiện giữa các thiết bị.</p> + +<p>Documenting SDP is well outside the scope of this documentation; however, there are a few things worth noting here.</p> + +<p>Tài liệu SDP nằm ngoài phạm vi của tài liệu này. Tuy nhiên, có một vài thứ thực sự đáng chú ý ở đây.</p> + +<h3 id="Cấu_trúc">Cấu trúc</h3> + +<p>SDP bao gồm một hay nhiều dòng text UTF-8, mỗi dòng bắt đầu với một kiểu ký tự, theo sau là một ký tự dấu bằng (<code>"="</code>), theo sau nữa là nội dung có cấu trúc bao gồm giá trị hay mô tả mà định dạng của nó phụ thuộc vào kiểu. Những dòng nội dung bắt đầu với một chữ (letter) thường được gọi là "letter-lines". Ví dụ, những dòng cung cấp mô tả đa phương tiện có kiểu <code>"m"</code>, vì vậy những dòng của nó được xem như là "m-lines"</p> + +<h3 id="Thông_tin_tham_khảo">Thông tin tham khảo</h3> + +<p>Để tìm hiểu thêm về SDP, tham khảo những tài liệu hữu ích dưới đây:</p> + +<ul> + <li>Specification: {{RFC(4566, "SDP: Session Description Protocol")}}</li> + <li><a href="https://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml">IANA registry of SDP parameters</a></li> +</ul> diff --git a/files/vi/web/api/websockets_api/index.html b/files/vi/web/api/websockets_api/index.html new file mode 100644 index 0000000000..e69c174077 --- /dev/null +++ b/files/vi/web/api/websockets_api/index.html @@ -0,0 +1,253 @@ +--- +title: The WebSocket API (WebSockets) +slug: Web/API/WebSockets_API +tags: + - API + - Client + - Communication + - NeedsTranslation + - Overview + - Server + - TopicStub + - Two-Way + - WebSocket + - WebSocket API + - WebSockets + - data + - interactive +translation_of: Web/API/WebSockets_API +--- +<p>{{DefaultAPISidebar("Websockets API")}}</p> + +<p>Các <strong>WebSocket API</strong> là một công nghệ tiên tiến mà nó có thể tạo ra một phiên giao tiếp tương tác hai chiều giữa trình duyệt của người dùng và một máy chủ (server). Với API này, bạn có thể gửi những thông báo tới một máy chủ và nhận những phản hồi (response) hướng sự kiện (event-driven) mà không phải liên tục gửi yêu cầu máy chủ để nhận một câu trả lời.</p> + +<div class="note"> +<p><strong>Chú ý:</strong> Mặc dù một kết nối Websocket có một số tính năng hơi giống với các socket kiểu Unix chuẩn, Nhưng chúng lại không có liên quan gì với nhau.</p> +</div> + +<h2 id="Giao_diện_(Interfaces)">Giao diện (Interfaces)</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebSocket" title="en/WebSockets/WebSockets reference/WebSocket"><code>WebSocket</code></a></dt> + <dd>Một giao diện cơ bản cho việc kết nối tới một máy chủ Websocket và sau đó là việc gửi và nhận dữ liệu trên kết nối đó.</dd> + <dt><code><a href="/en-US/docs/Web/API/CloseEvent" title="en/WebSockets/WebSockets reference/CloseEvent">CloseEvent</a></code></dt> + <dd>Sự kiện được gửi đi từ một đối tượng Websocket khi kết nối được đóng lại.</dd> + <dt><a href="/en-US/docs/Web/API/MessageEvent" title="en/WebSockets/WebSockets reference/MessageEvent"><code>MessageEvent</code></a></dt> + <dd>Sự kiện được gửi bởi đối tượng Websocket khi một thông điệp được nhận từ một máy chủ.</dd> +</dl> + +<h2 class="Tools" id="Tools" name="Tools">Công cụ</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2017/06/introducing-humblenet-a-cross-platform-networking-library-that-works-in-the-browser/">HumbleNet</a>: Một thư viện kết nối mạng đa nền tảng làm việc trong trình duyệt. Nó bao gồm một trình bao bọc Websocket và WebRTC viết bằng C mà khái quát những sự khác biệt trên trình duyệt, tạo sự thuận lợi cho việc phát triển các game và ứng dụng với kết nối nhiều người dùng cùng lúc.</li> + <li><a href="https://github.com/uWebSockets/uWebSockets">µWebSockets</a>: Triển khai máy chủ Websocket và ứng dụng phía người dùng với khả năng mở rộng cao hơn cho nền tảng C++ 11 và NodeJS.</li> + <li><a href="https://github.com/ClusterWS/ClusterWS">ClusterWS</a>: Một Framework nhẹ, nhanh và mạnh mẽ dể xây dựng các ứng dụng Websocket có khả năng mở rộng trên nền tảng NodeJS.</li> + <li><a class="external" href="http://socket.io" title="http://socket.io/">Socket.IO</a>: Một thư viện chuyển đổi giao thức bên thứ ba dựa trên nền tảng long polling/WebSocket cho <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a>.</li> + <li><a href="http://socketcluster.io/">SocketCluster</a>: Một pub/sub WebSocket framework cho <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a> với sự tập trung vào khả năng mở rộng.</li> + <li><a class="link-https" href="https://github.com/Worlize/WebSocket-Node" title="https://github.com/Worlize/WebSocket-Node">WebSocket-Node</a>: Một triển khai các API máy chủ WebSocket cho <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a>.</li> + <li><a href="http://www.totaljs.com">Total.js</a>: Một framework làm ứng dụng web cho <a href="http://www.nodejs.org">Node.js</a> (Ví dụ: <a href="https://github.com/totaljs/examples/tree/master/websocket">WebSocket chat</a>)</li> + <li><a href="https://www.npmjs.com/package/faye-websocket">Faye</a>: Một kết nối <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSocket</a> (kết nối hai chiều) và <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource/">EventSource</a> (Kết nối một chiều) cho ứng dụng và máy chủ <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a>.</li> + <li><a href="http://signalr.net/">SignalR</a>: SignalR sẽ sử dụng WebSockets bên dưới dụng vỏ bọc khi nó khả dụng, và dự phòng chuyển đổi với các kí thuật và công nghệ khác khi nó không còn khả dụng, trong khi mã nguồn ứng dụng của bạn vẫn được giữ nguyên.</li> + <li><a href="https://caddyserver.com/docs/websocket">Caddy</a>: Máy chủ web có khả năng ủy quyền các lệnh tùy ý (vào/ra) như một websocket.</li> + <li><a href="https://github.com/websockets/ws">ws</a>: Một thư viện websocket phổ biến cho cả máy chủ và client trên <a href="https://nodejs.org/en/">Node.js</a>.</li> + <li><a href="https://github.com/bigstepinc/jsonrpc-bidirectional">jsonrpc-bidirectional</a>: Asynchronous RPC which, trên một kết nối đơn,có thể có những tính năng đã xuất trên cả máy chủ và máy khách cùng lúc (máy khách gọi máy chủ hoặc ngược lại).</li> +</ul> + +<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Chủ đề liên quan</h2> + +<ul> + <li><a href="/en-US/docs/AJAX" title="AJAX">AJAX</a></li> + <li><a href="/en-US/docs/JavaScript" title="JavaScript">JavaScript</a></li> +</ul> + +<p> </p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comments</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td><a href="https://www.w3.org/TR/websockets/">WebSockets</a></td> + <td><span class="spec-CR">Candidate Recommendation</span></td> + <td> </td> + </tr><tr> + <td>{{RFC(6455, "The WebSocket Protocol")}}</td> + <td><span class="spec-RFC">IETF RFC</span></td> + <td> </td> + </tr> + </tbody> +</table> + +<p> </p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a class="external" href="http://tools.ietf.org/html/rfc6455">RFC 6455 — The WebSocket Protocol</a></li> + <li><a class="external" href="http://www.w3.org/TR/websockets/">WebSocket API Specification</a></li> + <li><a href="/en-US/docs/Server-sent_events" title="Server-sent_events">Server-Sent Events</a></li> +</ul> + +<h2 id="Khả_năng_tương_thích_với_các_trình_duyệt">Khả năng tương thích với các trình duyệt</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Version -76 support {{obsolete_inline}}</td> + <td>6</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatNo}}</td> + <td>11.00 (disabled)</td> + <td>5.0.1</td> + </tr> + <tr> + <td>Protocol version 7 support {{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("6.0")}}<br> + {{property_prefix("Moz")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Protocol version 10 support {{obsolete_inline}}</td> + <td>14</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("7.0")}}<br> + {{property_prefix("Moz")}}</td> + <td>HTML5 Labs</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Standard - RFC 6455 Support</td> + <td>43</td> + <td>14</td> + <td>{{CompatGeckoDesktop("48.0")}}</td> + <td>10</td> + <td>12.10</td> + <td>6.0</td> + </tr> + <tr> + <td>Usable in Workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("37.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Version -76 support {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Protocol version 7 support {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Protocol version 8 support (IETF draft 10) {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Standard - RFC 6455 Support</td> + <td>4.4</td> + <td>(Yes)</td> + <td>{{CompatGeckoDesktop("11.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>12.10</td> + <td>6.0</td> + </tr> + <tr> + <td>Usable in Workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Chú_ý_về_Gecko">Chú ý về Gecko</h3> + +<p>Việc hỗ trợ Websocket trên Firefox đang được tiếp tục với việc theo dõi sư thay đổi của đặc tả Websocket. Firefox 6 triển khai phiên bản 7 của các giao thức cơ bản, trong khi Firefox 7 triển khai phiên bản 8 (như mô tả bởi IETF draft 10). Firefox di đông đón nhận sự hỗ trợ WebSocket từ phiên bản Firefox di động 7.0.</p> + +<h4 id="Gecko_6.0">Gecko 6.0</h4> + +<p>Trước Gecko 6.0 {{geckoRelease("6.0")}}, Đã có, không chính xác, một đối tượng <code>WebSocket</code> mà một số trang đã nghĩ rằng đó là việc bao hàm các dịch vụ <code>WebSocket</code> không có tiền tố; Đối tượng này vừa được đổi tên thành <code>MozWebSocket</code>.</p> + +<h4 id="Gecko_7.0">Gecko 7.0</h4> + +<p>Bắt đầu từ phiên bản Gecko 7.0 {{geckoRelease("7.0")}}, <code>thông số network.websocket.max-connections</code> được sử dụng để xác định số lượng kết nối websocket tối đa có thể được mở trong một khoảng thời gian nhất định. Giá trị mặc định là 200.</p> + +<h4 id="Gecko_8.0">Gecko 8.0</h4> + +<p>Bắt đầu từ phiên bản Gecko 8.0 {{geckoRelease("8.0")}}, phần mở rộng của luồng deflate-stream tới giao thức WebSocket đã bị vô hiệu hóa, bởi vì nó không còn được dùng trong các bản đặc tả. Điều này giải quyết vấn đề không tương thích giữa một số trang web.</p> + +<h4 id="Gecko_11.0">Gecko 11.0</h4> + +<p>Trước phiên bản Gecko 11.0, Cả thông điệp đến và đi đều bị giới hạn ở kích thức 16MB. Bây giờ chúng có thể lên đến kích thước 2GB. Chú ý, tuy vậy vẫn còn tùy thuộc vào kích thước bộ nhớ (đặc biệt là trên thiết bị di động) làm cho nó chỉ là kích thước lý thuyết không phải là kích thước thực tế. Trong thực tế, việc truyền các dữ liệu kích thước như vậy sẽ thất bại nếu thiết bị không có đủ bộ nhớ.</p> + +<p>Ngoài ra, ArrayBuffer hỗ trợ cho việc gửi và nhận dữ liệu nhị phân đã được triển khai.</p> + +<p>Kể từ phiên bản Gecko 11.0, API Websocket không còn được thêm tiền tố nữa.</p> diff --git a/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html new file mode 100644 index 0000000000..6258f6236f --- /dev/null +++ b/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html @@ -0,0 +1,217 @@ +--- +title: Writing a WebSocket server in Java +slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +tags: + - WebSocket +translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +--- +<h2 id="Giới_thiệu">Giới thiệu</h2> + +<p>Đây là một ví dụ để cho bạn biết thế nào là một WebSocket API server sử dụng Oracle Java.<br> + <br> + Mặc dù có nhiều ngôn ngữ sercer-side khác nhau bạn có thể sử dụng để tạo một WebSocket server, đây là ví dụ sử dụng Oracle Java code đơn giản.</p> + +<p>Sever này phù hợp tiêu chuẩn <a href="http://tools.ietf.org/html/rfc6455" title="http://tools.ietf.org/html/rfc6455">RFC 6455</a>, vì vậy nó chỉ kết nối từ Chrome version 16, Firefox 11, IE 10 và cao hơn.</p> + +<h2 id="Bước_1">Bước 1:</h2> + +<p>WebSockets truyền đạt về một <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" title="http://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP (Transmission Control Protocol)</a> kết nối. Lớp Java's <a href="http://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html">ServerSocket</a> là nằm ở trong gói <em>java.net</em>.</p> + +<h3 id="ServerSocket">ServerSocket</h3> + +<p>Xây dựng:</p> + +<pre class="brush: java"><code><span class="memberNameLink">ServerSocket</span>(int port)</code></pre> + +<p>Khi bạn thuyết trình về ServerSocket class, it is bound to the port number you specified by the <em>port</em> argument.</p> + +<p><span style="line-height: 1.572;">Here's how to implement what we have learnt:</span></p> + +<pre class="brush: java">import java.net.ServerSocket; +import java.net.Socket; + +public class Server{ + public static void main(String[] args){ + ServerSocket server = new ServerSocket(80); + + System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection..."); + + Socket client = server.accept(); + + System.out.println("A client connected."); + } +}</pre> + +<h3 id="Socket">Socket</h3> + +<p>Methods:</p> + +<ul> + <li><code>java.net.</code><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html" title="class in java.net">Socket</a><code> <span class="memberNameLink"><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getInputStream--">getInputStream</a></span>()</code><br> + Returns an input stream for this socket.</li> + <li><code>java.net.</code><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html" title="class in java.net">Socket</a><code> <span class="memberNameLink"><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getOutputStream--">getOutputStream</a></span>()</code><br> + Returns an output stream for this socket.</li> +</ul> + +<h3 id="OutputStream">OutputStream</h3> + +<p>Methods:</p> + +<pre class="brush: java">write<code>(byte[] b, int off, int len)</code></pre> + +<p>Writes <em><code>len</code></em> bytes from the specified byte array starting at offset <em><code>off</code></em> to this output stream.</p> + +<h3 id="InputStream">InputStream</h3> + +<p>Methods:</p> + +<pre class="brush: java"><span class="brush: cpp" style="line-height: 1.572;">read</span><code>(byte[] b, int off, int len)</code></pre> + +<p>Reads up to <em>len</em> bytes of data from the input stream into an array of bytes.<em> </em></p> + +<p>Let us extend our example.</p> + +<pre class="brush: java">Socket client = server.accept(); + +System.out.println("A client connected."); + +InputStream in = client.getInputStream(); + +OutputStream out = client.getOutputStream(); + +new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();</pre> + +<h2 id="Handshaking">Handshaking</h2> + +<p>When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking.</p> + +<pre class="brush: java">import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +//translate bytes of request to string +String data = new Scanner(in,"UTF-8").useDelimiter("\\r\\n\\r\\n").next(); + +Matcher get = Pattern.compile("^GET").matcher(data); + +if (get.find()) { + +} else { + +}</pre> + +<p>Creating the response is easier than understanding why you must do it in this way.</p> + +<p>You must,</p> + +<ol> + <li>Obtain the value of <em>Sec-WebSocket-Key</em> request header without any leading and trailing whitespace</li> + <li>Link it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"</li> + <li>Compute SHA-1 and Base64 code of it</li> + <li>Write it back as value of <em>Sec-WebSocket-Accept</em> response header as part of a HTTP response.</li> +</ol> + +<pre class="brush: java">if (get.find()) { + Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data); + match.find(); + byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: websocket\r\n" + + "Sec-WebSocket-Accept: " + + DatatypeConverter + .printBase64Binary( + MessageDigest + .getInstance("SHA-1") + .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + .getBytes("UTF-8"))) + + "\r\n\r\n") + .getBytes("UTF-8"); + + out.write(response, 0, response.length); +} +</pre> + +<h2 id="Decoding_messages">Decoding messages</h2> + +<p>After a successful handshake, client can send messages to the server, but now these are encoded.</p> + +<p>If we send "abcdef", we get these bytes:</p> + +<table> + <tbody> + <tr> + <td>129</td> + <td>134</td> + <td>167</td> + <td>225</td> + <td>225</td> + <td>210</td> + <td>198</td> + <td>131</td> + <td>130</td> + <td>182</td> + <td>194</td> + <td>135</td> + </tr> + </tbody> +</table> + +<p>- 129:</p> + +<table> + <thead> + <tr> + <th scope="col">FIN (Is this the whole message?)</th> + <th scope="col">RSV1</th> + <th scope="col">RSV2</th> + <th scope="col">RSV3</th> + <th scope="col">Opcode</th> + </tr> + </thead> + <tbody> + <tr> + <td>1</td> + <td>0</td> + <td>0</td> + <td>0</td> + <td>0x1=0001</td> + </tr> + </tbody> +</table> + +<p>FIN: You can send your message in frames, but now keep things simple.<br> + <span style="line-height: 1.572;">Opcode </span><em>0x1</em><span style="line-height: 1.572;"> means this is a text. </span><a href="http://tools.ietf.org/html/rfc6455#section-5.2" style="line-height: 1.572;" title="http://tools.ietf.org/html/rfc6455#section-5.2">Full list of Opcodes</a></p> + +<p>- 134:</p> + +<p>If the second byte minus 128 is between 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit MUST be 0) are the length.</p> + +<div class="note"> +<p>I can take 128 because the first bit is always 1.</p> +</div> + +<p>- 167, 225, 225 and 210 are the bytes of the key to decode. It changes every time.</p> + +<p>- The remaining encoded bytes are the <span style="line-height: 1.572;">message.</span></p> + +<h3 id="Decoding_algorithm">Decoding algorithm</h3> + +<p>decoded byte = encoded byte XOR (position of encoded byte BITWISE AND 0x3)th byte of key</p> + +<p>Ví dụ trên Java:</p> + +<pre class="brush: java">byte[] decoded = new byte[6]; +byte[] encoded = new byte[] {198, 131, 130, 182, 194, 135}; +byte[] key = byte[4] {167, 225, 225, 210}; + +for (int i = 0; i < encoded.length; i++) { + decoded[i] = (byte)(encoded[i] ^ key[i & 0x3]); +}</pre> + +<h2 id="Tài_liệu_liên_quan">Tài liệu liên quan</h2> + +<ul> + <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_servers">Writing WebSocket servers</a></li> +</ul> + +<div id="cke_pastebin" style="position: absolute; top: 2209.23px; width: 1px; height: 1px; overflow: hidden; left: -1000px;"> </div> diff --git a/files/vi/web/api/window/index.html b/files/vi/web/api/window/index.html new file mode 100644 index 0000000000..1419252c54 --- /dev/null +++ b/files/vi/web/api/window/index.html @@ -0,0 +1,729 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - Browser + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - Tab + - TopicStub + - Window + - global + - global scope + - scope +translation_of: Web/API/Window +--- +<div>{{APIRef("DOM")}}</div> + +<p><span class="seoSummary">The <strong><code>Window</code></strong> interface represents a window containing a DOM document; the <code>document</code> property points to the <a href="/en-US/docs/DOM/document">DOM document</a> loaded in that window.</span> A window for a given document can be obtained using the {{domxref("document.defaultView")}} property.</p> + +<p>A global variable, <code>window</code>, representing the window in which the script is running, is exposed to JavaScript code.</p> + +<p>The <code>Window</code> interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the <code>Window</code> interface is a suitable place to include these items that need to be globally available. Many of these are documented in the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript Reference</a> and the <a href="/en-US/docs/Web/API/Document_Object_Model" title="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a>.</p> + +<p>In a tabbed browser, each tab is represented by its own <code>Window</code> object; the global <code>window</code> seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as {{Domxref("Window.resizeTo", "resizeTo()")}} and {{Domxref("Window.innerHeight", "innerHeight")}}. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Constructors">Constructors</h2> + +<p>See also the <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Interfaces</a>.</p> + +<dl> + <dt>{{domxref("DOMParser")}}</dt> + <dd><code>DOMParser</code> can parse XML or HTML source stored in a string into a DOM <a href="https://developer.mozilla.org/en-US/docs/DOM/document" title="document">Document</a>. <code>DOMParser</code> is specified in <a href="https://w3c.github.io/DOM-Parsing/" title="http://html5.org/specs/dom-parsing.html">DOM Parsing and Serialization</a>.</dd> + <dt>{{domxref("Window.GeckoActiveXObject")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Image")}}</dt> + <dd>Used for creating an {{domxref("HTMLImageElement")}}.</dd> + <dt>{{domxref("Option")}}</dt> + <dd>Used for creating an {{domxref("HTMLOptionElement")}}</dd> + <dt>{{domxref("Window.QueryInterface")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Used for creating a <a href="/en-US/docs/DOM/Using_web_workers">Web worker</a></dd> + <dt>{{domxref("Window.XMLSerializer")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XPCNativeWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XPCSafeJSObjectWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.</em></p> + +<p>Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.</p> + +<dl> + <dt>{{domxref("Window.closed")}} {{Non-standard_inline}} {{readOnlyInline}}</dt> + <dd>This property indicates whether the current window is closed or not.</dd> + <dt>{{domxref("Window.console")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the console object which provides access to the browser's debugging console.</dd> + <dt>{{domxref("Window.content")}} and <code>Window._content</code> {{Non-standard_inline}} {{obsolete_inline}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.</dd> + <dt>{{domxref("Window.controllers")}} {{non-standard_inline}} {{ReadOnlyInline}}</dt> + <dd>Returns the XUL controller objects for the current chrome window.</dd> + <dt>{{domxref("Window.customElements")}} {{ReadOnlyInline}}</dt> + <dd>returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new <a href="/en-US/docs/Web/Web_Components/Using_custom_elements">custom elements</a> and get information about previously registered custom elements.</dd> + <dt>{{domxref("Window.crypto")}} {{readOnlyInline}}</dt> + <dd>Returns the browser crypto object.</dd> + <dt>{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}</dt> + <dd>Gets/sets the status bar text for the given window.</dd> + <dt>{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}} {{ReadOnlyInline}}</dt> + <dd>Returns the ratio between physical pixels and device independent pixels in the current display.</dd> + <dt>{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}</dt> + <dd>Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.</dd> + <dt>{{domxref("Window.directories")}} {{obsolete_inline}}</dt> + <dd>Synonym of {{domxref("window.personalbar")}}</dd> + <dt>{{domxref("Window.document")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the document that the window contains.</dd> + <dt>{{domxref("Window.DOMMatrix")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMMatrix")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.</dd> + <dt>{{domxref("Window.DOMMatrixReadOnly")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMMatrixReadOnly")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.</dd> + <dt>{{domxref("Window.DOMPoint")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMPoint")}} object, which represents a 2D or 3D point in a coordinate system.</dd> + <dt>{{domxref("Window.DOMPointReadOnly")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMPointReadOnly")}} object, which represents a 2D or 3D point in a coordinate system.</dd> + <dt>{{domxref("Window.DOMQuad")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMQuad")}} object, which provides represents a quadrilaterial object, that is one having four corners and four sides.</dd> + <dt>{{domxref("Window.DOMRect")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMRect")}} object, which represents a rectangle.</dd> + <dt>{{domxref("Window.DOMRectReadOnly")}} {{readOnlyInline}} {{experimental_inline}}</dt> + <dd>Returns a reference to a {{domxref("DOMRectReadOnly")}} object, which represents a rectangle.</dd> + <dt>{{domxref("Window.event")}} {{ReadOnlyInline}}</dt> + <dd>Returns the <strong>current event</strong>, which is the event currently being handled by the JavaScript code's context, or <code>undefined</code> if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible.</dd> + <dt>{{domxref("Window.frameElement")}} {{readOnlyInline}}</dt> + <dd>Returns the element in which the window is embedded, or null if the window is not embedded.</dd> + <dt>{{domxref("Window.frames")}} {{readOnlyInline}}</dt> + <dd>Returns an array of the subframes in the current window.</dd> + <dt>{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>This property indicates whether the window is displayed in full screen or not.</dd> + <dt>{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}</dt> + <dd>Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.<br> + Was: Multiple storage objects that are used for storing data across multiple pages.</dd> + <dt>{{domxref("Window.history")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the history object.</dd> + <dt>{{domxref("Window.innerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.</dd> + <dt>{{domxref("Window.innerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.</dd> + <dt>{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}</dt> + <dd>Indicates whether a context is capable of using features that require secure contexts.</dd> + <dt>{{domxref("Window.length")}} {{readOnlyInline}}</dt> + <dd>Returns the number of frames in the window. See also {{domxref("window.frames")}}.</dd> + <dt>{{domxref("Window.location")}}</dt> + <dd>Gets/sets the location, or current URL, of the window object.</dd> + <dt>{{domxref("Window.locationbar")}} {{ReadOnlyInline}}</dt> + <dd>Returns the locationbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.localStorage")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("Window.menubar")}} {{ReadOnlyInline}}</dt> + <dd>Returns the menubar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the <a href="/en-US/docs/The_message_manager">message manager</a> object for this window.</dd> + <dt>{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}</dt> + <dd>The time in milliseconds since epoch at which the current animation cycle began. Use {{domxref("Animation.startTime")}} instead.</dd> + <dt>{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See <code>mozScreenPixelsPerCSSPixel</code> in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See <code>mozScreenPixelsPerCSSPixel</code> for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozPaintCount")}} {{non-standard_inline}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.</dd> + <dt>{{domxref("Window.name")}}</dt> + <dd>Gets/sets the name of the window.</dd> + <dt>{{domxref("Window.navigator")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the navigator object.</dd> + <dt>{{domxref("Window.opener")}}</dt> + <dd>Returns a reference to the window that opened this current window.</dd> + <dt>{{domxref("Window.orientation")}} {{non-standard_inline}} {{deprecated_inline}} {{readOnlyInline}}</dt> + <dd>Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.</dd> + <dt>{{domxref("Window.outerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the outside of the browser window.</dd> + <dt>{{domxref("Window.outerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the outside of the browser window.</dd> + <dt>{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollX")}}.</dd> + <dt>{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollY")}}</dd> + <dt>{{domxref("Window.parent")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the parent of the current window or subframe.</dd> + <dt>{{domxref("Window.performance")}} {{readOnlyInline}}</dt> + <dd>Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing <a href="/en-US/docs/Navigation_timing">performance-related</a> data. See also <a href="/en-US/docs/Web/API/Navigation_timing_API/Using_Navigation_Timing">Using Navigation Timing</a> for additional information and examples.</dd> + <dt>{{domxref("Window.personalbar")}} {{readOnlyInline}}</dt> + <dd>Returns the personalbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}</dt> + <dd>Formerly provided access to install and remove PKCS11 modules.</dd> + <dt>{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}</dt> + <dd>The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.</dd> + <dt>{{domxref("Window.screen")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the screen object associated with the window.</dd> + <dt>{{domxref("Window.screenX")}} and {{domxref("Window.screenLeft")}} {{readOnlyInline}}</dt> + <dd>Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.</dd> + <dt>{{domxref("Window.screenY")}} and {{domxref("Window.screenTop")}} {{readOnlyInline}}</dt> + <dd>Both properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen.</dd> + <dt>{{domxref("Window.scrollbars")}} {{readOnlyInline}}</dt> + <dd>Returns the scrollbars object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.scrollMaxX")}} {{non-standard_inline}} {{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.</dd> + <dt>{{domxref("Window.scrollMaxY")}} {{non-standard_inline}} {{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).</dd> + <dt>{{domxref("Window.scrollX")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled horizontally.</dd> + <dt>{{domxref("Window.scrollY")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled vertically.</dd> + <dt>{{domxref("Window.self")}} {{ReadOnlyInline}}</dt> + <dd>Returns an object reference to the window object itself.</dd> + <dt>{{domxref("Window.sessionStorage")}}</dt> + <dd>Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("Window.sidebar")}} {{non-standard_inline}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the window object of the sidebar.</dd> + <dt>{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}</dt> + <dd>Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using <a href="/en-US/docs/Web/API/Web_Speech_API">Web Speech API</a> speech synthesis functionality.</dd> + <dt>{{domxref("Window.status")}}</dt> + <dd>Gets/sets the text in the statusbar at the bottom of the browser.</dd> + <dt>{{domxref("Window.statusbar")}} {{readOnlyInline}}</dt> + <dd>Returns the statusbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.toolbar")}} {{readOnlyInline}}</dt> + <dd>Returns the toolbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.top")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the topmost window in the window hierarchy. This property is read only.</dd> + <dt>{{domxref("Window.visualViewport")}} {{readOnlyInline}}</dt> + <dd>Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.</dd> + <dt>{{domxref("Window.window")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the current window.</dd> + <dt><code>window[0]</code>, <code>window[1]</code>, etc.</dt> + <dd>Returns a reference to the <code>window</code> object in the frames. See {{domxref("Window.frames")}} for more details.</dd> +</dl> + +<h3 id="Properties_implemented_from_elsewhere">Properties implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}</dt> + <dd>Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}</dt> + <dd>Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}</dt> + <dd>Returns a boolean indicating whether the current context is secure (<code>true</code>) or not (<code>false</code>).</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}</dt> + <dd>Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("Window.alert()")}}</dt> + <dd>Displays an alert dialog.</dd> + <dt>{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves back one in the window history. This method is obsolete; you should instead use {{domxref("History.back", "window.history.back()")}}.</dd> + <dt>{{domxref("Window.blur()")}}</dt> + <dd>Sets focus away from the window.</dd> + <dt>{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}</dt> + <dd>Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.</dd> + <dt>{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}</dt> + <dd>Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.</dd> + <dt>{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}</dt> + <dd>Registers the window to capture all events of the specified type.</dd> + <dt>{{domxref("Window.clearImmediate()")}}</dt> + <dd>Cancels the repeated execution set using <code>setImmediate</code>.</dd> + <dt>{{domxref("Window.close()")}}</dt> + <dd>Closes the current window.</dd> + <dt>{{domxref("Window.confirm()")}}</dt> + <dd>Displays a dialog with a message that the user needs to respond to.</dd> + <dt>{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.dispatchEvent()")}}</dt> + <dd>Used to trigger an event.</dd> + <dt>{{domxref("Window.dump()")}} {{Non-standard_inline}}</dt> + <dd>Writes a message to the console.</dd> + <dt>{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.find()")}}</dt> + <dd>Searches for a given string in a window.</dd> + <dt>{{domxref("Window.focus()")}}</dt> + <dd>Sets focus on the current window.</dd> + <dt>{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves the window one document forward in the history. This method is obsolete; you should instead use {{domxref("History.forward", "window.history.forward()")}}.</dd> + <dt>{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Flashes the application icon.</dd> + <dt>{{domxref("Window.getAttentionWithCycleCount()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.getComputedStyle()")}}</dt> + <dd>Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.</dd> + <dt>{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}</dt> + <dd>Gets default computed style for the specified element, ignoring author stylesheets.</dd> + <dt>{{domxref("Window.getSelection()")}}</dt> + <dd>Returns the selection object representing the selected item(s).</dd> + <dt>{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns the browser to the home page.</dd> + <dt>{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.</dd> + <dt>{{domxref("Window.maximize()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.minimize()")}} (top-level XUL windows only)</dt> + <dd>Minimizes the window.</dd> + <dt>{{domxref("Window.moveBy()")}}</dt> + <dd>Moves the current window by a specified amount.</dd> + <dt>{{domxref("Window.moveTo()")}}</dt> + <dd>Moves the window to the specified coordinates.</dd> + <dt>{{domxref("Window.open()")}}</dt> + <dd>Opens a new window.</dd> + <dt>{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Opens a new dialog window.</dd> + <dt>{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}</dt> + <dd>Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.</dd> + <dt>{{domxref("Window.print()")}}</dt> + <dd>Opens the Print Dialog to print the current document.</dd> + <dt>{{domxref("Window.prompt()")}}</dt> + <dd>Returns the text entered by the user in a prompt dialog.</dd> + <dt>{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>Releases the window from trapping events of a specific type.</dd> + <dt>{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.</dd> + <dt>{{domxref("Window.requestIdleCallback()")}} {{experimental_inline}}</dt> + <dd>Enables the scheduling of tasks during a browser's idle periods.</dd> + <dt>{{domxref("Window.resizeBy()")}}</dt> + <dd>Resizes the current window by a certain amount.</dd> + <dt>{{domxref("Window.resizeTo()")}}</dt> + <dd>Dynamically resizes window.</dd> + <dt>{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.scroll()")}}</dt> + <dd>Scrolls the window to a particular place in the document.</dd> + <dt>{{domxref("Window.scrollBy()")}}</dt> + <dd>Scrolls the document in the window by the given amount.</dd> + <dt>{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}</dt> + <dd>Scrolls the document by the given number of lines.</dd> + <dt>{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}</dt> + <dd>Scrolls the current document by the specified number of pages.</dd> + <dt>{{domxref("Window.scrollTo()")}}</dt> + <dd>Scrolls to a particular set of coordinates in the document.</dd> + <dt>{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)</dt> + <dd>Changes the cursor for the current window</dd> + <dt>{{domxref("Window.setImmediate()")}}</dt> + <dd>Executes a function after the browser has finished other heavy tasks</dd> + <dt>{{domxref("Window.setResizable()")}} {{Non-standard_inline}}</dt> + <dd>Toggles a user's ability to resize a window.</dd> + <dt>{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}</dt> + <dd>Sizes the window according to its content.</dd> + <dt>{{domxref("Window.stop()")}}</dt> + <dd>This method stops window loading.</dd> + <dt>{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}</dt> + <dd>Updates the state of commands of the current chrome window (UI).</dd> +</dl> + +<h3 id="Methods_implemented_from_elsewhere">Methods implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("EventTarget.addEventListener()")}}</dt> + <dd>Register an event handler to a specific event type on the window.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.atob()")}}</dt> + <dd>Decodes a string of data which has been encoded using base-64 encoding.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.btoa()")}}</dt> + <dd>Creates a base-64 encoded ASCII string from a string of binary data.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}</dt> + <dd>Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}</dt> + <dd>Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at <em>(sx, sy)</em> with width sw, and height sh.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.fetch()")}}</dt> + <dd>Starts the process of fetching a resource from the network.</dd> + <dt>{{domxref("EventTarget.removeEventListener")}}</dt> + <dd>Removes an event listener from the window.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}</dt> + <dd>Schedules a function to execute every time a given number of milliseconds elapses.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}</dt> + <dd>Schedules a function to execute in a given amount of time.</dd> +</dl> + +<h3 id="Obsolete_methods">Obsolete methods</h3> + +<dl> + <dt>{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}</dt> + <dd>Displays a modal dialog. <strong>This method was removed completely in Chrome 43, and Firefox 55.</strong></dd> +</dl> + +<h2 id="Event_handlers">Event handlers</h2> + +<p>These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.</p> + +<p><em>This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.</em></p> + +<div class="note"> +<p><strong>Note:</strong> Starting in {{Gecko("9.0")}}, you can now use the syntax <code>if ("onabort" in window)</code> to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See <a href="/en-US/docs/DOM/DOM_event_handlers">DOM event handlers</a> for details.</p> +</div> + +<dl> + <dt>{{domxref("Window.onappinstalled")}}</dt> + <dd>Called when the page is installed as a webapp. See {{event('appinstalled')}} event.</dd> + <dt>{{domxref("Window.onbeforeinstallprompt")}}</dt> + <dd>An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.</dd> + <dt>{{domxref("Window.ondevicelight")}}</dt> + <dd>An event handler property for any ambient light levels changes</dd> + <dt>{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Called if accelerometer detects a change (For mobile devices)</dd> + <dt>{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Called when the orientation is changed (For mobile devices)</dd> + <dt>{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only</dt> + <dd>An event handler property for any device orientation changes.</dd> + <dt>{{domxref("Window.ondeviceproximity")}}</dt> + <dd>An event handler property for device proximity event</dd> + <dt>{{domxref("Window.ongamepadconnected")}}</dt> + <dd>Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).</dd> + <dt>{{domxref("Window.ongamepaddisconnected")}}</dt> + <dd>Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).</dd> + <dt>{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>An event handler property for the <code>MozBeforePaint</code> event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.</dd> + <dt>{{domxref("Window.onpaint")}}</dt> + <dd>An event handler property for paint events on the window.</dd> + <dt>{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}</dt> + <dd>An event handler for handled {{jsxref("Promise")}} rejection events.</dd> + <dt>{{domxref("Window.onuserproximity")}}</dt> + <dd>An event handler property for user proximity events.</dd> + <dt>{{domxref("Window.onvrdisplayconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaydisconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplayactivate")}}</dt> + <dd>Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.</dd> + <dt>{{domxref("Window.onvrdisplaydeactivate")}}</dt> + <dd>Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.</dd> + <dt>{{domxref("Window.onvrdisplayblur")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.</dd> + <dt>{{domxref("Window.onvrdisplayfocus")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaypresentchange")}}</dt> + <dd>represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).</dd> +</dl> + +<h3 id="Event_handlers_implemented_from_elsewhere">Event handlers implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("GlobalEventHandlers.onabort")}}</dt> + <dd>Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress</dd> + <dt>{{domxref("WindowEventHandlers.onafterprint")}}</dt> + <dd>Called when the print dialog box is closed. See {{event("afterprint")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeprint")}}</dt> + <dd>Called when the print dialog box is opened. See {{event("beforeprint")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeunload")}}</dt> + <dd>An event handler property for before-unload events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onblur")}}</dt> + <dd>Called after the window loses focus, such as due to a popup.</dd> + <dt>{{domxref("GlobalEventHandlers.onchange")}}</dt> + <dd>An event handler property for change events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onclick")}}</dt> + <dd>Called after the ANY mouse button is pressed & released</dd> + <dt>{{domxref("GlobalEventHandlers.ondblclick")}}</dt> + <dd>Called when a double click is made with ANY mouse button.</dd> + <dt>{{domxref("GlobalEventHandlers.onclose")}}</dt> + <dd>Called after the window is closed</dd> + <dt>{{domxref("GlobalEventHandlers.oncontextmenu")}}</dt> + <dd>Called when the RIGHT mouse button is pressed</dd> + <dt>{{domxref("GlobalEventHandlers.onerror")}}</dt> + <dd>Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onfocus")}}</dt> + <dd>Called after the window receives or regains focus. See {{event("focus")}} events.</dd> + <dt>{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.</dd> + <dt>{{domxref("GlobalEventHandlers.oninput")}}</dt> + <dd>Called when the value of an <input> element changes</dd> + <dt>{{domxref("GlobalEventHandlers.onkeydown")}}</dt> + <dd>Called when you begin pressing ANY key. See {{event("keydown")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeypress")}}</dt> + <dd>Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeyup")}}</dt> + <dd>Called when you finish releasing ANY key. See {{event("keyup")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onlanguagechange")}}</dt> + <dd>An event handler property for {{event("languagechange")}} events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onload")}}</dt> + <dd>Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.</dd> + <dt>{{domxref("WindowEventHandlers.onmessage")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousedown")}}</dt> + <dd>Called when ANY mouse button is pressed.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousemove")}}</dt> + <dd>Called continously when the mouse is moved inside the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseout")}}</dt> + <dd>Called when the pointer leaves the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseover")}}</dt> + <dd>Called when the pointer enters the window</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseup")}}</dt> + <dd>Called when ANY mouse button is released</dd> + <dt>{{domxref("WindowEventHandlers.onoffline")}}</dt> + <dd>Called when network connection is lost. See {{event("offline")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.ononline")}}</dt> + <dd>Called when network connection is established. See {{event("online")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpagehide")}}</dt> + <dd>Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpageshow")}}</dt> + <dd>Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Called when a back button is pressed.</dd> + <dt>{{domxref("GlobalEventHandlers.onreset")}}</dt> + <dd>Called when a form is reset</dd> + <dt>{{domxref("GlobalEventHandlers.onresize")}}</dt> + <dd>Called continuously as you are resizing the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onscroll")}}</dt> + <dd>Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked</dd> + <dt>{{domxref("GlobalEventHandlers.onwheel")}}</dt> + <dd>Called when the mouse wheel is rotated around any axis</dd> + <dt>{{domxref("GlobalEventHandlers.onselect")}}</dt> + <dd>Called after text in an input field is selected</dd> + <dt>{{domxref("GlobalEventHandlers.onselectionchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onstorage")}}</dt> + <dd>Called when there is a change in session storage or local storage. See {{event("storage")}} event</dd> + <dt>{{domxref("GlobalEventHandlers.onsubmit")}}</dt> + <dd>Called when a form is submitted</dd> + <dt>{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}</dt> + <dd>An event handler for unhandled {{jsxref("Promise")}} rejection events.</dd> + <dt>{{domxref("WindowEventHandlers.onunload")}}</dt> + <dd>Called when the user navigates away from the page.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<p>Listen to these events using <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code> or by assigning an event listener to the <code>on<em>eventname</em></code> property of this interface.</p> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/error_event">error</a></code></dt> + <dd>Fired when when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.<br> + Also available via the {{domxref("GlobalEventHandlers/onerror", "onerror")}} property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/languagechange_event">languagechange</a></code></dt> + <dd>Fired at the global scope object when the user's preferred language changes.<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onlanguagechange">onlanguagechange</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/orientationchange_event">orientationchange</a></code></dt> + <dd>Fired when the orientation of the device has changed.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onorientationchange">onorientationchange</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/devicemotion_event">devicemotion</a></code></dt> + <dd>Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/deviceorientation_event">deviceorientation</a></code></dt> + <dd>Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.</dd> + <dt><code>{{domxref("Document/defaultView/resize_event", "resize")}}</code></dt> + <dd>Fired when the window has been resized.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onresize">onresize</a></code> property.</dd> + <dt><code>{{domxref("Document/defaultView/storage_event", "storage")}}</code></dt> + <dd>Fired when a storage area (<code>localStorage</code> or <code>sessionStorage</code>) has been modified in the context of another document.<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onstorage">onstorage</a></code> property.</dd> +</dl> + +<h3 id="Animation_events">Animation events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/animationcancel_event">animationcancel</a></code></dt> + <dd>Fired when an animation unexpectedly aborts.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationcancel">onanimationcancel</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/animationend_event">animationend</a></code></dt> + <dd>Fired when an animation has completed normally.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationend">onanimationend</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/animationiteration_event">animationiteration</a></code></dt> + <dd>Fired when an animation iteration has completed.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationiteration">onanimationiteration</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/animationstart_event">animationstart</a></code></dt> + <dd>Fired when an animation starts.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onanimationstart">onanimationstart</a></code> property.</dd> +</dl> + +<h3 id="Clipboard_events">Clipboard events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/clipboardchange_event">clipboardchange</a></code></dt> + <dd>Fired when the system clipboard content changes.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/copy_event">copy</a></code></dt> + <dd>Fired when the user initiates a copy action through the browser's user interface.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncopy"><code>oncopy</code></a> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/cut_event">cut</a></code></dt> + <dd>Fired when the user initiates a cut action through the browser's user interface.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncut"><code>oncut</code></a> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/paste_event">paste</a></code></dt> + <dd>Fired when the user initiates a paste action through the browser's user interface.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/onpaste"><code>onpaste</code></a> property.</dd> +</dl> + +<h3 id="Connection_events">Connection events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/offline_event">offline</a></code></dt> + <dd>Fired when the browser has lost access to the network and the value of <code>navigator.onLine</code> has switched to <code>false</code>.<br> + Also available via the {{domxref("WindowEventHandlers.onoffline", "onoffline")}} property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/online_event">online </a></code></dt> + <dd>Fired when the browser has gained access to the network and the value of <code>navigator.onLine</code> has switched to <code>true</code>.<br> + Also available via the {{domxref("WindowEventHandlers.ononline", "ononline")}} property.</dd> +</dl> + +<h3 id="Focus_events">Focus events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/blur_event">blur</a></code></dt> + <dd>Fired when an element has lost focus.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onblur"><code>onblur</code></a> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/focus_event">focus</a></code></dt> + <dd>Fired when an element has gained focus.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onfocus"><code>onfocus</code></a> property</dd> +</dl> + +<h3 id="Gamepad_events">Gamepad events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/gamepadconnected_event">gamepadconnected</a></code></dt> + <dd>Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/ongamepadconnected">ongamepadconnected</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/gamepaddisconnected_event">gamepaddisconnected</a></code></dt> + <dd>Fired when the browser detects that a gamepad has been disconnected.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/ongamepaddisconnected">ongamepaddisconnected</a></code> property</dd> +</dl> + +<h3 id="History_events">History events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/hashchange_event">hashchange</a></code></dt> + <dd>Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the <code>#</code> symbol).<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onhashchange">onhashchange</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/pagehide_event">pagehide</a></code></dt> + <dd>Sent when the browser hides the current document while in the process of switching to displaying in its palce a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.<br> + Also available through the <code><a href="/en-US/docs/Mozilla/Tech/XUL/Attribute/onpagehide">onpagehide</a></code> event handler property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/pageshow_event">pageshow</a></code></dt> + <dd>Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.<br> + Also available using the <code><a href="/en-US/docs/Mozilla/Tech/XUL/Attribute/onpageshow">onpageshow</a></code> event handler property.</dd> + <dt><code>{{domxref("Document/defaultView/popstate_event", "popstate")}}</code></dt> + <dd>Fired when the active history entry changes.<br> + Also available using the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onpopstate">onpopstate</a></code> event handler property.</dd> +</dl> + +<h3 id="Load_unload_events">Load & unload events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/beforeunload_event">beforeunload</a></code></dt> + <dd>Fired when the window, the document and its resources are about to be unloaded.<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload">onbeforeunload</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/DOMContentLoaded_event">DOMContentLoaded</a></code></dt> + <dd>Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/load_event">load</a></code></dt> + <dd>Fired when the whole page has loaded, including all dependent resources such as stylesheets images.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onload">onload</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/unload_event">unload</a></code></dt> + <dd>Fired when the document or a child resource is being unloaded.<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onunload">onunload</a></code> property.</dd> +</dl> + +<h3 id="Manifest_events">Manifest events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/appinstalled_event">appinstalled</a></code></dt> + <dd>Fired when the browser has successfully installed a page as an application.<br> + Also available via the <a href="/en-US/docs/Web/API/Window/onappinstalled">onappinstalled</a> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/beforeinstallprompt_event">beforeinstallprompt</a></code></dt> + <dd>Fired when a user is about to be prompted to install a web application.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onbeforeinstallprompt">onbeforeinstallprompt</a></code> property.</dd> +</dl> + +<h3 id="Messaging_events">Messaging events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/message_event">message</a></code></dt> + <dd>Fired when the window receives a message, for example from a call to <code><a href="/en-US/docs/Web/API/Window/postMessage">Window.postMessage()</a></code> from another browsing context.<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onmessage">onmessage</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/messageerror_event">messageerror</a></code></dt> + <dd>Fired when a <code>Window</code> object receives a message that can't be deserialized.<br> + Also available via the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onmessageerror">onmessageerror</a></code> property.</dd> +</dl> + +<h3 id="Print_events">Print events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/afterprint_event">afterprint</a></code></dt> + <dd>Fired after the associated document has started printing or the print preview has been closed.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onafterprint"><code>onafterprint</code></a> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/beforeprint_event">beforeprint</a></code></dt> + <dd>Fired when the associated document is about to be printed or previewed for printing.<br> + Also available via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprint"><code>onbeforeprint</code></a> property.</dd> +</dl> + +<h3 id="Promise_rejection_events">Promise rejection events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/rejectionhandled_event">rejectionhandled</a></code></dt> + <dd>Sent every time a JavaScript {{jsxref("Promise")}} is rejected, regardless of whether or not there is a handler in place to catch the rejection.<br> + Also available through the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onrejectionhandled">onrejectionhandled</a></code> event handler property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/unhandledrejection_event">unhandledrejection</a></code></dt> + <dd>Sent when a JavaScript {{jsxref("Promise")}} is rejected but there is no handler in place to catch the rejection.<br> + Also available using the <code><a href="/en-US/docs/Web/API/WindowEventHandlers/onunhandledrejection">onunhandledrejection</a></code> event handler property.</dd> +</dl> + +<h3 id="Transition_events">Transition events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/transitioncancel_event">transitioncancel</a></code></dt> + <dd>Fired when a <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> is canceled.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/ontransitioncancel">ontransitioncancel</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/transitionend_event">transitionend</a></code></dt> + <dd>Fired when a <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> has completed.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/ontransitionend">ontransitionend</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/transitionrun_event">transitionrun</a></code></dt> + <dd>Fired when a <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> is first created.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/ontransitionrun">ontransitionrun</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/transitionstart_event">transitionstart</a></code></dt> + <dd>Fired when a <a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions">CSS transition</a> has actually started.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/ontransitionstart">ontransitionstart</a></code> property.</dd> +</dl> + +<h3 id="WebVR_events">WebVR events</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplayactivate_event">vrdisplayactivate</a></code></dt> + <dd>Fired when a VR display becomes available to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplayactivate">onvrdisplayactivate</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplayblur_event">vrdisplayblur</a></code></dt> + <dd>Fired when presentation to a VR display has been paused for some reason by the browser, OS, or VR hardware.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplayblur">onvrdisplayblur</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplayconnect_event">vrdisplayconnect</a></code></dt> + <dd>Fired when a compatible VR display is connected to the computer.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplayconnect">onvrdisplayconnect</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplaydeactivate_event">vrdisplaydeactivate</a></code></dt> + <dd>Fired when a VR display can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplaydeactivate">onvrdisplaydeactivate</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplaydisconnect_event">vrdisplaydisconnect</a></code></dt> + <dd>Fired when a compatible VR display is disconnected from the computer.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplaydisconnect">onvrdisplaydisconnect</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplayfocus_event">vrdisplayfocus</a></code></dt> + <dd>Fired when presentation to a VR display has resumed after being blurred.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplayfocus">onvrdisplayfocus</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplaypresentchange_event">vrdisplaypresentchange</a></code></dt> + <dd>fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplaypresentchange">onvrdisplaypresentchange</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplaypointerrestricted_event">vrdisplaypointerrestricted</a></code></dt> + <dd>Fired when the VR display's pointer input is restricted to consumption via a <a href="/en-US/docs/Web/API/Pointer_Lock_API">pointerlocked element</a>.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplaypointerrestricted">onvrdisplaypointerrestricted</a></code> property.</dd> + <dt><code><a href="/en-US/docs/Web/API/Window/vrdisplaypointerunrestricted_event">vrdisplaypointerunrestricted</a></code></dt> + <dd>Fired when the VR display's pointer input is no longer restricted to consumption via a <a href="/en-US/docs/Web/API/Pointer_Lock_API">pointerlocked element</a>.<br> + Also available via the <code><a href="/en-US/docs/Web/API/Window/onvrdisplaypointerunrestricted">onvrdisplaypointerunrestricted</a></code> property.</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<p>See <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Reference</a></p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Window")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Working_with_windows_in_chrome_code">Working with windows in chrome code</a></li> +</ul> diff --git a/files/vi/web/api/window/prompt/index.html b/files/vi/web/api/window/prompt/index.html new file mode 100644 index 0000000000..9830f0cb7c --- /dev/null +++ b/files/vi/web/api/window/prompt/index.html @@ -0,0 +1,86 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +<div>{{ApiRef("Window")}}</div> + +<p>Câu lệnh <code>Window.prompt()</code> hiển thị một cửa sổ yêu cầu người dùng nhập liệu vào.</p> + +<h2 id="Syntax" name="Syntax">Cú pháp</h2> + +<pre class="syntaxbox"><em>result</em> = window.prompt(<em>message</em>, <em>default</em>); +</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>Là một dòng thông báo hiện ra cho người dùng xem. Có thể bỏ trống không cần nhập.</dd> + <dt><code>default</code> {{optional_inline}}</dt> + <dd>Là giá trị mặc định hiển thị ở khung nhập liệu. Lưu ý nếu bạn dùng Internet Explorer 7 hoặc 8, nếu không cung cấp tham số này, thì giá trị mặc định sẽ là <code>"undefined"</code></dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Trả về chuỗi text hoặc <code>null</code>.</p> + +<h2 id="Example" name="Example">Example</h2> + +<pre class="brush: js">let sign = prompt("What's your sign?"); + +if (sign.toLowerCase() == "scorpio") { + alert("Wow! I'm a Scorpio too!"); +} + +// Có nhiều cách để sử dụng prompt() +sign = window.prompt(); // open the blank prompt window +sign = prompt(); // open the blank prompt window +sign = window.prompt('Are you feeling lucky'); // open the window with Text "Are you feeling lucky" +sign = window.prompt('Are you feeling lucky', 'sure'); // open the window with Text "Are you feeling lucky" and default value "sure"</pre> + +<p>Khi người dùng ấn OK, giá trị họ nhập vào sẽ là giá trị trả về ở dạng chuỗi text. Nếu họ nhấn OK mà chưa nhập gì thì sẽ trả về chuỗi rỗng. Và nếu họ bấm Cancel thì sẽ trả về <code>null</code>.</p> + +<p>Giao diện cửa sổ prompt (trình duyệt Chrome trên OS X):</p> + +<p><a href="https://mdn.mozillademos.org/files/11303/prompt.png"><img alt="prompt() dialog in Chrome on OS X" src="https://mdn.mozillademos.org/files/11303/prompt.png" style="height: 298px; width: 535px;"></a></p> + +<h2 id="Notes" name="Notes">Các lưu ý</h2> + +<p>Cửa sổ prompt chứa 1 textbox một dòng, 1 nút OK và 1 nút Cancel, và trả về giá trị người dùng nhập vào (có thể rỗng).</p> + +<p><span class="comment">The following text is shared between this article, DOM:window.confirm and DOM:window.alert</span> Dialog boxes are modal windows; chúng sẽ ngăn người dùng truy cập vào các nội dung khác của website cho đến khi hoàn thành thao tác với cửa sổ prompt. Chính vì vậy, bạn không nên lạm dụng nó quá mức.</p> + +<p>Giá trị trả về là chuỗi text, vì vậy nếu bạn muốn chắc chắn đó là kiểu Number thì hãy ép kiểu nó như ví dụ bên dưới:</p> + +<pre class="brush: js">const aNumber = Number(window.prompt("Type a number", ""));</pre> + +<h2 id="Specification" name="Specification">Specification</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-prompt', 'prompt()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Browser Compatibility</h2> + + + +<p>{{Compat("api.Window.prompt")}}</p> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li>{{domxref("window.alert", "alert")}}</li> + <li>{{domxref("window.confirm", "confirm")}}</li> +</ul> diff --git a/files/vi/web/css/-ms-scroll-snap-points-y/index.html b/files/vi/web/css/-ms-scroll-snap-points-y/index.html new file mode 100644 index 0000000000..2fb27bbef7 --- /dev/null +++ b/files/vi/web/css/-ms-scroll-snap-points-y/index.html @@ -0,0 +1,89 @@ +--- +title: '-ms-scroll-snap-points-y' +slug: Web/CSS/-ms-scroll-snap-points-y +translation_of: Archive/Web/CSS/-ms-scroll-snap-points-y +--- +<div>{{CSSRef}}</div> + +<div>{{non-standard_header}}</div> + +<div> </div> + +<p>The <strong><code>-ms-scroll-snap-points-y</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> property is a <a href="/en-US/docs/Web/CSS/Microsoft_CSS_extensions">Microsoft extension</a> that specifies where snap-points will be located along the y-axis.</p> + +<p>{{cssinfo}}</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<h3 id="Values" name="Values">Values</h3> + +<div class="note"> +<p>Note: a <code><length-percentage></code> is a value that can be either a {{cssxref("<length>")}} or a {{cssxref("<percentaqe>")}}.</p> +</div> + +<dl> + <dt><code>snapInterval( <length-percentage>, <length-percentage> )</code></dt> + <dd> + <p>Specifies a starting snap-point followed by the interval between all snap-points.</p> + + <ul> + <li>The first value specifies where the first snap-point will be placed.</li> + <li>The second value specifies the distance between subsequent snap-points both above and below the initial snap-point.</li> + </ul> + </dd> + <dt><code>snapList( <length-percentage># )</code></dt> + <dd> + <p>Specifies the position of individual snap-points as a comma-separated list of values, each of which represents a zoom factor.</p> + + <ul> + <li>If any value is less than {{CSSXref("-ms-scroll-limit-y-min")}} , then {{cssxref("-ms-scroll-limit-y-min")}} is used.</li> + <li>If any value is greater than {{CSSXref("-ms-scroll-limit-y-max")}}, then {{cssxref("-ms-scroll-limit-y-max")}} is used.</li> + </ul> + </dd> +</dl> + +<h3 id="Formal_syntax" name="Formal_syntax">Formal syntax</h3> + +<pre class="syntaxbox"> {{csssyntax}} +</pre> + +<h2 id="Examples" name="Examples">Examples</h2> + +<p>This example demonstrates both types of values for the <code>-ms-scroll-snap-points-y</code> property. In the first selector, the first snap-point is at 0%, and the interval is set to 100%. In the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. (The <code>-ms-scroll-snap-points-y</code> property behaves identically to the {{cssxref("-ms-scroll-snap-points-x")}} property, but along the y-axis.)</p> + +<pre class="brush: css">.container { + overflow-x: auto; + overflow-y: hidden; + -ms-scroll-snap-type: mandatory; + -ms-scroll-snap-points-y: snapInterval(0%, 100%); + width: 480px; + height: 270px; +} + +.imageContainer { + -ms-scroll-chaining: chained; + -ms-overflow-style: none; + -ms-content-zooming: zoom; + -ms-scroll-rails: none; + -ms-scroll-limit-y-min: 100%; + -ms-scroll-limit-y-max: 500%; + -ms-scroll-snap-type: proximity; + -ms-scroll-snap-points-y: snapList(100%, 200%, 300%, 400%, 500%); + -ms-overflow-style: none; + width: 480px; + height: 270px; + overflow: auto; +} +</pre> + +<h2 id="Specifications" name="Specifications">Specifications</h2> + +<p>Not part of any specification.</p> + +<h2 id="Remarks" name="Remarks">Remarks</h2> + +<p>This property requires Windows 8 or later.</p> + +<p>This property has no effect on non-scrollable elements.</p> + +<p>Starting with Windows 8.1, this property is also supported for mouse, keyboard, and touchpad interaction.</p> diff --git a/files/vi/web/css/_colon_first-child/index.html b/files/vi/web/css/_colon_first-child/index.html new file mode 100644 index 0000000000..b02b008f18 --- /dev/null +++ b/files/vi/web/css/_colon_first-child/index.html @@ -0,0 +1,127 @@ +--- +title: ':first-child' +slug: 'Web/CSS/:first-child' +translation_of: 'Web/CSS/:first-child' +--- +<div>{{CSSRef}}</div> + +<p><strong><code>:first-child</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> <a href="/en-US/docs/Web/CSS/Pseudo-classes">pseudo-class</a> đại diện cho phần tử đầu tiên trong số các phần tử anh chị em của nó.</p> + +<pre class="brush: css no-line-numbers">/* Chọn thẻ <p> đầu tiên trong số các thẻ anh chị em của nó*/ +p:first-child { + color: lime; +}</pre> + +<div class="note"> +<p><strong>Note</strong>: As originally defined, the selected element had to have a parent. Beginning with Selectors Level 4, this is no longer required.</p> +</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">{{csssyntax}} +</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Ví_dụ_đơn_giản">Ví dụ đơn giản</h3> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><div> + <p>This text is selected!</p> + <p>This text isn't selected.</p> +</div> + +<div> + <h2>This text isn't selected: it's not a `p`.</h2> + <p>This text isn't selected.</p> +</div> +</pre> + +<h4 id="CSS">CSS</h4> + +<pre class="brush: css">p:first-child { + color: lime; + background-color: black; + padding: 5px; +} +</pre> + +<h4 id="Kết_quả">Kết quả</h4> + +<p><span>{{EmbedLiveSample('Basic_example', 500, 200)}}</span></p> + +<h3 id="Styling_một_danh_sách">Styling một danh sách</h3> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush: html"><ul> + <li>Item 1</li> + <li>Item 2</li> + <li>Item 3 + <ul> + <li>Item 3.1</li> + <li>Item 3.2</li> + <li>Item 3.3</li> + </ul> + </li> +</ul></pre> + +<h4 id="CSS_2">CSS</h4> + +<pre class="brush: css">ul li { + color: blue; +} + +ul li:first-child { + color: red; + font-weight: bold; +}</pre> + +<h4 id="Result">Result</h4> + +<p>{{EmbedLiveSample('Styling_a_list')}}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS4 Selectors', '#first-child-pseudo', ':first-child')}}</td> + <td>{{Spec2('CSS4 Selectors')}}</td> + <td>Matching elements are not required to have a parent.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Selectors', '#first-child-pseudo', ':first-child')}}</td> + <td>{{Spec2('CSS3 Selectors')}}</td> + <td>No change.</td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'selector.html#first-child', ':first-child')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_của_trình_duyệt">Khả năng tương thích của trình duyệt</h2> + + + +<p>{{Compat("css.selectors.first-child")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{CSSxRef(":-moz-first-node")}} {{Non-standard_Inline}}</li> + <li>{{CSSxRef(":first-of-type")}}</li> + <li>{{CSSxRef(":last-child")}}</li> + <li>{{CSSxRef(":nth-child")}}</li> +</ul> diff --git a/files/vi/web/css/_colon_focus-within/index.html b/files/vi/web/css/_colon_focus-within/index.html new file mode 100644 index 0000000000..3c39e176fa --- /dev/null +++ b/files/vi/web/css/_colon_focus-within/index.html @@ -0,0 +1,88 @@ +--- +title: ':focus-within' +slug: 'Web/CSS/:focus-within' +translation_of: 'Web/CSS/:focus-within' +--- +<div>{{CSSRef}}</div> + +<p><a href="/en-US/docs/Web/CSS/Pseudo-classes">Lớp giả</a> <a href="/en-US/docs/Web/CSS">CSS</a> <strong><code>:focus-within</code></strong> đại diện cho thành phần nhận focus hoặc <em>chứa </em>một thành phần nhận focus. Nói cách khác, nó đại diện cho một thành phần mà chính nó khớp bởi một lớp giả {{cssxref(":focus")}} hoặc có một hậu duệ (con cháu) được khớp bởi <code>:focus</code>. (Gồm cả hậu duệ trong <a href="/en-US/docs/Web/Web_Components/Shadow_DOM">shadow trees</a>.)</p> + +<pre><code>/* Chọn một <div> khi hậu duệ của nó được focus */</code> +div:focus-within { + background: cyan; +}</pre> + +<p>Nó rất hữu dụng, ví dụ chung, để làm nổi bật toàn bộ container {{htmlElement("form")}} khi người dùng focus vào một trong các field {{htmlElement("input")}} của nó.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<p>Trong ví dụ này, form sẽ nhận kiểu màu đặc biệt khi text input nhận focus.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p>Try typing into this form.</p> + +<form> + <label for="given_name">Given Name:</label> + <input id="given_name" type="text"> + <br> + <label for="family_name">Family Name:</label> + <input id="family_name" type="text"> +</form></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">form { + border: 1px solid; + color: gray; + padding: 4px; +} + +form:focus-within { + background: #ff8; + color: black; +} + +input { + margin: 4px; +} +</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample("Example", 500, 150)}}</p> + +<h2 id="Chi_tiết">Chi tiết</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Chi tiết</th> + <th scope="col">Tình trạng</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS4 Selectors", "#the-focus-within-pseudo", ":focus-within")}}</td> + <td>{{Spec2("CSS4 Selectors")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_Trình_duyệt">Tương thích Trình duyệt</h2> + + + +<p>{{Compat("css.selectors.focus-within")}}</p> + +<h2 id="Xem_cả">Xem cả</h2> + +<ul> + <li>{{cssxref(":focus")}}</li> +</ul> diff --git a/files/vi/web/css/_colon_focus/index.html b/files/vi/web/css/_colon_focus/index.html new file mode 100644 index 0000000000..c13a30c0d9 --- /dev/null +++ b/files/vi/web/css/_colon_focus/index.html @@ -0,0 +1,96 @@ +--- +title: ':focus' +slug: 'Web/CSS/:focus' +translation_of: 'Web/CSS/:focus' +--- +<div>{{CSSRef}}</div> + +<p><a href="/en-US/docs/Web/CSS/Pseudo-classes" title="Pseudo-classes">Lớp giả </a> <a href="/en-US/docs/Web/CSS">CSS</a> <strong><code>:focus</code></strong> đại diện cho thành phần (như một input form) nhận focus. Nó được kích hoạt khi người dùng kích hoặc tap lên thành phần hoặc chọn nó bằng phím "tab".</p> + +<pre class="brush: css no-line-numbers">/* Chọn bấy kỳ thành phần input nào được focus */ +input:focus { + color: red; +}</pre> + +<div class="note"> +<p><strong>Chú ý: </strong>Lớp giả này chỉ áp dụng với chính thành phần được focus. Sử dụng {{cssxref(":focus-within")}} nếu bạn muốn chọn thành phần <em>chứa</em> một thành phần được focus.</p> +</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><input class="red-input" value="I'll be red when focused."><br> +<input class="blue-input" value="I'll be blue when focused."></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">.red-input:focus { + background: yellow; + color: red; +} + +.blue-input:focus { + background: yellow; + color: blue; +}</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample('Example')}}</p> + +<h2 id="Chi_tiết">Chi tiết</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Chi tiết</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'scripting.html#selector-focus', ':focus')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Defines HTML-specific semantics.</td> + </tr> + <tr> + <td>{{SpecName('CSS4 Selectors', '#focus-pseudo', ':focus')}}</td> + <td>{{Spec2('CSS4 Selectors')}}</td> + <td>No change.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Selectors', '#the-user-action-pseudo-classes-hover-act', ':focus')}}</td> + <td>{{Spec2('CSS3 Selectors')}}</td> + <td>No change.</td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':focus')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("css.selectors.focus")}}</p> +</div> + +<p> </p> + +<div id="compat-mobile"> </div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{cssxref(":focus-within")}}</li> +</ul> diff --git a/files/vi/web/css/_colon_last-of-type/index.html b/files/vi/web/css/_colon_last-of-type/index.html new file mode 100644 index 0000000000..2fad50fb05 --- /dev/null +++ b/files/vi/web/css/_colon_last-of-type/index.html @@ -0,0 +1,130 @@ +--- +title: ':last-of-type' +slug: 'Web/CSS/:last-of-type' +translation_of: 'Web/CSS/:last-of-type' +--- +<div>{{CSSRef}}</div> + +<h2 id="Nội_dung_tóm_tắt">Nội dung tóm tắt</h2> + +<p>Cú pháp <code>:last-of-type</code> (<a href="/en-US/docs/Web/CSS">CSS</a> <a href="/en-US/docs/Web/CSS/Pseudo-classes">pseudo-class</a>) đại diện cho phần tử cuối cùng trong danh sách các phần tử con có chung phần tử cha trong phép chọn css.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">{{csssyntax}} +</pre> + +<h2 id="Example">Example</h2> + +<p>Để chỉ định phần tử cuối cùng bên trong thẻ {{HTMLElement("p")}} , bạn có thể sử dụng cú pháp:</p> + +<pre class="brush: css">p em:last-of-type { + color: lime; +} +</pre> + +<pre class="brush: html"><p> + <em>I'm not lime :(</em> + <strong>I'm not lime :(</strong> + <em>I'm lime :D</em> + <strong>I'm also not lime :(</strong> +</p> + +<p> + <em>I'm not lime :(</em> + <span><em>I am lime!</em></span> + <strong>I'm not lime :(</strong> + <em>I'm lime :D</em> + <span><em>I am also lime!</em> <strike> I'm not lime </strike></span> + <strong>I'm also not lime :(</strong> +</p></pre> + +<p id="...will_result_in.3A">...hết quả trả về:</p> + +<div>{{EmbedLiveSample('Example','100%', '120')}}</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS4 Selectors', '#last-of-type-pseudo', ':last-of-type')}}</td> + <td>{{Spec2('CSS4 Selectors')}}</td> + <td>No change</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Selectors', '#last-of-type-pseudo', ':last-of-type')}}</td> + <td>{{Spec2('CSS3 Selectors')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_(browser)_tương_thích">Trình duyệt (browser) tương thích</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0</td> + <td>9.5</td> + <td>3.2</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>9.0</td> + <td>10.0</td> + <td>3.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{Cssxref(":nth-last-of-type")}}</li> + <li>{{Cssxref(":first-of-type")}}</li> + <li>{{Cssxref(":nth-of-type")}}</li> +</ul> diff --git a/files/vi/web/css/backdrop-filter/index.html b/files/vi/web/css/backdrop-filter/index.html new file mode 100644 index 0000000000..6edf76fb78 --- /dev/null +++ b/files/vi/web/css/backdrop-filter/index.html @@ -0,0 +1,146 @@ +--- +title: backdrop-filter +slug: Web/CSS/backdrop-filter +tags: + - Bố trí + - Bộ lọc SVG + - CSS + - SVG + - Thuộc tính CSS + - Tài liệu tham khảo + - Web + - 'recipe:css-property' + - Đồ họa +translation_of: Web/CSS/backdrop-filter +--- +<div>{{CSSRef}}</div> + +<p>Thuộc tính <a href="/vi/docs/Web/CSS">CSS</a> <strong><code>backdrop-filter</code></strong> cho phép bạn áp dụng các hiệu ứng đồ họa như làm mờ hoặc chuyển màu cho vùng phía sau một phần tử. Bởi vì nó áp dụng cho mọi thứ <em>phía sau</em> phần tử, để xem hiệu ứng, bạn phải làm cho phần tử hoặc nền của nó ít nhất một phần trong suốt.</p> + +<pre class="brush: css no-line-numbers notranslate">/* Giá trị từ khóa */ +backdrop-filter: none; + +/* Bộ lọc URL đến SVG */ +backdrop-filter: url(commonfilters.svg#filter); + +/* Giá trị <filter-function> */ +backdrop-filter: blur(2px); +backdrop-filter: brightness(60%); +backdrop-filter: contrast(40%); +backdrop-filter: drop-shadow(4px 4px 10px blue); +backdrop-filter: grayscale(30%); +backdrop-filter: hue-rotate(120deg); +backdrop-filter: invert(70%); +backdrop-filter: opacity(20%); +backdrop-filter: sepia(90%); +backdrop-filter: saturate(80%); + +/* Nhiều bộ lọc */ +backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%); + +/* Giá trị chung */ +backdrop-filter: inherit; +backdrop-filter: initial; +backdrop-filter: unset; +</pre> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<h3 id="Giá_trị">Giá trị</h3> + +<dl> + <dt><code>none</code></dt> + <dd>Không có bộ lọc nào được áp dụng cho phông nền.</dd> + <dt><code><filter-function-list></code></dt> + <dd>Danh sách được phân tách bằng dấu cách về {{cssxref("<filter-function>")}}s hoặc một <a href="/en-US/docs/Web/SVG/Element/filter">bộ lọc SVG</a> sẽ được áp dụng cho phông nền.</dd> +</dl> + +<h2 id="Định_nghĩa_hình_thức">Định nghĩa hình thức</h2> + +<p>{{cssinfo}}</p> + +<h2 id="Cấu_trúc_hình_thức">Cấu trúc hình thức</h2> + +<pre class="syntaxbox notranslate">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css notranslate">.box { + background-color: rgba(255, 255, 255, 0.3); + border-radius: 5px; + font-family: sans-serif; + text-align: center; + line-height: 1; + -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); + max-width: 50%; + max-height: 50%; + padding: 20px 40px; +} + +html, +body { + height: 100%; + width: 100%; +} + +body { + background-image: url(https://picsum.photos/id/1080/6858/4574), linear-gradient(rgb(219, 166, 166), rgb(0, 0, 172)); + background-position: center center; + background-repeat: no-repeat; + background-size: cover; +} + +.container { + align-items: center; + display: flex; + justify-content: center; + height: 100%; + width: 100%; +}</pre> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><div class="container"> + <div class="box"> + <p>backdrop-filter: blur(10px)</p> + </div> +</div> +</pre> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{EmbedLiveSample("Examples", 600, 400)}}</p> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Filters 2.0', '#BackdropFilterProperty', 'backdrop-filter')}}</td> + <td>{{Spec2('Filters 2.0')}}</td> + <td>Định nghĩa ban đầu.</td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_của_trình_duyệt_web">Tính tương thích của trình duyệt web</h2> + +<div class="hidden">Bảng tương thích trên trang này được tạo từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp vào dữ liệu, vui lòng truy cập <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi một pull request.</div> + +<p>{{Compat("css.properties.backdrop-filter")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{cssxref("filter")}}</li> +</ul> diff --git a/files/vi/web/css/background-color/index.html b/files/vi/web/css/background-color/index.html new file mode 100644 index 0000000000..9cb5bc0330 --- /dev/null +++ b/files/vi/web/css/background-color/index.html @@ -0,0 +1,157 @@ +--- +title: background-color +slug: Web/CSS/background-color +translation_of: Web/CSS/background-color +--- +<div>{{CSSRef}}</div> + +<p>Thuộc tính <a href="/vi/docs/Web/CSS">CSS</a> <strong><code>background-color</code></strong> đặt màu nền của một phần tử.</p> + +<div>{{EmbedInteractiveExample("pages/css/background-color.html")}}</div> + +<p class="hidden">Nguồn cho ví dụ tương tác này được lưu trữ trong kho lưu trữ GitHub. Nếu bạn muốn đóng góp vào dự án ví dụ tương tác, vui lòng sao chép <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="brush: css no-line-numbers notranslate">/* Giá trị từ khóa */ +background-color: red; +background-color: indigo; + +/* Giá trị Hex (Thập lục phân) */ +background-color: #bbff00; /* Hoàn toàn mờ đục */ +background-color: #bf0; /* Fully opaque shorthand */ +background-color: #11ffee00; /* Hoàn toàn trong suốt */ +background-color: #1fe0; /* Fully transparent shorthand */ +background-color: #11ffeeff; /* Hoàn toàn mờ đục */ +background-color: #1fef; /* Fully opaque shorthand */ + +/* Giá trị RGB */ +background-color: rgb(255, 255, 128); /* Hoàn toàn mờ đục */ +background-color: rgba(117, 190, 218, 0.5); /* Trong suốt 50% */ + +/* Giá trị HSL */ +background-color: hsl(50, 33%, 25%); /* Hoàn toàn mờ đục */ +background-color: hsla(50, 33%, 25%, 0.75); /* Trong suốt 75% */ + +/* Giá trị từ khóa đặc biệt */ +background-color: currentcolor; +background-color: transparent; + +/* Giá trị chung */ +background-color: inherit; +background-color: initial; +background-color: unset;</pre> + +<p>Thuộc tính <code>background-color</code> được chỉ định là một giá trị <code><a href="#<color>"><color></a></code>.</p> + +<h3 id="Giá_trị">Giá trị</h3> + +<dl> + <dt><a id="<color>"></a>{{cssxref("<color>")}}</dt> + <dd>Màu đồng nhất của nền. Nó được hiển thị đằng sau bất kỳ {{cssxref("background-image")}} được chỉ định, mặc dù màu sẽ vẫn hiển thị qua bất kỳ độ trong suốt nào của hình ảnh.</dd> +</dl> + +<h2 id="Mối_quan_tâm_về_khả_năng_tiếp_cận">Mối quan tâm về khả năng tiếp cận</h2> + +<p>Điều quan trọng là phải đảm bảo rằng tỷ lệ tương phản giữa màu nền và màu của văn bản được đặt trên nó đủ cao để những người gặp tình trạng thị lực kém có thể đọc được nội dung của trang.</p> + +<p>Tỷ lệ tương phản màu được xác định bằng cách so sánh độ chói của văn bản và giá trị màu nền. Để xem <a href="https://www.w3.org/WAI/intro/wcag">Web Content Accessibility Guidelines (WCAG)</a> hiện tại, tỷ lệ 4,5:1 là bắt buộc đối với nội dung văn bản và 3:1 đối với văn bản to, chẳng hạn như tiêu đề. Văn bản to được định nghĩa là 18,66px và <a href="/vi/docs/Web/CSS/font-weight">đậm</a> hoặc lớn hơn, hoặc 24px hoặc lớn hơn.</p> + +<ul> + <li><a href="https://webaim.org/resources/contrastchecker/">WebAIM: Color Contrast Checker</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#Guideline_1.4_Make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background">MDN Understanding WCAG, Guideline 1.4 explanations</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html">Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0</a></li> +</ul> + +<h2 id="Định_nghĩa_hình_thức">Định nghĩa hình thức</h2> + +<p>{{cssinfo}}</p> + +<h2 id="Cú_pháp_hình_thức">Cú pháp hình thức</h2> + +<pre class="syntaxbox notranslate">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><div class="exampleone"> + Lorem ipsum dolor sit amet, consectetuer +</div> + +<div class="exampletwo"> + Lorem ipsum dolor sit amet, consectetuer +</div> + +<div class="examplethree"> + Lorem ipsum dolor sit amet, consectetuer +</div></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css; highlight:[2,7,12]; notranslate">.exampleone { + background-color: teal; + color: white; +} + +.exampletwo { + background-color: rgb(153,102,153); + color: rgb(255,255,204); +} + +.examplethree { + background-color: #777799; + color: #FFFFFF; +} +</pre> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{EmbedLiveSample("Examples", 200, 150)}}</p> + +<ul> +</ul> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Ghi chú</th> + <th scope="col">Phản hồi</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Backgrounds', '#background-color', 'background-color')}}</td> + <td>Though technically removing the <code>transparent</code> keyword, this doesn't change anything as it has been incorporated as a true {{cssxref("<color>")}}</td> + <td><a href="https://github.com/w3c/csswg-drafts/labels/css-backgrounds-3">Backgrounds Level 3 GitHub issues</a></td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color')}}</td> + <td></td> + <td></td> + </tr> + <tr> + <td>{{SpecName('CSS1', '#background-color', 'background-color')}}</td> + <td>Initial definition</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_của_trình_duyệt_web">Tính tương thích của trình duyệt web</h2> + +<p class="hidden">Bảng tương thích trong trang này được tạo từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp vào dữ liệu, vui lòng xem <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi một pull request.</p> + +<p>{{Compat("css.properties.background-color")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds">Multiple backgrounds</a></li> + <li>Kiểu dữ liệu của {{cssxref("<color>")}}</li> + <li>Các thuộc tính khác liên quan đến màu sắc: {{cssxref("color")}}, {{cssxref("border-color")}}, {{cssxref("outline-color")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-emphasis-color")}}, {{cssxref("text-shadow")}}, {{cssxref("caret-color")}}, and {{cssxref("column-rule-color")}}</li> + <li><a href="/en-US/docs/Web/HTML/Applying_color">Applying color to HTML elements using CSS</a></li> +</ul> diff --git a/files/vi/web/css/content/index.html b/files/vi/web/css/content/index.html new file mode 100644 index 0000000000..188f634136 --- /dev/null +++ b/files/vi/web/css/content/index.html @@ -0,0 +1,296 @@ +--- +title: content +slug: Web/CSS/content +translation_of: Web/CSS/content +--- +<div>{{CSSRef}}</div> + +<p class="summary">The <strong><code>content</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> property replaces an element with a generated value. Objects inserted using the <code>content</code> property are <strong>anonymous <a href="/en-US/docs/Web/CSS/Replaced_element">replaced elements</a></strong><em>.</em></p> + +<pre class="brush:css no-line-numbers notranslate">/* Keywords that cannot be combined with other values */ +content: normal; +content: none; + +/* <a href="/en-US/docs/Web/CSS/image"><image></a> values */ +content: url("http://www.example.com/test.png"); +content: linear-gradient(#e66465, #9198e5); + +/* alt text for generated content, added in the Level 3 specification */ +content: url("http://www.example.com/test.png") / "This is the alt text"; + +/* values below can only be applied to generated content using ::before and ::after */ + +/* <string> value */ +content: "prefix"; + +/* <a href="/en-US/docs/Web/CSS/counter"><counter></a> values, optionally with <a href="/en-US/docs/Web/CSS/list-style-type"><list-style-type> </a>*/ +content: counter(chapter_counter); +content: counter(chapter_counter, upper-roman); +content: counters(section_counter, "."); +content: counters(section_counter, ".", <code>decimal-leading-zero</code>); + +/* <a href="/en-US/docs/Web/CSS/attr">attr()</a> value linked to the HTML attribute value */ +content: attr(value string); + +/* Language- and position-dependent keywords */ +content: open-quote; +content: close-quote; +content: no-open-quote; +content: no-close-quote; + +/* Except for normal and none, several values can be used simultaneously */ +content: open-quote chapter_counter; + +/* Global values */ +content: inherit; +content: initial; +content: unset; +</pre> + +<h2 id="Syntax">Syntax</h2> + +<h3 id="Values">Values</h3> + +<dl> + <dt><code>none</code></dt> + <dd>The pseudo-element is not generated.</dd> + <dt><code>normal</code></dt> + <dd>Computes to <code>none</code> for the <code>::before</code> and <code>::after</code> pseudo-elements.</dd> + <dt>{{cssxref("<string>")}}</dt> + <dd>Specifies the "alt text" for the element. This value can be any number of text characters. Non-Latin characters must be encoded using their Unicode escape sequences: for example, <code>\000A9</code> represents the copyright symbol.</dd> + <dt>{{cssxref("<image>")}}</dt> + <dd>An {{cssxref("<image>")}}, denoted by the {{cssxref("<url>")}} or {{cssxref("<gradient>")}} data type, or part of the webpage, defined by the {{cssxref("element", "element()")}} function, denoting the content to display.</dd> + <dt>{{cssxref("<counter>")}}</dt> + <dd>The value of a <a href="/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters">CSS counter</a>, generally a number produced by computations defined by {{cssxref("<counter-reset>")}} and {{cssxref("<counter-increment>")}} properies. It can be displayed using either the {{cssxref("counter")}} or {{cssxref("counters")}} function.</dd> + <dd> + <p>The {{cssxref("counter")}} function has two forms: 'counter(<var>name</var>)' or 'counter(<var>name</var>, style)'. The generated text is the value of the innermost counter of the given name in scope at the given pseudo-element. It is formatted in the specified {{cssxref("<list-style-type>")}} (<code>decimal</code> by default).</p> + + <p>The {{cssxref("counters")}} function also has two forms: 'counters(<var>name</var>, <var>string</var>)' or 'counters(<var>name</var>, <var>string</var>, <var>style</var>)'. The generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. The counters are rendered in the indicated {{cssxref("<list-style-type>")}} (<code>decimal</code> by default).</p> + </dd> + <dt><code>attr(x)</code></dt> + <dd>The value of the element's attribute <code>x</code> as a string. If there is no attribute <code>x</code>, an empty string is returned. The case-sensitivity of attribute names depends on the document language.</dd> + <dt><code>open-quote</code> | <code>close-quote</code></dt> + <dd>These values are replaced by the appropriate string from the {{cssxref("quotes")}} property.</dd> + <dt><code>no-open-quote</code> | <code>no-close-quote</code></dt> + <dd>Introduces no content, but increments (decrements) the level of nesting for quotes.</dd> +</dl> + +<h2 id="Accessibility_concerns">Accessibility concerns</h2> + +<p>CSS-generated content is not included in the <a href="/en-US/docs/Web/API/Document_Object_Model/Introduction">DOM</a>. Because of this, it will not be represented in the <a href="/en-US/docs/Learn/Accessibility/What_is_accessibility#Accessibility_APIs">accessibility tree</a> and certain assistive technology/browser combinations will not announce it. If the content conveys information that is critical to understanding the page's purpose, it is better to include it in the main document.</p> + +<ul> + <li><a href="https://tink.uk/accessibility-support-for-css-generated-content/">Accessibility support for CSS generated content – Tink</a></li> + <li><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#Guideline_1.3_%E2%80%94_Create_content_that_can_be_presented_in_different_ways">Explanation of WCAG, Guideline 1.3 – MDN</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html">Understanding Success Criterion 1.3.1 | W3C Understanding WCAG 2.0</a></li> +</ul> + +<h2 id="Formal_definition">Formal definition</h2> + +<p>{{cssinfo}}</p> + +<h2 id="Formal_syntax">Formal syntax</h2> + +<pre class="syntaxbox notranslate">{{csssyntax}}</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Headings_and_quotes">Headings and quotes</h3> + +<p>This example inserts quotation marks around quotes, and adds the word "Chapter" before headings.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html notranslate"><h1>5</h1> +<p>According to Sir Tim Berners-Lee, + <q cite="http://www.w3.org/People/Berners-Lee/FAQ.html#Internet">I was + lucky enough to invent the Web at the time when the Internet + already existed - and had for a decade and a half.</q> + We must understand that there is nothing fundamentally wrong + with building on the contributions of others. +</p> + +<h1>6</h1> +<p>According to the Mozilla Manifesto, + <q cite="http://www.mozilla.org/en-US/about/manifesto/">Individuals + must have the ability to shape the Internet and + their own experiences on the Internet.</q> + Therefore, we can infer that contributing to the open web + can protect our own individual experiences on it. +</p></pre> + +<h4 id="CSS">CSS</h4> + +<pre class="brush: css notranslate">q { + color: blue; +} + +q::before { + content: open-quote; +} + +q::after { + content: close-quote; +} + +h1::before { + content: "Chapter "; /* The trailing space creates separation + between the added content and the + rest of the content */ +}</pre> + +<h4 id="Result">Result</h4> + +<p>{{EmbedLiveSample('Headings_and_quotes', '100%', 200)}}</p> + +<h3 id="Image_combined_with_text">Image combined with text</h3> + +<p>This example inserts an image before the link. If the image is not found, it inserts text instead.</p> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush: html notranslate"><a href="http://www.mozilla.org/en-US/">Mozilla Home Page</a></pre> + +<h4 id="CSS_2">CSS</h4> + +<pre class="brush: css notranslate">a::before { + content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") / " MOZILLA: "; + font: x-small Arial, sans-serif; + color: gray; +}</pre> + +<h4 id="Result_2">Result</h4> + +<p>{{EmbedLiveSample('Image_combined_with_text', '100%', 60)}}</p> + +<h3 id="Targeting_classes">Targeting classes</h3> + +<p>This example inserts additional text after special items in a list.</p> + +<h4 id="HTML_3">HTML</h4> + +<pre class="brush: html notranslate"><h2>Paperback Best Sellers</h2> +<ol> + <li>Political Thriller</li> + <li class="new-entry">Halloween Stories</li> + <li>My Biography</li> + <li class="new-entry">Vampire Romance</li> +</ol></pre> + +<h4 id="CSS_3">CSS</h4> + +<pre class="brush: css notranslate">.new-entry::after { + content: " New!"; /* The leading space creates separation + between the added content and the + rest of the content */ + color: red; +}</pre> + +<h4 id="Result_3">Result</h4> + +<p>{{EmbedLiveSample('Targeting_classes', '100%', 160)}}</p> + +<h3 id="Images_and_element_attributes">Images and element attributes</h3> + +<p>This example inserts an image before each link, and adds its <code>id</code> attribute after.</p> + +<h4 id="HTML_4">HTML</h4> + +<pre class="brush: html notranslate"><ul> + <li><a id="moz" href="http://www.mozilla.org/"> + Mozilla Home Page</a></li> + <li><a id="mdn" href="https://developer.mozilla.org/"> + Mozilla Developer Network</a></li> +</ul></pre> + +<h4 id="CSS_4">CSS</h4> + +<pre class="brush: css notranslate">a { + text-decoration: none; + border-bottom: 3px dotted navy; +} + +a::after { + content: " (" attr(id) ")"; +} + +#moz::before { + content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico"); +} + +#mdn::before { + content: url("https://mdn.mozillademos.org/files/7691/mdn-favicon16.png"); +} + +li { + margin: 1em; +} +</pre> + +<h4 id="Result_4">Result</h4> + +<p>{{EmbedLiveSample('Images_and_element_attributes', '100%', 160)}}</p> + +<h3 id="Element_replacement">Element replacement</h3> + +<p>This example replaces an element's content with an image. You can replace the contents of an element with either a {{cssxref("<url>")}} or an {{cssxref("<image>")}} value. Content added with <code>::before</code> or <code>::after</code> will not be generated as the contents of the element have been replaced.</p> + +<h4 id="HTML_5">HTML</h4> + +<pre class="brush: html notranslate"><div id="replaced">Mozilla</div> +</pre> + +<h4 id="CSS_5">CSS</h4> + +<pre class="brush: css notranslate">#replaced { + content: url("https://mdn.mozillademos.org/files/12668/MDN.svg"); +} + +#replaced::after { /* will not show if element replacement is supported */ + content: " (" attr(id) ")"; +}</pre> + +<h4 id="Result_5">Result</h4> + +<p>{{EmbedLiveSample('Element_replacement', '100%', 200)}}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS3 Content", "#content-property", "content")}}</td> + <td>{{Spec2("CSS3 Content")}}</td> + <td>Adds support for alt-text</td> + </tr> + <tr> + <td>{{SpecName("CSS2.1", "generate.html#content", "content")}}</td> + <td>{{Spec2("CSS2.1")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("css.properties.content")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Replaced_element">Replaced elements</a></li> + <li>{{Cssxref("::after")}}</li> + <li>{{Cssxref("::before")}}</li> + <li>{{Cssxref("::marker")}}</li> + <li>{{Cssxref("quotes")}}</li> + <li>{{cssxref("url()", "url()")}} function</li> +</ul> diff --git a/files/vi/web/css/css_box_alignment/index.html b/files/vi/web/css/css_box_alignment/index.html new file mode 100644 index 0000000000..c3014fee65 --- /dev/null +++ b/files/vi/web/css/css_box_alignment/index.html @@ -0,0 +1,245 @@ +--- +title: CSS Box Alignment +slug: Web/CSS/CSS_Box_Alignment +translation_of: Web/CSS/CSS_Box_Alignment +--- +<div><font><font>{{CSSRef}}</font></font></div> + +<p class="summary"><font><font>Mô-đun sắp xếp hộp CSS chỉ định các tính năng CSS liên quan đến căn chỉnh các hộp trong các mô hình bố trí hộp CSS khác nhau: bố trí khối, bố cục bảng, bố cục flex và bố cục lưới. </font><font>Mô-đun này nhằm mục đích tạo ra một phương thức liên kết nhất quán trên tất cả CSS. </font><font>Tài liệu này nêu chi tiết các khái niệm chung được tìm thấy trong đặc tả.</font></font></p> + +<div class="note"> +<p><strong><font><font>Lưu ý</font></font></strong><font><font> : Tài liệu cho từng phương pháp bố cục sẽ nêu chi tiết cách áp dụng Sắp xếp hộp ở đó.</font></font></p> +</div> + +<h2 id="Phương_thức_căn_chỉnh_cũ_hơn"><font><font>Phương thức căn chỉnh cũ hơn</font></font></h2> + +<p><font><font>CSS theo truyền thống có khả năng liên kết rất hạn chế. </font><font>Chúng tôi đã có thể căn chỉnh văn bản bằng cách sử dụng {{cssxref ("text-align")}}, các khối trung tâm sử dụng tự động {{cssxref ("margin")}} s và trong bảng hoặc khối nội tuyến bằng cách sử dụng {{cssxref ( thuộc tính "vertical-align")}}. </font><font>Việc căn chỉnh văn bản hiện được bao phủ bởi các </font><font>mô-đun </font><a href="https://www.w3.org/TR/css-text-3/"><font>Văn bản </font></a></font><a href="https://www.w3.org/TR/css-inline-3/"><font><font>Nội tuyến</font></font></a><font><font> và </font></font><a href="https://www.w3.org/TR/css-text-3/"><font><font>CSS</font></font></a><font><font> , và lần đầu tiên trong Căn chỉnh Hộp, chúng tôi có khả năng căn chỉnh ngang và dọc hoàn toàn.</font></font></p> + +<p><font><font>Nếu ban đầu bạn học </font></font><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout"><font><font>Flexbox</font></font></a><font><font> thì bạn có thể xem xét các thuộc tính này là một phần của đặc tả Flexbox, và một số thuộc tính thực sự được liệt kê trong Cấp 1 của Flexbox. </font><font>Tuy nhiên, đặc điểm kỹ thuật lưu ý rằng đặc tả của Alignment Box nên được nhắc đến vì nó có thể bổ sung thêm các khả năng so với những gì hiện có trong Flexbox.</font></font></p> + +<h2 id="Ví_dụ_cơ_bản"><font><font>Ví dụ cơ bản</font></font></h2> + +<p><font><font>Các ví dụ sau đây minh họa cách một số Thuộc tính sắp xếp hộp được áp dụng trong </font></font><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout"><font><font>Grid</font></font></a><font><font> và </font></font><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout"><font><font>Flexbox</font></font></a><font><font> .</font></font></p> + +<h3 id="Ví_dụ_căn_chỉnh_bố_cục_lưới_CSS"><font><font>Ví dụ căn chỉnh bố cục lưới CSS</font></font></h3> + +<p><font><font>Trong ví dụ này bằng cách sử dụng Grid Layout, có thêm không gian trong vùng chứa lưới sau khi đặt các bản nhạc có chiều rộng cố định trên trục nội tuyến (chính). </font><font>Không gian này được phân phối bằng {{cssxref ("justify-content")}}. </font><font>Trên trục (chéo), sự liên kết của các mục bên trong vùng lưới của chúng được điều khiển bằng {{cssxref ("align-items")}}. </font><font>Mục đầu tiên ghi đè </font></font><code>align-items</code><font><font>giá trị được đặt trên nhóm bằng cách đặt {{cssxref ("align-self")}} thành </font></font><code>center</code><font><font>.</font></font></p> + +<p><font><font>{{EmbedGHLiveSample ("css-example / box-alignment / overview / grid-align-items.html", '100%', 500)}}</font></font></p> + +<h3 id="Ví_dụ_liên_kết_Flexbox"><font><font>Ví dụ liên kết Flexbox</font></font></h3> + +<p><font><font>Trong ví dụ này, ba mục flex được căn chỉnh trên trục chính sử dụng </font></font><code>justify-content</code><font><font>và trên Trục chéo sử dụng </font></font><code>align-items</code><font><font>. </font><font>Mục đầu tiên ghi đè </font></font><code>align-items</code><font><font>tập hợp trên nhóm bằng cách đặt </font></font><code>align-self</code><font><font>thành </font></font><code>center</code><font><font>.</font></font></p> + +<p><font><font>{{EmbedGHLiveSample ("css-example / box-alignment / overview / flex-align-items.html", '100%', 500)}}</font></font></p> + +<h2 id="Khái_niệm_và_thuật_ngữ_chính"><font><font>Khái niệm và thuật ngữ chính</font></font></h2> + +<p><font><font>Đặc tả chi tiết một số thuật ngữ liên kết để giúp dễ dàng thảo luận các thuộc tính căn chỉnh bên ngoài việc thực hiện chúng trong một phương pháp bố cục cụ thể. </font><font>Ngoài ra còn có một số khái niệm chính được phổ biến cho tất cả các phương pháp bố trí.</font></font></p> + +<h3 id="Mối_quan_hệ_với_chế_độ_viết"><font><font>Mối quan hệ với chế độ viết</font></font></h3> + +<p><font><font>Sự liên kết được liên kết với các chế độ viết trong đó khi chúng ta căn chỉnh một mục, chúng ta không xem xét liệu chúng ta đang căn chỉnh nó với các kích thước vật lý của trên cùng, bên phải, phía dưới và bên trái. </font><font>Thay vào đó, chúng tôi mô tả sự liên kết về mặt bắt đầu và kết thúc của thứ nguyên cụ thể mà chúng tôi đang làm việc. </font><font>Điều này đảm bảo rằng liên kết hoạt động theo cùng một cách mà bất kỳ chế độ ghi nào của tài liệu.</font></font></p> + +<h3 id="Hai_kích_thước_căn_chỉnh"><font><font>Hai kích thước căn chỉnh</font></font></h3> + +<p><font><font>Khi sử dụng các thuộc tính căn chỉnh hộp, bạn sẽ căn chỉnh nội dung trên một trong hai trục - trục nội tuyến (hoặc trục chính) và trục khối (hoặc chéo). </font><font>Trục nội tuyến là trục dọc theo đó các từ trong dòng câu trong chế độ viết đang được sử dụng - cho tiếng Anh, ví dụ, trục nội tuyến nằm ngang. </font><font>Trục khối là trục dọc theo đó các khối, chẳng hạn như các phần tử đoạn, được đặt ra và nó chạy trên trục Inline.</font></font></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15952/two-axes.png"><img alt="" src="https://mdn.mozillademos.org/files/15952/two-axes.png" style="height: 260px; width: 480px;"></p> + +<p><font><font>Khi căn chỉnh các mục trên trục nội tuyến, bạn sẽ sử dụng các thuộc tính bắt đầu bằng </font></font><code>justify-</code><font><font>:</font></font></p> + +<ul> + <li><font><font>{{cssxref ("justify-items")}}</font></font></li> + <li><font><font>{{cssxref ("biện minh")}}</font></font></li> + <li><font><font>{{cssxref ("justify-content")}}</font></font></li> +</ul> + +<p><font><font>Khi căn chỉnh các mục trên trục khối, bạn sẽ sử dụng các thuộc tính bắt đầu </font></font><code>align-</code><font><font>:</font></font></p> + +<ul> + <li><font><font>{{cssxref ("align-items")}}</font></font></li> + <li><font><font>{{cssxref ("căn chỉnh")}}</font></font></li> + <li><font><font>{{cssxref ("căn chỉnh nội dung")}}</font></font></li> +</ul> + +<p><font><font>Flexbox bổ sung thêm một biến chứng trong đó ở trên là đúng khi {{cssxref ("flex-direction")}} được đặt thành </font></font><code>row</code><font><font>. </font><font>Các thuộc tính được hoán đổi khi flexbox được đặt thành </font></font><code>column</code><font><font>. </font><font>Vì vậy, khi làm việc với flexbox, bạn sẽ dễ dàng nghĩ về trục chính và trục chéo hơn là nội tuyến và khối. </font><font>Các </font></font><code>justify-</code><font><font>thuộc tính luôn được sử dụng để căn chỉnh trên trục chính, các </font></font><code>align-</code><font><font>thuộc tính trên trục chéo.</font></font></p> + +<h3 id="Chủ_thể_căn_chỉnh"><font><font>Chủ thể căn chỉnh</font></font></h3> + +<p><font><font>Các </font></font><strong><font><font>chủ đề liên kết</font></font></strong><font><font> là điều đang được liên kết. </font><font>Đối với </font></font><code>justify-self</code><font><font>hoặc </font></font><code>align-self</code><font><font>, hoặc khi thiết lập các giá trị này dưới dạng một nhóm có </font></font><code>justify-items</code><font><font>hoặc </font></font><code>align-items</code><font><font>, đây sẽ là hộp lề của phần tử mà thuộc tính này đang được sử dụng. </font><font>Các </font><font>thuộc tính </font></font><code>justify-content</code><font><font>và </font></font><code>align-content</code><font><font>khác nhau theo phương thức bố cục.</font></font></p> + +<h3 id="Container_liên_kết"><font><font>Container liên kết</font></font></h3> + +<p><font><font>Các </font></font><strong><font><font>thùng chứa liên kết</font></font></strong><font><font> là hộp đề tài này đã được liên kết bên trong. </font><font>Điều này thường sẽ là khối chứa của đối tượng căn chỉnh. </font><font>Vùng chứa liên kết có thể chứa một hoặc nhiều đối tượng căn chỉnh.</font></font></p> + +<p><font><font>Hình ảnh dưới đây cho thấy một container liên kết với hai đối tượng căn chỉnh bên trong.</font></font></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15953/align-container-subjects.png" style="height: 170px; width: 248px;"></p> + +<h3 id="Căn_chỉnh_dự_phòng"><font><font>Căn chỉnh dự phòng</font></font></h3> + +<p><font><font>Nếu bạn đặt căn chỉnh không thể hoàn thành, thì </font></font><strong><font><font>căn chỉnh dự phòng</font></font></strong><font><font> sẽ đi vào hoạt động và đối phó với không gian có sẵn. </font><font>Liên kết dự phòng này được chỉ định riêng cho từng phương thức bố cục và được trình bày chi tiết trên trang cho phương thức đó.</font></font></p> + +<h2 id="Các_loại_căn_chỉnh"><font><font>Các loại căn chỉnh</font></font></h2> + +<p><font><font>Có ba loại căn chỉnh khác nhau mà chi tiết đặc điểm kỹ thuật; </font><font>các giá trị từ khóa này sử dụng.</font></font></p> + +<ul> + <li><strong><font><font>Căn chỉnh vị trí</font></font></strong><font><font> : xác định vị trí của đối tượng căn chỉnh có liên quan đến vùng chứa căn chỉnh của nó.</font></font></li> + <li><strong><font><font>Căn chỉnh đường cơ sở</font></font></strong><font><font> : Các từ khóa này xác định căn chỉnh là mối quan hệ giữa các đường cơ sở của nhiều đối tượng căn chỉnh trong một ngữ cảnh căn chỉnh.</font></font></li> + <li><strong><font><font>Căn chỉnh phân phối</font></font></strong><font><font> : Các từ khóa này xác định căn chỉnh là phân bố không gian giữa các đối tượng căn chỉnh.</font></font></li> +</ul> + +<h3 id="Giá_trị_từ_khóa_liên_kết_vị_trí"><font><font>Giá trị từ khóa liên kết vị trí</font></font></h3> + +<p><font><font>Các giá trị sau được định nghĩa cho sự liên kết vị trí, và có thể được sử dụng như giá trị cho sự liên kết nội dung với </font></font><code>justify-content</code><font><font>và </font></font><code>align-content</code><font><font>và còn cho sự liên kết tự với </font></font><code>justify-self</code><font><font>và </font></font><code>align-self</code><font><font>.</font></font></p> + +<ul> + <li><code>center</code></li> + <li><code>start</code></li> + <li><code>end</code></li> + <li><code>self-start</code></li> + <li><code>self-end</code></li> + <li><code>flex-start</code><font><font> chỉ dành cho Flexbox</font></font></li> + <li><code>flex-end</code><font><font> chỉ dành cho Flexbox</font></font></li> + <li><code>left</code></li> + <li><code>right</code></li> +</ul> + +<p><font><font>Khác với các giá trị vật lý </font></font><code>left</code><font><font>và </font></font><code>right</code><font><font>, liên quan đến các thuộc tính vật lý của màn hình, tất cả các giá trị khác là các giá trị logic và liên quan đến chế độ viết của nội dung.</font></font></p> + +<p><font><font>Ví dụ, khi làm việc trong CSS Grid Layout, nếu bạn đang làm việc bằng tiếng Anh và thiết lập </font></font><code>justify-content</code><font><font>để </font></font><code>start</code><font><font>điều này sẽ di chuyển các mục trong kích thước nội tuyến để bắt đầu, mà sẽ được trái như câu trong tiếng Anh bắt đầu ở bên trái. </font><font>Nếu bạn đang sử dụng tiếng Ả Rập, ngôn ngữ từ phải sang trái, thì giá trị tương tự </font></font><code>start</code><font><font>sẽ dẫn đến các mục di chuyển sang phải, như các câu trong tiếng Ả Rập bắt đầu ở phía bên tay phải của trang.</font></font></p> + +<p><font><font>Cả hai ví dụ này đều có </font></font><code>justify-content: start</code><font><font>, tuy nhiên vị trí bắt đầu thay đổi theo chế độ viết.</font></font></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15956/writing-mode-start.png" style="height: 101px; width: 478px;"></p> + +<h3 id="Căn_chỉnh_căn_bản"><font><font>Căn chỉnh căn bản</font></font></h3> + +<p><font><font>Các từ khóa căn chỉnh đường cơ sở được sử dụng để căn chỉnh các đường cơ sở của các hộp trên một nhóm đối tượng căn chỉnh. </font><font>Chúng có thể được sử dụng như giá trị cho sự liên kết nội dung với </font></font><code>justify-content</code><font><font>và </font></font><code>align-content</code><font><font>và còn cho sự liên kết tự với </font></font><code>justify-self</code><font><font>và </font></font><code>align-self</code><font><font>.</font></font></p> + +<ul> + <li><code>baseline</code></li> + <li><code>first baseline</code></li> + <li><code>last baseline</code></li> +</ul> + +<p><font><font>Căn chỉnh nội dung đường cơ sở - chỉ định giá trị căn chỉnh căn bản cho </font></font><code>justify-content</code><font><font>hoặc </font></font><code>align-content</code><font><font>- hoạt động trong các phương thức bố cục để sắp xếp các mục ra theo hàng. </font><font>Các đối tượng căn chỉnh là đường cơ sở được căn chỉnh với nhau bằng cách thêm đệm vào bên trong các hộp.</font></font></p> + +<p><font><font>Căn chỉnh tự căn chỉnh thay đổi các hộp để căn chỉnh theo đường cơ sở bằng cách thêm lề ngoài các hộp. </font><font>Tự căn chỉnh là khi sử dụng </font></font><code>justify-self</code><font><font>hoặc </font></font><code>align-self</code><font><font>, hoặc khi đặt các giá trị này thành một nhóm có </font></font><code>justify-items</code><font><font>và </font></font><code>align-items</code><font><font>.</font></font></p> + +<h3 id="Căn_chỉnh_phân_phối"><font><font>Căn chỉnh phân phối</font></font></h3> + +<p><font><font>Các </font></font><strong><font><font>từ khóa liên kết phân tán</font></font></strong><font><font> được sử dụng với các </font><font>thuộc tính </font></font><code>align-content</code><font><font>và </font></font><code>justify-content</code><font><font>. </font><font>Những từ khóa này xác định những gì sẽ xảy ra với bất kỳ không gian bổ sung nào sau khi đối tượng căn chỉnh được hiển thị. </font><font>Các giá trị như sau:</font></font></p> + +<ul> + <li><code>stretch</code></li> + <li><code>space-between</code></li> + <li><code>space-around</code></li> + <li><code>space-evenly</code></li> +</ul> + +<p><font><font>Ví dụ, trong các mục Flex Layout được căn chỉnh với </font></font><code>flex-start</code><font><font>ban đầu. </font><font>Làm việc ở chế độ viết ngang từ trên xuống dưới như tiếng Anh, </font></font><code>flex-direction</code><font><font>khi </font></font><code>row</code><font><font>các mục bắt đầu ở phía xa bên trái và bất kỳ khoảng trống nào sau khi hiển thị các mục được đặt sau các mục.</font></font></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15954/justify-content-start.png" style="height: 100px; width: 559px;"></p> + +<p><font><font>Nếu bạn đặt </font></font><code>justify-content: space-between</code><font><font>trên thùng chứa flex, không gian có sẵn hiện được chia sẻ và đặt giữa các mục.</font></font></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15955/justify-content-space-between.png" style="height: 100px; width: 559px;"></p> + +<p><font><font>Cần có khoảng trống trong thứ nguyên bạn muốn căn chỉnh các mục để các từ khóa này có hiệu lực. </font><font>Không có không gian, không có gì để phân phối.</font></font></p> + +<h2 id="Căn_chỉnh_tràn"><font><font>Căn chỉnh tràn</font></font></h2> + +<p><font><font>Các </font><font>từ khóa </font></font><code>safe</code><font><font>và </font></font><code>unsafe</code><font><font>từ khóa giúp xác định hành vi khi đối tượng căn chỉnh lớn hơn vùng chứa căn chỉnh. </font><font>Các </font></font><code>safe</code><font><font>từ khóa sẽ sắp xếp để </font></font><code>start</code><font><font>trong trường hợp của một liên kết cụ thể gây ra một tràn, mục đích là để tránh “mất dữ liệu”, nơi một phần của mặt hàng đó nằm ngoài ranh giới của container liên kết và không thể được cuộn để.</font></font></p> + +<p><font><font>Nếu bạn chỉ định </font></font><code>unsafe</code><font><font>sau đó sự liên kết sẽ được tôn trọng ngay cả khi nó sẽ gây ra mất dữ liệu như vậy.</font></font></p> + +<h2 id="Khoảng_cách_giữa_các_hộp"><font><font>Khoảng cách giữa các hộp</font></font></h2> + +<p><font><font>Các đặc điểm kỹ thuật liên kết hộp cũng bao gồm </font></font><code>gap</code><font><font>, </font></font><code>row-gap</code><font><font>và </font></font><code>column-gap</code><font><font>tài sản. </font><font>Các thuộc tính này cho phép thiết lập khoảng cách nhất quán giữa các mục trong một hàng hoặc cột, trong bất kỳ phương thức bố cục nào có các mục được sắp xếp theo cách này.</font></font></p> + +<p><font><font>Tài </font></font><code>gap</code><font><font>sản là một cách viết tắt </font></font><code>row-gap</code><font><font>và </font></font><code>column-gap</code><font><font>cho phép chúng tôi thiết lập các thuộc tính này cùng một lúc:</font></font></p> + +<ul> + <li><font><font>{{cssxref ("hàng-khoảng cách")}}</font></font></li> + <li><font><font>{{cssxref ("khoảng trống cột")}}</font></font></li> + <li><font><font>{{cssxref ("khoảng cách")}}</font></font></li> +</ul> + +<p><font><font>Trong ví dụ dưới đây, bố cục lưới sử dụng </font></font><code>gap</code><font><font>viết tắt để đặt </font></font><code>10px</code><font><font>khoảng cách giữa các bản nhạc hàng và </font></font><code>2em</code><font><font>khoảng cách giữa các bản nhạc cột.</font></font></p> + +<p><font><font>{{EmbedGHLiveSample ("css-example / box-alignment / overview / grid-gap.html", '100%', 500)}}</font></font></p> + +<p><font><font>Trong ví dụ này, tôi đang sử dụng thuộc tính {{cssxref ("grid-gap")}} ngoài {{cssxref ("gap")}}. </font><font>Các thuộc tính khoảng trống ban đầu được bắt đầu bằng </font></font><code>grid-</code><font><font>đặc tả bố cục lưới và một số trình duyệt chỉ hỗ trợ các phiên bản tiền tố này.</font></font></p> + +<ul> + <li><font><font>{{cssxref ("lưới-hàng-khoảng cách")}}</font></font></li> + <li><font><font>{{cssxref ("lưới-cột-khoảng trống")}}</font></font></li> + <li><font><font>{{cssxref ("lưới-khoảng cách")}}</font></font></li> +</ul> + +<p><font><font>Các phiên bản tiền tố sẽ được duy trì như một bí danh của những cái chưa được sửa đổi, tuy nhiên bạn luôn có thể tăng gấp đôi theo cách bạn muốn với tiền tố của nhà cung cấp, thêm thuộc </font></font><code>grid-gap</code><font><font>tính và sau đó thuộc </font></font><code>gap</code><font><font>tính có cùng giá trị.</font></font></p> + +<p><font><font>Ngoài ra, hãy lưu ý rằng những thứ khác có thể làm tăng khoảng cách trực quan được hiển thị, ví dụ bằng cách sử dụng các từ khóa phân phối không gian hoặc thêm các lề vào các mục.</font></font></p> + +<h2 id="Các_trang_chi_tiết_các_thuộc_tính_căn_chỉnh_riêng_lẻ"><font><font>Các trang chi tiết các thuộc tính căn chỉnh riêng lẻ</font></font></h2> + +<p><font><font>Vì các thuộc tính căn chỉnh hộp CSS được thực hiện khác nhau tùy thuộc vào đặc tả mà chúng tương tác, hãy tham khảo các trang sau cho từng loại bố cục để biết chi tiết về cách sử dụng các thuộc tính căn chỉnh với nó:</font></font></p> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Box_Alignment/Box_Alignment_in_Flexbox"><font><font>Sắp xếp hộp trong Flexbox</font></font></a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Box_Alignment/Box_Alignment_In_Grid_Layout"><font><font>Sắp xếp hộp trong Bố cục lưới CSS</font></font></a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Box_Alignment/Box_Alignment_in_Multi-column_Layout"><font><font>Căn chỉnh hộp trong bố cục nhiều cột</font></font></a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Box_Alignment/Box_Alignment_In_Block_Abspos_Tables"><font><font>Sắp xếp hộp cho khối, bố trí hoàn toàn và bố cục bảng</font></font></a></li> +</ul> + +<h2 id="Tài_liệu_tham_khảo"><font><font>Tài liệu tham khảo</font></font></h2> + +<h3 id="Thuộc_tính_CSS"><font><font>Thuộc tính CSS</font></font></h3> + +<div class="index"> +<ul> + <li><font><font>{{cssxref ("justify-content")}}</font></font></li> + <li><font><font>{{cssxref ("căn chỉnh nội dung")}}</font></font></li> + <li><font><font>{{cssxref ("vị trí nội dung")}}</font></font></li> + <li><font><font>{{cssxref ("justify-items")}}</font></font></li> + <li><font><font>{{cssxref ("align-items")}}</font></font></li> + <li><font><font>{{cssxref ("địa điểm")}}</font></font></li> + <li><font><font>{{cssxref ("biện minh")}}</font></font></li> + <li><font><font>{{cssxref ("căn chỉnh")}}</font></font></li> + <li><font><font>{{cssxref ("địa điểm")}}</font></font></li> + <li><font><font>{{cssxref ("hàng-khoảng cách")}}</font></font></li> + <li><font><font>{{cssxref ("khoảng trống cột")}}</font></font></li> + <li><font><font>{{cssxref ("khoảng cách")}}</font></font></li> +</ul> +</div> + +<h3 id="Thuật_ngữ"><font><font>Thuật ngữ</font></font></h3> + +<div class="index"> +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Cross_Axis"><font><font>Trục chéo</font></font></a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Main_Axis"><font><font>Trục chính</font></font></a></li> + <li><a href="/en-US/docs/Glossary/Alignment_Container"><font><font>Container sắp xếp</font></font></a></li> + <li><a href="/en-US/docs/Glossary/Alignment_Subject"><font><font>Chủ đề căn chỉnh</font></font></a></li> + <li><a href="/en-US/docs/Glossary/Fallback_Alignment"><font><font>Căn chỉnh dự phòng</font></font></a></li> +</ul> +</div> + +<h2 id="Hướng_dẫn"><font><font>Hướng dẫn</font></font></h2> + +<ul> + <li><font><font>Hướng dẫn CSS Flexbox: </font></font><em><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox"><font><font>Các khái niệm cơ bản của Flexbox</font></font></a></em></li> + <li><font><font>Hướng dẫn Flexbox CSS: Sắp xếp </font></font><em><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container"><font><font>các mục trong một thùng chứa flex</font></font></a></em></li> + <li><font><font>Hướng dẫn lưới CSS: </font></font><em><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout"><font><font>Sắp xếp hộp trong bố cục lưới CSS</font></font></a></em></li> +</ul> + +<h2 id="Tài_nguyên_bên_ngoài"><font><font>Tài nguyên bên ngoài</font></font></h2> + +<ul> + <li><a href="https://rachelandrew.co.uk/css/cheatsheets/box-alignment"><font><font>Hộp liên kết cheatsheet</font></font></a></li> + <li><a href="https://www.smashingmagazine.com/2016/11/css-grids-flexbox-box-alignment-new-layout-standard/"><font><font>CSS Grid, Flexbox và Box alignment</font></font></a></li> + <li><a href="https://blogs.igalia.com/jfernandez/2017/05/03/can-i-use-css-box-alignment/"><font><font>Suy nghĩ về việc triển khai từng phần của căn chỉnh Hộp</font></font></a></li> +</ul> diff --git a/files/vi/web/css/css_box_model/index.html b/files/vi/web/css/css_box_model/index.html new file mode 100644 index 0000000000..08152c9c16 --- /dev/null +++ b/files/vi/web/css/css_box_model/index.html @@ -0,0 +1,115 @@ +--- +title: CSS Basic Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Box_Model +--- +<div>{{CSSRef}}</div> + +<p><strong>CSS Basic Box Model</strong> is a module of CSS that defines the rectangular boxes—including their padding and margin—that are generated for elements and laid out according to the <a href="/en-US/docs/Web/CSS/Visual_formatting_model">visual formatting model</a>.</p> + +<h2 id="Reference">Reference</h2> + +<h3 id="Properties">Properties</h3> + +<h4 id="Properties_controlling_the_flow_of_content_in_a_box">Properties controlling the flow of content in a box</h4> + +<div class="index"> +<ul> + <li>{{CSSxRef("overflow")}}</li> + <li>{{CSSxRef("overflow-x")}}</li> + <li>{{CSSxRef("overflow-y")}}</li> +</ul> +</div> + +<h4 id="Properties_controlling_the_size_of_a_box">Properties controlling the size of a box</h4> + +<div class="index"> +<ul> + <li>{{CSSxRef("height")}}</li> + <li>{{CSSxRef("width")}}</li> + <li>{{CSSxRef("max-height")}}</li> + <li>{{CSSxRef("max-width")}}</li> + <li>{{CSSxRef("min-height")}}</li> + <li>{{CSSxRef("min-width")}}</li> +</ul> +</div> + +<h4 id="Properties_controlling_the_margins_of_a_box">Properties controlling the margins of a box</h4> + +<div class="index"> +<ul> + <li>{{CSSxRef("margin")}}</li> + <li>{{CSSxRef("margin-bottom")}}</li> + <li>{{CSSxRef("margin-left")}}</li> + <li>{{CSSxRef("margin-right")}}</li> + <li>{{CSSxRef("margin-top")}}</li> + <li>{{CSSxRef("margin-trim")}} {{Experimental_Inline}}</li> +</ul> +</div> + +<h4 id="Properties_controlling_the_paddings_of_a_box">Properties controlling the paddings of a box</h4> + +<div class="index"> +<ul> + <li>{{CSSxRef("padding")}}</li> + <li>{{CSSxRef("padding-bottom")}}</li> + <li>{{CSSxRef("padding-left")}}</li> + <li>{{CSSxRef("padding-right")}}</li> + <li>{{CSSxRef("padding-top")}}</li> +</ul> +</div> + +<h4 id="Other_properties">Other properties</h4> + +<div class="index"> +<ul> + <li>{{CSSxRef("visibility")}}</li> +</ul> +</div> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model">Introduction to the CSS box model</a></dt> + <dd>Explains one of the fundamental concept of CSS: the box model. This model defines how CSS lays out elements, including their content, padding, border, and margin areas.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing">Mastering margin collapsing</a></dt> + <dd>Sometimes, two adjacent margins are collapsed into one. This article describes the rules that govern when and why this happens, and how to control it.</dd> + <dt><a href="/en-US/docs/Web/CSS/Visual_formatting_model">Visual formatting model</a></dt> + <dd>Explains the visual formatting model.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS3 Box")}}</td> + <td>{{Spec2("CSS3 Box")}}</td> + <td>Added <code style="white-space: nowrap;">margin-trim</code></td> + </tr> + <tr> + <td>{{SpecName("CSS2.1", "box.html")}}</td> + <td>{{Spec2("CSS2.1")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS1")}}</td> + <td>{{Spec2("CSS1")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> diff --git a/files/vi/web/css/css_box_model/kien_thuc_co_ban_ve_css_box_model/index.html b/files/vi/web/css/css_box_model/kien_thuc_co_ban_ve_css_box_model/index.html new file mode 100644 index 0000000000..287d709494 --- /dev/null +++ b/files/vi/web/css/css_box_model/kien_thuc_co_ban_ve_css_box_model/index.html @@ -0,0 +1,77 @@ +--- +title: Kiến thức cơ bản về CSS box model +slug: Web/CSS/CSS_Box_Model/Kien_thuc_co_ban_ve_css_box_model +tags: + - CSS + - CSS Box Model + - Layout +translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +--- +<div>{{CSSRef}}</div> + +<p>Khi dựng giao diện của một trang web, theo lý thuyết chuẩn của <strong>CSS box model</strong>, engine của trình duyệt thể hiện các element trên trang web dưới dạng một hình chữ nhật. CSS sẽ giúp định nghĩa các thuộc tính như kích thước, vị trí và các thuộc tính khác (màu sắc, màu nền, kích thước của border...) của các element này.</p> + +<p>Mỗi element được cấu tạo bởi bốn phần (vùng), các phần này được xác định thông qua các cạnh (đường biên) tương ứng: cạnh ngoài vùng nội dung (<em>content edge)</em>, cạnh ngoài vùng padding (<em>padding edge)</em>, cạnh ngoài vùng border (<em>border edge)</em>, và cạnh ngoài vùng margin (<em>margin edge).</em></p> + +<p><img alt="CSS Box model" src="https://mdn.mozillademos.org/files/8685/boxmodel-(3).png" style="height: 384px; width: 548px;"></p> + +<p><strong>Vùng nội dung, </strong>được bọc bởi các cạnh ngoài (<em>content edge</em>), là nơi chứa nội dung chính của element như văn bản, hình ảnh, hoặc video. Các thông số về kích thước của vùng này gồm chiều rộng (<em>content width</em>) và chiều cao (<em>content height</em>). Vùng này thường có cả màu nền hoặc ảnh nền.</p> + +<p>Nếu thuộc tính {{cssxref("box-sizing")}} được gán giá trị <code>content-box</code> (mặc định) và nếu element này có kiểu hiển thị block, thì kích thước của vùng nội dung có thể được định nghĩa bởi các thông số thuộc tính {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, và {{cssxref("max-height")}}.</p> + +<p><strong>Vùng padding</strong>, được bọc bởi các cạnh ngoài (<em>padding edge</em>), bọc lấy bên ngoài vùng nội dung bằng padding của element. Các thông số kích thước của vùng này gồm chiều rộng (<em>padding-box width</em>) và chiều cao (<em>padding-box height</em>).</p> + +<p id="padding-area">Độ dày của padding được xác định dựa trên các thuộc tính {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}, hay viết tắt là {{cssxref("padding")}}.</p> + +<p><strong>Vùng border</strong>, được bọc bởi các cạnh ngoài (border edge), bọc lấy bên ngoài vùng padding bằng border của element. Các thông số kích thước của vùng này gồm chiều rộng (<em>border-box width)</em> và chiều cao (<em>border-box height)</em>;</p> + +<p>Độ dày của border được xác định dựa trên thuộc tính {{cssxref("border-width")}}. Nếu thuộc tính {{cssxref("box-sizing")}} được gán giá trị <code>border-box</code>, thì kích thước của vùng border có thể được định nghĩa bởi các thông số thuộc tính {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, và {{cssxref("max-height")}}. Nếu element có background bằng cách gán thuộc tính ({{cssxref("background-color")}} hoặc {{cssxref("background-image")}}), thì background sẽ tràn ra cả vùng border. Bạn có thể thay đổi trạng thái mặc định này bằng cách sử dụng kèm thuộc tính {{cssxref("background-clip")}}.</p> + +<p><strong>Vùng margin</strong>, được bọc bởi các cạnh ngoài (margn edge), bọc lấy bên ngoài vùng border và tạo ra một vùng trống để giãn cách vị trí của element này với các element khác xung quanh. Các thông số kích thước của vùng này gồm chiều rộng (<em>margin-box width)</em> và chiều cao (<em>margin-box height)</em>;</p> + +<p>Kích thước của vùng margin được xác định dựa trên các thuộc tính {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, {{cssxref("margin-left")}}, hay viết tắt là {{cssxref("margin")}}. Khi có sự xung đột margin xảy ra (<a href="/en/CSS/margin_collapsing" title="en/CSS/margin_collapsing">margin collapsing</a>), sẽ khó xác định chính xác vùng margin của một element vì nó được chia sẻ cho các element với nhau.</p> + +<p>Cuối cùng, lưu ý với một elements với thuộc tính hiển thị là inline (inline element), thì khoảng không gian mà nó chiếm dụng (chiều cao) được xác định bởi thuộc tính {{cssxref('line-height')}}, dù cho nó có các thuộc tính border hay padding thêm vào.</p> + +<h2 id="Tham_khảo_thêm">Tham khảo thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Containing_block">Layout và containing block trong CSS Box Model</a></li> + <li><a href="/en-US/docs/Web/CSS/Cascade">Giới thiệu về CSS Cascade</a></li> + <li><a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance">Cascade và inheritance trong CSS</a></li> +</ul> + +<h2 id="Đặc_tả_kĩ_thuật">Đặc tả kĩ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Đặc tả kĩ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Box', '#intro')}}</td> + <td>{{Spec2('CSS3 Box')}}</td> + <td></td> + </tr> + <tr> + <td>{{ SpecName("CSS2.1","box.html#box-dimensions")}}</td> + <td>{{ Spec2('CSS2.1') }}</td> + <td>Chỉnh sửa từ ngữ chính xác hơn, không có thay đổi gì về quan trọng.</td> + </tr> + <tr> + <td>{{ SpecName("CSS1","#formatting-model")}}</td> + <td>{{ Spec2('CSS1') }}</td> + <td>Các định nghĩa ban đầu.</td> + </tr> + </tbody> +</table> + +<h2 id="Tham_khảo_thêm_2">Tham khảo thêm</h2> + +<ul> + <li>{{css_key_concepts}}</li> +</ul> diff --git a/files/vi/web/css/css_grid_layout/index.html b/files/vi/web/css/css_grid_layout/index.html new file mode 100644 index 0000000000..9869d6b999 --- /dev/null +++ b/files/vi/web/css/css_grid_layout/index.html @@ -0,0 +1,243 @@ +--- +title: CSS Grid Layout +slug: Web/CSS/CSS_Grid_Layout +translation_of: Web/CSS/CSS_Grid_Layout +--- +<p><strong>CSS Grid Layout</strong> chia trang thành các nhiều phần và định hình mối quan hệ giữa các phần dựa trên kích thước, vị trí, và lớp (layer) xây dựng từ HTML nguyên thủy.</p> + +<p>Giống như tables, grid layout cho phép chúng ta sắp xếp các phần thành cột và hàng. Tuy nhiên, đối với nhiều bố cục, việc sử dụng CSS grid sẽ dễ dàng hơn là table. Ví dụ như các phần tử con trong grid có thể chồng chéo lên nhau thành các layer, giống như việc sử dụng cách định hình vị trí của CSS.</p> + +<h2 id="Basic_Example" name="Basic_Example">Ví dụ cơ bản</h2> + +<p>Ví dụ dưới đây sẽ cho bạn thấy một bố cục grid gồm 3 cột có kích thước nhỏ nhất là 100 pixels và kích thước lớn nhất được chỉnh tự động. Các phần được sắp xếp vào grid theo đường thẳng.</p> + +<div id="example"> +<div class="hidden"> +<pre class="brush: css notranslate">* {box-sizing: border-box;} +.wrapper { + max-width: 940px; + margin: 0 auto; +} + +.wrapper > div { + border: 2px solid rgb(233,171,88); + border-radius: 5px; + background-color: rgba(233,171,88,.5); + padding: 1em; + color: #d9480f; +}</pre> +</div> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><div class="wrapper"> + <div class="one">One</div> + <div class="two">Two</div> + <div class="three">Three</div> + <div class="four">Four</div> + <div class="five">Five</div> + <div class="six">Six</div> +</div></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css notranslate">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-gap: 10px; + grid-auto-rows: minmax(100px, auto); +} +.one { + grid-column: 1 / 3; + grid-row: 1; +} +.two { + grid-column: 2 / 4; + grid-row: 1 / 3; +} +.three { + grid-column: 1; + grid-row: 2 / 5; +} +.four { + grid-column: 3; + grid-row: 3; +} +.five { + grid-column: 2; + grid-row: 4; +} +.six { + grid-column: 3; + grid-row: 4; +} +</pre> + +<p>{{ EmbedLiveSample('example', '500', '440') }}</p> +</div> + +<h2 id="Liên_quan">Liên quan</h2> + +<h3 id="Thuộc_tính_CSS">Thuộc tính CSS</h3> + +<div class="index"> +<ul> + <li>{{cssxref("grid-template-columns")}}</li> + <li>{{cssxref("grid-template-rows")}}</li> + <li>{{cssxref("grid-template-areas")}}</li> + <li>{{cssxref("grid-template")}}</li> + <li>{{cssxref("grid-auto-columns")}}</li> + <li>{{cssxref("grid-auto-rows")}}</li> + <li>{{cssxref("grid-auto-flow")}}</li> + <li>{{cssxref("grid")}}</li> + <li>{{cssxref("grid-row-start")}}</li> + <li>{{cssxref("grid-column-start")}}</li> + <li>{{cssxref("grid-row-end")}}</li> + <li>{{cssxref("grid-column-end")}}</li> + <li>{{cssxref("grid-row")}}</li> + <li>{{cssxref("grid-column")}}</li> + <li>{{cssxref("grid-area")}}</li> + <li>{{cssxref("grid-row-gap")}}</li> + <li>{{cssxref("grid-column-gap")}}</li> + <li>{{cssxref("grid-gap")}}</li> +</ul> +</div> + +<h3 id="Chức_năng_CSS">Chức năng CSS</h3> + +<div class="index"> +<ul> + <li>{{cssxref("repeat", "repeat()")}}</li> + <li>{{cssxref("minmax", "minmax()")}}</li> + <li>{{cssxref("fit-content", "fit-content()")}}</li> +</ul> +</div> + +<h3 id="Kiểu_dữ_liệu_CSS">Kiểu dữ liệu CSS</h3> + +<div class="index"> +<ul> + <li>{{cssxref("<flex>")}}</li> +</ul> +</div> + +<h3 id="Glossary_entries">Glossary entries</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Glossary/Grid">Grid</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Lines">Grid Lines</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Tracks">Grid Tracks</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Cell">Grid Cell</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Areas">Grid Area</a></li> + <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Axis">Grid Axis</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Rows">Grid row</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Column">Grid column</a></li> +</ul> +</div> + +<h2 id="Chỉ_dẫn">Chỉ dẫn</h2> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout">Basic concepts of Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship of Grid Layout to other layout methods</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Layout using line-based placement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in CSS Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in CSS Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">CSS Grid, Logical Values and Writing Modes</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and accessibility</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid and progressive enhancement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realising_common_layouts_using_CSS_Grid_">Realising common layouts using CSS Grid</a></li> +</ul> +</div> + +<h2 id="Nguồn_bên_ngoài">Nguồn bên ngoài</h2> + +<ul> + <li><a href="http://labs.jensimmons.com/">Examples from Jen Simmons</a></li> + <li><a href="http://gridbyexample.com/">Grid by Example - a collection of usage examples and video tutorials</a></li> + <li><a href="https://tympanus.net/codrops/css_reference/grid/">Codrops Grid Reference</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts">Firefox DevTools CSS Grid Inspector</a></li> + <li><a href="https://mozilladevelopers.github.io/playground/">CSS Grid Playground</a></li> +</ul> + +<h2 id="Đặc_điểm">Đặc điểm</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Grid') }}</td> + <td>{{ Spec2('CSS3 Grid') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<section class="Quick_links" id="Quick_Links"> +<ol> + <li><a href="/en-US/docs/Web/CSS"><strong>CSS</strong></a></li> + <li><a href="/en-US/docs/Web/CSS/Reference"><strong>CSS Reference</strong></a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a></li> + <li data-default-state="open"><a href="#"><strong>Guides</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout">Basics concepts of grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship to other layout methods</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Line-based placement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">Grids, logical values and writing modes</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and Accessibility</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid Layout and Progressive Enhancement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout">Realizing common layouts using grids</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Properties</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/grid">grid</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-area">grid-area</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-columns">grid-auto-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-flow">grid-auto-flow</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-rows">grid-auto-rows</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column">grid-column</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-end">grid-column-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-gap">grid-column-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-start">grid-column-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-gap">grid-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row">grid-row</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-end">grid-row-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-gap">grid-row-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-start">grid-row-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template">grid-template</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-areas">grid-template-areas</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-columns">grid-template-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-rows">grid-template-rows</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Glossary</strong></a> + <ol> + <li><a href="/en-US/docs/Glossary/Grid">Grid</a></li> + <li><a href="/en-US/docs/Glossary/Grid_lines">Grid lines</a></li> + <li><a href="/en-US/docs/Glossary/Grid_tracks">Grid tracks</a></li> + <li><a href="/en-US/docs/Glossary/Grid_cell">Grid cell</a></li> + <li><a href="/en-US/docs/Glossary/Grid_areas">Grid areas</a></li> + <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Axis">Grid Axis</a></li> + <li><a href="/en-US/docs/Glossary/Grid_rows">Grid row</a></li> + <li><a href="/en-US/docs/Glossary/Grid_column">Grid column</a></li> + </ol> + </li> +</ol> +</section> diff --git a/files/vi/web/css/css_grid_layout/tong_quan_ve_grid_layout/index.html b/files/vi/web/css/css_grid_layout/tong_quan_ve_grid_layout/index.html new file mode 100644 index 0000000000..c1ebfbf5d5 --- /dev/null +++ b/files/vi/web/css/css_grid_layout/tong_quan_ve_grid_layout/index.html @@ -0,0 +1,763 @@ +--- +title: Tổng quan về Bố cục Lưới +slug: Web/CSS/CSS_Grid_Layout/tong_quan_ve_grid_layout +tags: + - ok +translation_of: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +--- +<p><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">Bố cục Lưới CSS</a> đưa vào CSS một hệ thống lưới hai chiều. Các lưới có thể dùng để bố cục những vùng lớn trong trang hoặc những thành phần giao diện người dùng nhỏ. Bài viết này giới thiệu Bố cục Lưới CSS và hệ thống thuật ngữ nằm trong chi tiết kỹ thuật của Bố cục Lưới CSS Cấp 1. Những đặc trưng được thể hiện trong tổng quan này sẽ được giải thích chi tiết hơn trong phần còn lại của hướng dẫn.</p> + +<h2 id="Lưới_là_gì">Lưới là gì?</h2> + +<p>Một lưới là một tổ hợp của những đường ngang và dọc cắt nhau - một nhóm xác định các cột và nhóm kia xác định các hàng. Các phần tử có thể được đặt lên lưới, dựa vào các đường hàng và cột này. Lưới CSS có các đặc trưng sau:</p> + +<h3 id="Kích_thước_đường_ray_cố_định_và_linh_hoạt">Kích thước đường ray cố định và linh hoạt</h3> + +<p>Bạn có thể tạo một lưới có kích thước đường ray cố định - bằng điểm ảnh chẳng hạn. Điều này sẽ đặt lưới vào điểm ảnh xác định khớp với bố cục bạn mong muốn. Bạn cũng có thể tạo một lưới sử dụng kích thước linh hoạt bằng phần trăm hoặc dùng đơn vị mới <code>fr</code> được thiết kế cho mục đích này.</p> + +<h3 id="Sắp_đặt_phần_tử">Sắp đặt phần tử</h3> + +<p>Bạn có thể đặt những phần tử vào những vị trí chính xác trên lưới bằng cách dùng số thứ tự đường, bằng tên hoặc trỏ vào một khu vực của lưới. Lưới có bao gồm một thuật toán để điều khiển việc sắp đặt các phần tử không có vị trí rõ ràng trên lưới.</p> + +<h3 id="Creation_of_additional_tracks_to_hold_content">Creation of additional tracks to hold content</h3> + +<p>You can define an explicit grid with grid layout but the specification also deals with the content added outside of a declared grid, which adds additional rows and columns when needed. Features such as adding “as many columns that will fit into a container” are included.</p> + +<h3 id="Alignment_control">Alignment control</h3> + +<p>Grid contains alignment features so that we can control how the items align once placed into a grid area, and how the entire grid is aligned. </p> + +<h3 id="Control_of_overlapping_content">Control of overlapping content</h3> + +<p>More than one item can be placed into a grid cell or area, they can partially overlap each other. This layering may then be controlled with {{cssxref("z-index")}} property.</p> + +<p>Grid is a powerful specification and when combined with other parts of CSS such as <a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">flexbox</a>, can help you to create layouts that were previously impossible to build in CSS. It all starts by creating a grid in your <strong>grid container</strong>.</p> + +<h2 id="The_Grid_container">The Grid container</h2> + +<p>We create a <em>grid container</em> by declaring <code>display: grid</code> or <code>display: inline-grid</code> on an element. As soon as we do this all <em>direct children</em> of that element will become <em>grid items</em>.</p> + +<p>In this example, I have a containing div with a class of wrapper, inside are five child elements.</p> + +<pre class="brush: html"><div class="wrapper"> + <div>One</div> + <div>Two</div> + <div>Three</div> + <div>Four</div> + <div>Five</div> +</div> +</pre> + +<p>I make the <code>.wrapper</code> a grid container.</p> + +<pre class="brush: css">.wrapper { + display: grid; +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('The_Grid_container', '200', '330') }}</p> + +<p>All the direct children are now grid items. In a web browser, you won’t see any difference to how these items are displayed before turning them into a grid, as grid has created a single column grid for the items. At this point, you may find it useful to work in Firefox Developer Edition, which has the <a href="/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts">Grid Inspector</a> available as part of the Developer Tools. If you view this example in Firefox and inspect the grid, you will see a small icon next to the value <code>grid</code>. Click this and then the grid on this element will be overlaid in the browser window.</p> + +<p><img alt="Using the Grid Highlighter in DevTools to view a grid" src="https://mdn.mozillademos.org/files/14631/1-grid-inspector.png" style="height: 753px; width: 900px;"></p> + +<p>As you learn and then work with the CSS Grid Layout this tool will give you a better idea of what is happening with your grids visually.</p> + +<p>If we want to start making this more grid-like we need to add column tracks.</p> + +<h2 id="Grid_Tracks">Grid Tracks</h2> + +<p>We define rows and columns on our grid with the {{cssxref("grid-template-columns")}} and {{cssxref("grid-template-rows")}} properties. These define grid tracks. A <em>grid track</em> is the space between any two lines on the grid. In the below image you can see a track highlighted – this is the first row track in our grid.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14637/1_Grid_Track.png" style="height: 261px; width: 392px;"></p> + +<p>I can add to our earlier example by adding the <code>grid-template-columns</code> property, then defining the size of the column tracks.</p> + +<p>I have now created a grid with three 200-pixel-wide column tracks. The child items will be laid out on this grid one in each grid cell.</p> + +<div id="grid_first"> +<pre class="brush: html"><div class="wrapper"> + <div>One</div> + <div>Two</div> + <div>Three</div> + <div>Four</div> + <div>Five</div> +</div> +</pre> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 200px 200px 200px; +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('grid_first', '610', '140') }}</p> +</div> + +<h3 id="The_fr_Unit">The fr Unit</h3> + +<p>Tracks can be defined using any length unit. Grid also introduces an additional length unit to help us create flexible grid tracks. The new <code>fr</code> unit represents a fraction of the available space in the grid container. The next grid definition would create three equal width tracks that grow and shrink according to the available space.</p> + +<div id="fr_unit_ls"> +<pre class="brush: html"><div class="wrapper"> + <div>One</div> + <div>Two</div> + <div>Three</div> + <div>Four</div> + <div>Five</div> +</div> +</pre> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 1fr 1fr 1fr; +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('fr_unit_ls', '220', '140') }}</p> +</div> + +<p>In this next example, we create a definition with a <code>2fr</code> track then two <code>1fr</code> tracks. The available space is split into four. Two parts are given to the first track and one part each to the next two tracks.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 2fr 1fr 1fr; +} +</pre> + +<p>In this final example, we mix absolute sized tracks with fraction units. The first track is 500 pixels, so the fixed width is taken away from the available space. The remaining space is divided into three and assigned in proportion to the two flexible tracks.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 500px 1fr 2fr; +} +</pre> + +<h3 id="Track_listings_with_repeat()_notation">Track listings with <code>repeat()</code> notation</h3> + +<p>Large grids with many tracks can use the <code>repeat()</code> notation, to repeat all or a section of the track listing. For example the grid definition:</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 1fr 1fr 1fr; +} +</pre> + +<p>Can also be written as:</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); +} +</pre> + +<p>Repeat notation can be used for a part of the track listing. In this next example I have created a grid with an initial 20-pixel track, then a repeating section of 6 <code>1fr</code> tracks then a final 20-pixel track.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: 20px repeat(6, 1fr) 20px; +} +</pre> + +<p>Repeat notation takes the track listing, and uses it to create a repeating pattern of tracks. In this next example, my grid will consist of 10 tracks, a <code>1fr</code> track, and then followed by a <code>2fr</code> track. This pattern will be repeated five times.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(5, 1fr 2fr); +} +</pre> + +<h3 id="The_implicit_and_explicit_grid">The implicit and explicit grid</h3> + +<p>When creating our example grid we defined our column tracks with the {{cssxref("grid-template-columns")}} property, but in addition let the grid create rows it needed for any other content. These rows are created in the implicit grid. The explicit grid consists of the rows and columns you define with {{cssxref("grid-template-columns")}} and {{cssxref("grid-template-rows")}}. If you place something outside of that defined grid, or due to the amount of content more grid tracks are needed, then the grid creates rows and columns in the implicit grid. These tracks will be auto-sized by default, resulting in their size being based on the content that is inside them.</p> + +<p>You can also define a set size for tracks created in the implicit grid with the {{cssxref("grid-auto-rows")}} and {{cssxref("grid-auto-columns")}} properties.</p> + +<p>In the below example we use <code>grid-auto-rows</code> to ensure that tracks created in the implicit grid are 200 pixels tall.</p> + +<pre class="brush: html"><div class="wrapper"> + <div>One</div> + <div>Two</div> + <div>Three</div> + <div>Four</div> + <div>Five</div> +</div> +</pre> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-auto-rows: 200px; +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('The_implicit_and_explicit_grid', '230', '420') }}</p> + +<h3 id="Track_sizing_and_minmax()">Track sizing and <code>minmax()</code></h3> + +<p>When setting up an explicit grid or defining the sizing for automatically created rows or columns we may want to give tracks a minimum size, but also ensure they expand to fit any content that is added. For example, I may want my rows to never collapse smaller than 100 pixels, but if my content stretches to 300 pixels in height, then I would like the row to stretch to that height.</p> + +<p>Grid has a solution for this with the {{cssxref("minmax", "minmax()")}} function. In this next example I am using <code>minmax()</code> in the value of {{cssxref("grid-auto-rows")}}. This means automatically created rows will be a minimum of 100 pixels tall, and a maximum of <code>auto</code>. Using <code>auto</code> means that the size will look at the content size and will stretch to give space for the tallest item in a cell, in this row.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-auto-rows: minmax(100px, auto); +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<pre class="brush: html"><div class="wrapper"> + <div>One</div> + <div>Two + <p>I have some more content in.</p> + <p>This makes me taller than 100 pixels.</p> + </div> + <div>Three</div> + <div>Four</div> + <div>Five</div> +</div> +</pre> + +<p>{{ EmbedLiveSample('Track_sizing_and_minmax()', '240', '470') }}</p> + +<h2 id="Grid_Lines">Grid Lines</h2> + +<p>It should be noted that when we define a grid we define the grid tracks, not the lines. Grid then gives us numbered lines to use when positioning items. In our three column, two row grid we have four column lines.</p> + +<p><img alt="Diagram showing numbered grid lines." src="https://mdn.mozillademos.org/files/14761/1_diagram_numbered_grid_lines.png" style="height: 456px; width: 764px;"></p> + +<p>Lines are numbered according to the writing mode of the document. In a left-to-right language, line 1 is on the left-hand side of the grid. In a right-to-left language, it is on the right-hand side of the grid. Lines can also be named, and we will look at how to do this in a later guide in this series.</p> + +<h3 id="Positioning_items_against_lines">Positioning items against lines</h3> + +<p>We will be exploring line based placement in full detail in a later article. The following example demonstrates doing this in a simple way. When placing an item, we target the line – rather than the track.</p> + +<p>In the following example I am placing the first two items on our three column track grid, using the {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} and {{cssxref("grid-row-end")}} properties. Working from left to right, the first item is placed against column line 1, and spans to column line 4, which in our case is the far-right line on the grid. It begins at row line 1 and ends at row line 3, therefore spanning two row tracks.</p> + +<p>The second item starts on grid column line 1, and spans one track. This is the default so I do not need to specify the end line. It also spans two row tracks from row line 3 to row line 5. The other items will place themselves into empty spaces on the grid.</p> + +<pre class="brush: html"><div class="wrapper"> + <div class="box1">One</div> + <div class="box2">Two</div> + <div class="box3">Three</div> + <div class="box4">Four</div> + <div class="box5">Five</div> +</div> +</pre> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-auto-rows: 100px; +} + +.box1 { + grid-column-start: 1; + grid-column-end: 4; + grid-row-start: 1; + grid-row-end: 3; +} + +.box2 { + grid-column-start: 1; + grid-row-start: 3; + grid-row-end: 5; +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Positioning_items_against_lines', '230', '420') }}</p> + +<p>Don't forget that you can use the <a href="/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts">Grid Inspector</a> in Firefox Developer Tools to see how the items are positioned against the lines of the grid.</p> + +<h2 id="Grid_Cells">Grid Cells</h2> + +<p>A <em>grid cell</em> is the smallest unit on a grid. Conceptually it is like a table cell. As we saw in our earlier examples, once a grid is defined as a parent the child items will lay themselves out in one cell each of the defined grid. In the below image, I have highlighted the first cell of the grid.</p> + +<p><img alt="The first cell of the grid highlighted" src="https://mdn.mozillademos.org/files/14643/1_Grid_Cell.png" style="height: 233px; width: 350px;"></p> + +<h2 id="Grid_Areas">Grid Areas</h2> + +<p>Items can span one or more cells both by row or by column, and this creates a <em>grid area</em>. Grid areas must be rectangular – it isn’t possible to create an L-shaped area for example. The highlighted grid area spans two row and two column tracks.</p> + +<p><img alt="A grid area" src="https://mdn.mozillademos.org/files/14645/1_Grid_Area.png" style="height: 238px; width: 357px;"></p> + +<h2 id="Gutters">Gutters</h2> + +<p><em>Gutters</em> or <em>alleys</em> between grid cells can be created using the {{cssxref("grid-column-gap")}} and {{cssxref("grid-row-gap")}} properties, or the shorthand {{cssxref("grid-gap")}}. In the below example, I am creating a 10-pixel gap between columns and a <code>1em</code> gap between rows.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-column-gap: 10px; + grid-row-gap: 1em; +} +</pre> + +<pre class="brush: html"><div class="wrapper"> + <div>One</div> + <div>Two</div> + <div>Three</div> + <div>Four</div> + <div>Five</div> +</div> +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.wrapper > div { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Gutters') }}</p> + +<p>Any space used by gaps will be accounted for before space is assigned to the flexible length <code>fr</code> tracks, and gaps act for sizing purposes like a regular grid track, however you cannot place anything into a gap. In terms of line-based positioning, the gap acts like a fat line.</p> + +<h2 id="Nesting_grids">Nesting grids</h2> + +<p>A grid item can become a grid container. In the following example, I have the three-column grid that I created earlier, with our two positioned items. In this case the first item has some sub-items. As these items are not direct children of the grid they do not participate in grid layout and so display in a normal document flow.</p> + +<div id="nesting"> +<pre class="brush: html"><div class="wrapper"> + <div class="box box1"> + <div class="nested">a</div> + <div class="nested">b</div> + <div class="nested">c</div> + </div> + <div class="box box2">Two</div> + <div class="box box3">Three</div> + <div class="box box4">Four</div> + <div class="box box5">Five</div> +</div> +</pre> + +<p><img alt="Nested grid in flow" src="https://mdn.mozillademos.org/files/14641/1_Nested_Grids_in_flow.png" style="height: 512px; width: 900px;"></p> + +<p>If I set <code>box1</code> to <code>display: grid</code> I can give it a track definition and it too will become a grid. The items then lay out on this new grid.</p> + +<pre class="brush: css">.box1 { + grid-column-start: 1; + grid-column-end: 4; + grid-row-start: 1; + grid-row-end: 3; + display: grid; + grid-template-columns: repeat(3, 1fr); +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.box { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> +</div> + +<p>{{ EmbedLiveSample('nesting', '600', '340') }}</p> + +<p>In this case the nested grid has no relationship to the parent. As you can see in the example it has not inherited the {{cssxref("grid-gap")}} of the parent and the lines in the nested grid do not align to the lines in the parent grid.</p> + +<h3 id="Subgrid">Subgrid</h3> + +<p>In the level 1 grid specification there is a feature called <em>subgrid</em> which would let us create nested grids that use the track definition of the parent grid.</p> + +<div class="note"> +<p>Subgrids are not yet implemented in any browsers, and the specification is subject to change.</p> +</div> + +<p>In the current specification, we would edit the above nested grid example to use <code>display: subgrid</code> rather than <code>display: grid</code>, then remove the track definition. The nested grid will use the parent grid tracks to layout items.</p> + +<p>It should be noted that the nested grid is in both dimensions—rows and columns. There is no concept of the implicit grid working with subgrids. This means you need to ensure that the parent grid has enough row and column tracks for all the subitems.</p> + +<pre class="brush: css">.box1 { + grid-column-start: 1; + grid-column-end: 4; + grid-row-start: 1; + grid-row-end: 3; + display: subgrid; +} +</pre> + +<h2 id="Layering_items_with_z-index">Layering items with <code>z-index</code></h2> + +<p>Grid items can occupy the same cell. If we return to our example with items positioned by line number, we can change this to make two items overlap.</p> + +<div id="l_ex"> +<pre class="brush: html"><div class="wrapper"> + <div class="box box1">One</div> + <div class="box box2">Two</div> + <div class="box box3">Three</div> + <div class="box box4">Four</div> + <div class="box box5">Five</div> +</div> +</pre> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-auto-rows: 100px; +} + +.box1 { + grid-column-start: 1; + grid-column-end: 4; + grid-row-start: 1; + grid-row-end: 3; +} + +.box2 { + grid-column-start: 1; + grid-row-start: 2; + grid-row-end: 4; +} +</pre> + +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.box { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> +</div> + +<p>{{ EmbedLiveSample('l_ex', '230', '420') }}</p> + +<p>The item <code>box2</code> is now overlapping <code>box1</code>, it displays on top as it comes later in the source order.</p> + +<h3 id="Controlling_the_order">Controlling the order</h3> + +<p>We can control the order in which items stack up by using the <code>z-index</code> property - just like positioned items. If we give <code>box2</code> a lower <code>z-index</code> than <code>box1</code> it will display below <code>box1</code> in the stack.</p> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-auto-rows: 100px; +} + +.box1 { + grid-column-start: 1; + grid-column-end: 4; + grid-row-start: 1; + grid-row-end: 3; + z-index: 2; +} + +.box2 { + grid-column-start: 1; + grid-row-start: 2; + grid-row-end: 4; + z-index: 1; +} +</pre> + +<div class="hidden"> +<pre class="brush: html"><div class="wrapper"> + <div class="box box1">One</div> + <div class="box box2">Two</div> + <div class="box box3">Three</div> + <div class="box box4">Four</div> + <div class="box box5">Five</div> +</div> +</pre> + +<pre class="brush: css">* {box-sizing: border-box;} + +.wrapper { + border: 2px solid #f76707; + border-radius: 5px; + background-color: #fff4e6; +} + +.box { + border: 2px solid #ffa94d; + border-radius: 5px; + background-color: #ffd8a8; + padding: 1em; + color: #d9480f; +} + +.nested { + border: 2px solid #ffec99; + border-radius: 5px; + background-color: #fff9db; + padding: 1em; +} +</pre> +</div> + +<p>{{ EmbedLiveSample('Controlling_the_order', '230', '420') }}</p> + +<h2 id="Next_Steps">Next Steps</h2> + +<p>In this article we have had a very quick look through the Grid Layout Specification. Have a play with the code examples, and then move onto <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">the next part of this guide where we will really start to dig into the detail of CSS Grid Layout</a>.</p> + +<section class="Quick_links" id="Quick_Links"> +<ol> + <li><a href="/en-US/docs/Web/CSS"><strong>CSS</strong></a></li> + <li><a href="/en-US/docs/Web/CSS/Reference"><strong>CSS Reference</strong></a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout"><strong>Bố cục Lưới CSS</strong></a></li> + <li data-default-state="open"><a href="#"><strong>Các hướng dẫn</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout">Basics concepts of grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship to other layout methods</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Line-based placement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">Grids, logical values and writing modes</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and Accessibility</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid Layout and Progressive Enhancement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout">Realizing common layouts using grids</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Properties</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/grid">grid</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-area">grid-area</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-columns">grid-auto-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-flow">grid-auto-flow</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-rows">grid-auto-rows</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column">grid-column</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-end">grid-column-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-gap">grid-column-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-start">grid-column-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-gap">grid-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row">grid-row</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-end">grid-row-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-gap">grid-row-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-start">grid-row-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template">grid-template</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-areas">grid-template-areas</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-columns">grid-template-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-rows">grid-template-rows</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Glossary</strong></a> + <ol> + <li><a href="/en-US/docs/Glossary/Grid">Grid</a></li> + <li><a href="/en-US/docs/Glossary/Grid_lines">Grid lines</a></li> + <li><a href="/en-US/docs/Glossary/Grid_tracks">Grid tracks</a></li> + <li><a href="/en-US/docs/Glossary/Grid_cell">Grid cell</a></li> + <li><a href="/en-US/docs/Glossary/Grid_areas">Grid areas</a></li> + <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Axis">Grid Axis</a></li> + <li><a href="/en-US/docs/Glossary/Grid_rows">Grid row</a></li> + <li><a href="/en-US/docs/Glossary/Grid_column">Grid column</a></li> + </ol> + </li> +</ol> +</section> diff --git a/files/vi/web/css/css_transitions/index.html b/files/vi/web/css/css_transitions/index.html new file mode 100644 index 0000000000..23559df42c --- /dev/null +++ b/files/vi/web/css/css_transitions/index.html @@ -0,0 +1,121 @@ +--- +title: CSS Transitions +slug: Web/CSS/CSS_Transitions +tags: + - CSS + - CSS Transitions + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Transitions +--- +<div>{{CSSRef}}</div> + +<p><strong>CSS Transitions</strong> is a module of CSS that lets you create gradual transitions between the values of specific CSS properties. The behavior of these transitions can be controlled by specifying their timing function, duration, and other attributes.</p> + +<h2 id="Reference">Reference</h2> + +<h3 id="Properties">Properties</h3> + +<div class="index"> +<ul> + <li>{{cssxref("transition")}}</li> + <li>{{cssxref("transition-delay")}}</li> + <li>{{cssxref("transition-duration")}}</li> + <li>{{cssxref("transition-property")}}</li> + <li>{{cssxref("transition-timing-function")}}</li> +</ul> +</div> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Guide/CSS/Using_CSS_transitions">Using CSS transitions</a></dt> + <dd>Step-by-step tutorial about how to create transitions using CSS. This article describes each relevant CSS property and explains how they interact with each other.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Transitions')}}</td> + <td>{{Spec2('CSS3 Transitions')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0 {{property_prefix("-webkit")}}<br> + 26.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10.0</td> + <td>11.6 {{property_prefix("-o")}}<br> + 12.10 <a href="http://my.opera.com/ODIN/blog/2012/08/03/a-hot-opera-12-50-summer-time-snapshot">#</a></td> + <td>3.0 {{property_prefix("-webkit")}}<br> + 6.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.1 {{property_prefix("-webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}} {{property_prefix("-moz")}}<br> + {{CompatGeckoMobile("16.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>10.0 {{property_prefix("-o")}}<br> + 12.10 <a href="http://my.opera.com/ODIN/blog/2012/08/03/a-hot-opera-12-50-summer-time-snapshot">#</a></td> + <td>3.2 {{property_prefix("-webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Related to CSS Transitions, <a href="/en-US/docs/Web/CSS/CSS_Animations">CSS Animations</a> provide finer control over animated properties.</li> +</ul> diff --git a/files/vi/web/css/css_transitions/using_css_transitions/index.html b/files/vi/web/css/css_transitions/using_css_transitions/index.html new file mode 100644 index 0000000000..e9a5bd6acd --- /dev/null +++ b/files/vi/web/css/css_transitions/using_css_transitions/index.html @@ -0,0 +1,1139 @@ +--- +title: Sử dụng CSS transitions +slug: Web/CSS/CSS_Transitions/Using_CSS_transitions +translation_of: Web/CSS/CSS_Transitions/Using_CSS_transitions +--- +<p>{{CSSref}}</p> + +<p><span class="seoSummary"><strong>CSS transitions</strong> cung cấp một cách để điều khiển tốc độ của hiệu ứng khi thay đổi các thuộc tính của CSS. Thay vì, các thay đổi thuộc tính tạo ra ảnh hưởng ngay lập tức, bạn có thể làm cho các thay đổi này diễn ra trong một khoảng thời gian. Ví dụ, nếu bạn thay đổi màu sắc của một phần tử từ trắng thành đen, thông thường sự thay đổi là tức thời. Với CSS transitions, các thay đổi xảy ra tại những khoảng thời gian, theo một đường cong tăng tốc, có thể tùy chỉnh.</span></p> + +<p>Các hình động liên quan đến quá trình chuyển tiếp giữa hai trạng thái thường được gọi là các chuyển tiếp tiềm ẩn (implicit transitions) vì các trạng thái ở giữa trạng thái bắt đầu và kết thúc đã được ngầm định bởi trình duyệt.</p> + +<p><img alt="A CSS transition tells the browser to draw the intermediate states between the initial and final states, showing the user a smooth transitions." src="/files/4529/TransitionsPrinciple.png" style="display: block; height: 196px; margin: auto; width: 680px;"></p> + +<p>CSS transitions giúp bạn quyết định những thuộc tính nào có hiệu ứng (bằng cách <em>liệt kê chúng</em>), khi nào thì hiệu ứng sẽ bắt đầu (bằng cách thiết lập <em>thời gian trì hoãn - delay</em>), bao lâu thì chuyển đổi sẽ kết thúc (bằng cách thiết lập khoảng <em>thời gian - duration</em>), và cách chuyển đổi diễn ra (bằng cách định nghĩa <em>timing function,</em> ... tuyến tính hoặc nhanh ở lúc bắt đầu, chậm ở lúc kết thúc).</p> + +<div class="note"><strong>Chú ý: </strong>các thuộc tính CSS transition có thể được sử dụng mà không cần bất kỳ prefix provider (nhà cung cấp tiền tố nào), nhưng hiện nay, các vender prefix (tiền tố nhà cung cấp) vẫn cần thiết để tương thích với các trình duyệt cũ (ví dụ Firefox 15 và các phiên bản trước đó, Opera 12 và các phiên bản trước đó, WebKit 5.1.10 và các phiên bản trước đó, Chrome 25 và các phiên bản thấp hơn). Một bảng thống kê khả năng tương thích ở phần cuối của trang này sẽ cung cấp nhiều thông tin hơn.</div> + +<h2 id="Những_thuộc_tính_CSS_nào_có_thể_tạo_hiệu_ứng">Những thuộc tính CSS nào có thể tạo hiệu ứng?</h2> + +<p>Những lập trình viên Web có thể định nghĩa thuộc tính nào có hiệu ứng và theo cách nào. Điều này cho phép tạo ra các chuyển đổi phức tạo. Tuy nhiên, không phải tất cả các thuộc tính đều có thể tạo hiệu ứng, vì vậy bạn cần biết <a href="/en-US/docs/CSS/CSS_animated_properties">danh sách các thuộc tính có thể tạo hiệu ứng</a>.</p> + +<div class="note">Chú ý: Danh sách này có thể thay đổi. Bạn cần chú ý tới điều này.</div> + +<p class="note">Ngoài ra giá trị <code>auto</code> là một trường hợp rất phức tạp. Một vài trình duyệt, dựa trên Gecko, triển khai giá trị này khác so với những trình duyệt dựa trên WebKit, ít chặt chẽ hơn. Sử dụng các hiệu ứng với <code>auto</code> có thể dẫn tới những kết quả khác nhau, phụ thuộc vào trình duyệt và phiên bản của nó, vì vậy nên tránh sử dụng giá trị này.</p> + +<p class="note">Cũng cần lưu ý khi sử dụng một transition ngay sau khi thêm phần tử tới DOM bằng cách sử dụng <code>.appendChild()</code> hoặc loại bỏ thuộc tính <code>display: none</code> của nó. Điều này xem như trạng thái ban đầu không bao giờ xảy ra và phần tử luôn luôn ở trạng thái kết thúc. Cách dễ nhất để giải quyết vấn đề này là sử dụng <code>window.setTimeout()</code> trước khi thay đổi thuộc tính CSS mà bạn muốn tạo hiệu ứng.</p> + +<h3 id="Ví_dụ_nhiều_thuộc_tính_với_hiệu_ứng">Ví dụ nhiều thuộc tính với hiệu ứng</h3> + +<h4 id="Nội_dung_HTML">Nội dung HTML</h4> + +<pre class="brush: html; highlight:[3]"><body> + <p>The box below combines transitions for: width, height, background-color, transform. Hover over the box to see these properties animated.</p> + <div class="box">Sample</div> +</body></pre> + +<h4 id="Nội_dung_CSS">Nội dung CSS</h4> + +<pre class="brush: css; highlight:[8,9]">.box { + border-style: solid; + border-width: 1px; + display: block; + width: 100px; + height: 100px; + background-color: #0000FF; + -webkit-transition: width 2s, height 2s, background-color 2s, -webkit-transform 2s; + transition: width 2s, height 2s, background-color 2s, transform 2s; +} + +.box:hover { + background-color: #FFCCCC; + width: 200px; + height: 200px; + -webkit-transform: rotate(180deg); + transform: rotate(180deg); +} +</pre> + +<p>{{EmbedLiveSample('Multiple_animated_properties_example', 600, 300)}}</p> + +<h2 id="Các_thuộc_tính_được_sử_dụng_để_định_nghĩa_các_transition">Các thuộc tính được sử dụng để định nghĩa các transition</h2> + +<p>CSS Transitions được điều khiển bằng cách viết tắt thuộc tính {{cssxref("transition")}}. Đây là cách tốt nhất để cấu hình các transition, nó tránh việc có một danh sách dài các tham số, cái có thể gây khó chịu khi phải dành nhiều thời gian để gỡ lỗi.</p> + +<p>Bạn có thể điều khiển từng thành phần của transition với các thuộc tính sau:</p> + +<p><strong>(Chú ý các vòng lặp vô hạn chỉ dành cho mục đích mục đích minh họa; CSS <code>transitions</code> chỉ thay đổi một thuộc tính từ bắt đầu tới kết thúc. Nếu bạn cần các hiệu ứng như vòng lặp, hãy sử dụng CSS <code><a href="/en-US/docs/">animation</a></code>)</strong></p> + +<dl> + <dt>{{cssxref("transition-property")}}</dt> + <dd>Chỉ định tên các thuộc tính CSS để áp dụng hiệu ứng. Chỉ các các thuộc tính được liệt kê ở đây có hiệu ứng trong thời gian chuyển đổi; những thay đổi của các thuộc tính khác xảy ra ngay lập tức như thường lệ.</dd> + <dt>{{cssxref("transition-duration")}}</dt> + <dd>Chỉ định khoảng thời gian các chuyển tiếp xảy ra. Bạn có thể chỉ định một khoảng thời gian duy nhất áp dụng cho tất cả các thuộc tính, hoặc nhiều giá trị cho mỗi cho phép mỗi thuộc tính chuyển đổi qua các khoảng thời gian khác nhau.</dd> + <dd> + <div> + <div id="duration_0_5s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-duration: 0.5s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush:css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position:absolute; + -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transform color; + transition-duration: 0.5s; + transition-timing-function: ease-in-out; +} +.box1{ + transform: rotate(270deg); + -webkit-transform: rotate(270deg); + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transformv color; + transition-duration: 0.5s; + transition-timing-function: ease-in-out; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("duration_0_5s", 275, 150)}}</div> + </div> + + <div id="duration_1s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-duration: 1s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top -webkit-transform color; + -webkit-transition-duration: 1s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform color; + transition-duration: 1s; + transition-timing-function: ease-in-out; +} +.box1{ + transform: rotate(270deg); + -webkit-transform: rotate(270deg); + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top -webkit-transform transform color; + -webkit-transition-duration: 1s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transform color; + transition-duration: 1s; + transition-timing-function: ease-in-out; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("duration_1s",275,150)}}</div> + </div> + + <div id="duration_2s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-duration: 2s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transform color; + transition-duration: 2s; + transition-timing-function: ease-in-out; +} +.box1{ + transform: rotate(270deg); + -webkit-transform: rotate(270deg); + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transform color; + transition-duration: 2s; + transition-timing-function: ease-in-out; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("duration_2s",275,150)}}</div> + </div> + + <div id="duration_4s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-duration: 4s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; + -webkit-transition-duration: 4s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transform color; + transition-duration: 4s; + transition-timing-function: ease-in-out; +} +.box1{ + transform: rotate(270deg); + -webkit-transform: rotate(270deg); + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; + -webkit-transition-duration: 4s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top transform -webkit-transform color; + transition-duration: 4s; + transition-timing-function: ease-in-out; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("duration_4s",275,150)}}</div> + </div> + </div> + </dd> + <dt>{{cssxref("transition-timing-function")}}</dt> + <dd><img alt="" src="/files/3434/TF_with_output_gt_than_1.png" style="float: left; height: 173px; margin-right: 5px; width: 130px;">Chỉ định một hàm để định nghĩa cách các giá trị trung gian cho các thuộc tính được tính toán như thế nào. Timing functions xác định cách các giá trị trung gian của chuyển đổi được tính toán. Hầu hết <a href="/en-US/docs/CSS/timing-function">timing function</a> có thể được xác định bằng cách cung cấp các đồ thị tương ứng, như định nghĩa bốn đỉnh của một khối cubic bezier. Bạn cũng có thể chọn easing từ <a href="http://easings.net/">Easing Functions Cheat Sheet.</a></dd> + <dd> + <div class="cleared"> + <div id="ttf_ease" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-timing-function: ease</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: ease; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: ease; +} +.box1{ + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position:absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: ease; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: ease; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("ttf_ease",275,150)}}</div> + </div> + + <div id="ttf_linear" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-timing-function: linear</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: linear; +} +.box1{ + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top:25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: linear; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("ttf_linear",275,150)}}</div> + </div> + + <div id="ttf_stepend" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-timing-function: step-end</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: step-end; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: step-end; +} +.box1{ + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top:25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: step-end; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: step-end; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("ttf_stepend",275,150)}}</div> + </div> + + <div id="ttf_step4end" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-timing-function: steps(4, end)</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { width: 250px; height:125px;} +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: steps(4, end); + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: steps(4, end); +} +.box1{ + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-timing-function: steps(4, end); + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-timing-function: steps(4, end); +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("ttf_step4end",275,150)}}</div> + </div> + </div> + </dd> + <dt>{{cssxref("transition-delay")}}</dt> + <dd>Xác định khoảng thời gian trì hoãn giữa thời gian một thuộc tính thay đổi và lúc chuyển tiếp thực sự bắt đầu.</dd> + <dd> + <div> + <div id="delay_0_5s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-delay: 0.5s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { + width: 250px; + height: 125px; +} + +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 0.5s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 0.5s; + transition-timing-function: linear; +} + +.box1 { + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top:25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 0.5s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 0.5s; + transition-timing-function: linear; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("delay_0_5s",275,150)}}</div> + </div> + + <div id="delay_1s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-delay: 1s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { + width: 250px; + height: 125px; +} + +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 1s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 1s; + transition-timing-function: linear; +} + +.box1{ + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 1s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 1s; + transition-timing-function: linear; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("delay_1s",275,150)}}</div> + </div> + + <div id="delay_2s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-delay: 2s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { + width: 250px; + height: 125px; +} + +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 2s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 2s; + transition-timing-function: linear; +} + +.box1 { + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 2s; + -webkit-transition-timing-function: linear; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 2s; + transition-timing-function: linear; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("delay_2s",275,150)}}</div> + </div> + + <div id="delay_4s" style="width: 251px; display: inline-block; margin-right: 1px; margin-bottom: 1px;"> + <p><code>transition-delay: 4s</code></p> + + <div style="display: none;"> + <pre class="brush:html"> <div class="parent"> + <div class="box">Lorem</div> +</div> + </pre> + + <pre class="brush: css">.parent { + width: 250px; + height: 125px; +} + +.box { + width: 100px; + height: 100px; + background-color: red; + font-size: 20px; + left: 0px; + top: 0px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 4s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 4s; + transition-timing-function: ease-in-out; +} + +.box1 { + width: 50px; + height: 50px; + background-color: blue; + color: yellow; + font-size: 18px; + left: 150px; + top: 25px; + position: absolute; + -webkit-transition-property: width height background-color font-size left top color; + -webkit-transition-duration: 2s; + -webkit-transition-delay: 4s; + -webkit-transition-timing-function: ease-in-out; + transition-property: width height background-color font-size left top color; + transition-duration: 2s; + transition-delay: 4s; + transition-timing-function: ease-in-out; +} +</pre> + + <pre class="brush:js">function updateTransition() { + var el = document.querySelector("div.box"); + + if (el) { + el.className = "box1"; + } else { + el = document.querySelector("div.box1"); + el.className = "box"; + } + + return el; +} + +var intervalID = window.setInterval(updateTransition, 7000); +</pre> + </div> + + <div>{{EmbedLiveSample("delay_4s",275,150)}}</div> + </div> + </div> + </dd> +</dl> + +<p>Cú pháp CSS được viết tắt như sau:</p> + +<pre class="brush: css">div { + transition: <property> <duration> <timing-function> <delay>; +}</pre> + +<h2 id="Phát_hiện_sự_bắt_đầu_và_hoàn_thành_của_quá_trình_chuyển_tiếp">Phát hiện sự bắt đầu và hoàn thành của quá trình chuyển tiếp</h2> + +<p>Bạn có thể sử dụng sự kiện {{event("transitionend")}} để phát hiện một hiệu ứng đã kết thúc. Đây là một đối tượng {{domxref("TransitionEvent")}}, trong đó có 2 thuộc tính được thêm vào một đối tượng {{domxref("Event")}} thông thường là:</p> + +<dl> + <dt><code>propertyName</code></dt> + <dd>Một chuỗi báo hiệu tên thuộc tính CSS đã hoàn thành quá trình chuyển tiếp.</dd> + <dt><code>elapsedTime</code></dt> + <dd>Một số thực báo hiệu số giây quá trình chuyển tiếp đã diễn ra tại thời điểm sự kiện xảy ra. Giá trị này không ảnh hưởng tới giá trị của {{cssxref("transition-delay")}}.</dd> +</dl> + +<p>Thông thường, bạn có thể sử dụng phương thức {{domxref("EventTarget.addEventListener", "addEventListener()")}} để theo dõi sự kiện này:</p> + +<pre class="brush: js">el.addEventListener("transitionend", updateTransition, true); +</pre> + +<p>Để phát hiện quá trình chuyển tiếp bắt đầu sử dụng {{event("transitionrun")}} (xảy ra trước thời gian chờ) và {{event("transitionstart")}} (xảy ra sau thời gian chờ), theo cùng một mẫu:</p> + +<pre class="brush: js">el.addEventListener("transitionrun", signalStart, true); +el.addEventListener("transitionstart", signalStart, true);</pre> + +<div class="note"><strong>Chú ý: </strong>Sự kiện transitioned không xảy ra nếu quá trình chuyển tiếp bị hủy bỏ trước khi nó hoàn thành vì phần tử {{cssxref("display")}}<code>: none </code>hoặc giá trị của thuộc tính đã thay đổi.</div> + +<h2 id="Khi_danh_sách_thuộc_tính_và_giá_trị_có_độ_dài_khác_nhau">Khi danh sách thuộc tính và giá trị có độ dài khác nhau</h2> + +<p>Nếu danh sách giá trị ngắn hơn danh sách thuộc tính, giá trị của nó sẽ được lặp lại để phù hợp. Ví dụ:</p> + +<pre class="brush: css">div { + transition-property: opacity, left, top, height; + transition-duration: 3s, 5s; +} +</pre> + +<p>Điều này sẽ tương ứng với:</p> + +<pre class="brush: css">div { + transition-property: opacity, left, top, height; + transition-duration: 3s, 5s, 3s, 5s; +}</pre> + +<p>Tương tự, nếu danh sách giá trị dài hơn danh sách thuộc tính, nó sẽ bị cắt bớt, như ví dụ dưới đây:</p> + +<pre class="brush: css">div { + transition-property: opacity, left; + transition-duration: 3s, 5s, 2s, 1s; +}</pre> + +<p>Sẽ được biên dịch thành:</p> + +<pre class="brush: css">div { + transition-property: opacity, left; + transition-duration: 3s, 5s; +}</pre> + +<h2 id="Một_ví_dụ_đơn_giản">Một ví dụ đơn giản</h2> + +<p>Đây là ví dụ thực hiện quá trình chuyển tiếp font size trong bốn giây với 2 giây trì hoãn giữa thời điểm người dùng di chuyển chuột lên phần tử và khi hiệu ứng bắt đầu:</p> + +<pre class="brush: css">#delay { + font-size: 14px; + transition-property: font-size; + transition-duration: 4s; + transition-delay: 2s; +} + +#delay:hover { + font-size: 36px; +} +</pre> + +<h2 id="Sử_dụng_transitions_khi_highlighting_menus">Sử dụng transitions khi highlighting menus</h2> + +<p>Một trường hợp phổ biến là sử dụng CSS làm nổi bật các item trong một menu khi người dùng di chuột lên chúng. Việc sử dụng transition giúp hiệu ứng hấp dẫn hơn.</p> + +<p>Trước khi xem code, bạn có thể muốn xem <a href="https://codepen.io/anon/pen/WOEpva">live demo</a> (giả sử trình duyệt của bạn hỗ trợ transitions).</p> + +<p>Đầu tiên chúng ta thiết lập menu sử dụng HTML:</p> + +<pre class="brush: html"><nav> + <a href="#">Home</a> + <a href="#">About</a> + <a href="#">Contact Us</a> + <a href="#">Links</a> +</nav></pre> + +<p>Sau đó chúng ta sử dụng CSS để style và tạo hiệu ứng cho menu:</p> + +<pre class="brush: css">a { + color: #fff; + background-color: #333; + transition: all 1s ease-out; +} + +a:hover, +a:focus { + color: #333; + background-color: #fff; +} +</pre> + +<p>Đoạn CSS quyết định menu trông như thế nào, với cả màu background và text thay đổi khi phần tử có trạng thái là {{cssxref(":hover")}} và {{cssxref(":focus")}}.</p> + +<h2 id="Sử_dụng_transitions_để_làm_cho_tính_năng_JavaScript_mượt_mà">Sử dụng transitions để làm cho tính năng JavaScript mượt mà</h2> + +<p>Transitions là một công cụ tuyệt vời để làm mọi thứ trong mượt mà hơn mà không cần phải làm mọi thứ với JavaScript. Hãy xem ví dụ.</p> + +<pre class="brush: html"><p>Click anywhere to move the ball</p> +<div id="foo"></div> +</pre> + +<p>Sử dụng JavaScript bạn có thể làm hiệu ứng quả bóng di chuyển tới một vị trí nhất định xảy ra:</p> + +<pre class="brush: js">var f = document.getElementById('foo'); +document.addEventListener('click', function(ev){ + f.style.transform = 'translateY('+(ev.clientY-25)+'px)'; + f.style.transform += 'translateX('+(ev.clientX-25)+'px)'; +},false); +</pre> + +<p>Với CSS bạn có thể làm cho nó diễn ra mượt mà, mà không cần nhiều nỗ lực. Đơn giản thêm một transition tới phần tử và mọi thay đổi sẽ diễn ra mượt mà:</p> + +<pre class="brush: css">p { + padding-left: 60px; +} + +#foo { + border-radius: 50px; + width: 50px; + height: 50px; + background: #c00; + position: absolute; + top: 0; + left: 0; + transition: transform 1s; +} +</pre> + +<p>Bạn có thể thử ở đây: <a href="http://jsfiddle.net/9h261pzo/291/">http://jsfiddle.net/9h261pzo/291/</a></p> + +<h2 id="Các_thông_số_kỹ_thuật">Các thông số kỹ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Transitions', '', '')}}</td> + <td>{{Spec2('CSS3 Transitions')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_với_trình_duyệt">Khả năng tương thích với trình duyệt</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0 {{property_prefix("-webkit")}}<br> + 26.0</td> + <td>{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10</td> + <td>10.5 {{property_prefix("-o")}}<br> + 12.10</td> + <td>3.2 {{property_prefix("-webkit")}}</td> + </tr> + <tr> + <td><code>transitionend</code> event</td> + <td>1.0<sup>[1]</sup><br> + 26.0</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>10</td> + <td>10.5<sup>[2]</sup><br> + 12<br> + 12.10</td> + <td>3.2<sup>[1]</sup><br> + 6.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.1</td> + <td>{{CompatGeckoMobile("2.0")}} {{property_prefix("-moz")}}<br> + {{CompatGeckoMobile("16.0")}}</td> + <td>10</td> + <td>10 {{property_prefix("-o")}}<br> + 12.10</td> + <td>3.2</td> + </tr> + <tr> + <td><code>transitionend</code> event</td> + <td>2.1<sup>[1]</sup></td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>10</td> + <td>10<sup>[2]</sup><br> + 12<br> + 12.10</td> + <td>3.2<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Chrome 1.0, WebKit 3.2 and Android 2.1 implemented this as the non-standard <code>webkitTransitionEnd</code>. Chrome 26.0 and WebKit 6.0 implement the standard <code>transitionend</code>.</p> + +<p>[2] Opera 10.5 and Opera Mobile 10 implemented this as <code>oTransitionEnd</code>, version 12 as <code>otransitionend</code> and version 12.10 as the standard <code>transitionend</code>.</p> + +<h2 id="Các_bài_liên_quan">Các bài liên quan</h2> + +<ul> + <li>The {{domxref("TransitionEvent")}} interface and the {{event("transitionend")}} event.</li> + <li><a href="/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations">Using CSS animations</a></li> +</ul> diff --git a/files/vi/web/css/filter-function/index.html b/files/vi/web/css/filter-function/index.html new file mode 100644 index 0000000000..d991ffe975 --- /dev/null +++ b/files/vi/web/css/filter-function/index.html @@ -0,0 +1,68 @@ +--- +title: <filter-function> +slug: Web/CSS/filter-function +tags: + - CSS + - CSS Data Type + - Filter Effects + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/filter-function +--- +<div>{{cssref}}</div> + +<p>The <code><strong><filter-function></strong></code> <a href="/en-US/docs/Web/CSS">CSS</a> <a href="/en-US/docs/Web/CSS/CSS_Types">data type</a> represents a graphical effect that can change the appearance of an input image. It is used in the {{cssxref("filter")}} and {{cssxref("backdrop-filter")}} properties.</p> + +<h2 id="Syntax">Syntax</h2> + +<p>The <code><filter-function></code> data type is specified using one of the filter functions listed below. Each function requires an argument which, if invalid, results in no filter being applied.</p> + +<dl> + <dt>{{cssxref("filter-function/blur", "blur()")}}</dt> + <dd>Blurs the image.</dd> + <dt>{{cssxref("filter-function/brightness", "brightness()")}}</dt> + <dd>Makes the image brighter or darker.</dd> + <dt>{{cssxref("filter-function/contrast", "contrast()")}}</dt> + <dd>Increases or decreases the image's contrast.</dd> + <dt>{{cssxref("filter-function/drop-shadow", "drop-shadow()")}}</dt> + <dd>Applies a drop shadow behind the image.</dd> + <dt>{{cssxref("filter-function/grayscale", "grayscale()")}}</dt> + <dd>Converts the image to grayscale.</dd> + <dt>{{cssxref("filter-function/hue-rotate", "hue-rotate()")}}</dt> + <dd>Changes the overall hue of the image.</dd> + <dt>{{cssxref("filter-function/invert", "invert()")}}</dt> + <dd>Inverts the colors of the image.</dd> + <dt>{{cssxref("filter-function/opacity", "opacity()")}}</dt> + <dd>Makes the image transparent.</dd> + <dt>{{cssxref("filter-function/saturate", "saturate()")}}</dt> + <dd>Super-saturates or desaturates the input image.</dd> + <dt>{{cssxref("filter-function/sepia", "sepia()")}}</dt> + <dd>Converts the image to sepia.</dd> +</dl> + +<h2 id="Specification">Specification</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comments</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('Filters 1.0', '#typedef-filter-function', '<filter-function>') }}</td> + <td>{{ Spec2('Filters 1.0') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Properties that use this data type: {{cssxref("filter")}} and {{cssxref("backdrop-filter")}}</li> +</ul> diff --git a/files/vi/web/css/filter-function/url/index.html b/files/vi/web/css/filter-function/url/index.html new file mode 100644 index 0000000000..b341e7d763 --- /dev/null +++ b/files/vi/web/css/filter-function/url/index.html @@ -0,0 +1,29 @@ +--- +title: url() +slug: Web/CSS/filter-function/url +translation_of: Web/CSS/url() +--- +<div>{{cssref}}</div> + +<p>Hàm <strong><code>url()</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> dùng <a href="/en-US/docs/Web/SVG/Element/filter">SVG filter</a> để thay đổi bề ngoài của ảnh.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">url(<em>location</em>)</pre> + +<h3 id="Thông_số">Thông số</h3> + +<dl> + <dt><code>location</code></dt> + <dd> {{cssxref("<url>")}} của tệp {{glossary("XML")}} chỉ định bộ lọc SVG, và có thể bao gồm một neo cho một phần tử bộ lọc cụ thể.</dd> +</dl> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: css">url(resources.svg#c1)</pre> + +<h2 id="Liên_quan">Liên quan</h2> + +<ul> + <li>{{cssxref("<filter-function>")}}</li> +</ul> diff --git a/files/vi/web/css/flex-basis/index.html b/files/vi/web/css/flex-basis/index.html new file mode 100644 index 0000000000..8b2021d009 --- /dev/null +++ b/files/vi/web/css/flex-basis/index.html @@ -0,0 +1,206 @@ +--- +title: flex-basis +slug: Web/CSS/flex-basis +translation_of: Web/CSS/flex-basis +--- +<div>{{CSSRef}}</div> + +<p>The <strong><code>flex-basis</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> property sets the initial main size of a flex item. It sets the size of the content box unless otherwise set with {{Cssxref("box-sizing")}}.</p> + +<div>{{EmbedInteractiveExample("pages/css/flex-basis.html")}}</div> + + + +<div class="note"> +<p><strong>Note:</strong> in case both <code>flex-basis</code> (other than <code>auto</code>) and <code>width</code> (or <code>height</code> in case of <code>flex-direction: column</code>) are set for an element, <code>flex-basis</code> has priority.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="brush:css no-line-numbers">/* Specify <'width'> */ +flex-basis: 10em; +flex-basis: 3px; +flex-basis: auto; + +/* Intrinsic sizing keywords */ +flex-basis: fill; +flex-basis: max-content; +flex-basis: min-content; +flex-basis: fit-content; + +/* Automatically size based on the flex item’s content */ +flex-basis: content; + +/* Global values */ +flex-basis: inherit; +flex-basis: initial; +flex-basis: unset; +</pre> + +<p>The <code>flex-basis</code> property is specified as either the keyword <code><a href="#content">content</a></code> or a <code><a href="#<'width'>"><'width'></a></code>.</p> + +<h3 id="Values">Values</h3> + +<dl> + <dt><a id="<'width'>" name="<'width'>"><code><'width'></code></a></dt> + <dd>An absolute {{cssxref("<length>")}}, a {{cssxref("<percentage>")}} of the parent flex container's main size property, or the keyword <code>auto</code>. Negative values are invalid. Defaults to <code>auto</code>.</dd> + <dt><a id="content" name="content"><code>content</code></a></dt> + <dd>Indicates automatic sizing, based on the flex item’s content.</dd> + <dd> + <div class="note"><strong>Note:</strong> This value was not present in the initial release of Flexible Box Layout, and thus some older implementations will not support it. The equivalent effect can be had by using <code>auto</code> together with a main size (<a href="https://drafts.csswg.org/css2/visudet.html#propdef-width">width</a> or <a href="https://drafts.csswg.org/css2/visudet.html#propdef-height">height</a>) of <code>auto</code>.</div> + + <div class="note"> + <p id="comment_text_0"><strong>History:</strong></p> + + <ul> + <li>Originally, <code>flex-basis:auto</code> meant "look at my <code>width</code> or <code>height</code> property".</li> + <li>Then, <code>flex-basis:auto</code> was changed to mean automatic sizing, and "main-size" was introduced as the "look at my <code>width</code> or <code>height</code> property" keyword. It was implemented in <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1032922" title='RESOLVED FIXED - Rename "flex-basis:auto" to "main-size", while preserving "flex:auto" shorthand value'>bug 1032922</a>.</li> + <li>Then, that change was reverted in <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1093316" title='RESOLVED FIXED - Back out flexbox "flex-basis:main-size" rename, since the CSSWG removed it from the spec'>bug 1093316</a>, so <code>auto</code> once again means "look at my <code>width</code> or <code>height</code> property"; and a new <code>content</code> keyword is being introduced to trigger automatic sizing. ({{bug("1105111")}} covers adding that keyword).</li> + </ul> + </div> + </dd> +</dl> + +<h3 id="Formal_syntax">Formal syntax</h3> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Example">Example</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><ul class="container"> + <li class="flex flex1">1: flex-basis test</li> + <li class="flex flex2">2: flex-basis test</li> + <li class="flex flex3">3: flex-basis test</li> + <li class="flex flex4">4: flex-basis test</li> + <li class="flex flex5">5: flex-basis test</li> +</ul> + +<ul class="container"> + <li class="flex flex6">6: flex-basis test</li> +</ul> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">.container { + font-family: arial, sans-serif; + margin: 0; + padding: 0; + list-style-type: none; + display: flex; + flex-wrap: wrap; +} + +.flex { + background: #6AB6D8; + padding: 10px; + margin-bottom: 50px; + border: 3px solid #2E86BB; + color: white; + font-size: 20px; + text-align: center; + position: relative; +} + +.flex:after { + position: absolute; + z-index: 1; + left: 0; + top: 100%; + margin-top: 10px; + width: 100%; + color: #333; + font-size: 18px; +} + +.flex1 { + flex-basis: auto; +} + +.flex1:after { + content: 'auto'; +} + +.flex2 { + flex-basis: max-content; +} + +.flex2:after { + content: 'max-content'; +} + +.flex3 { + flex-basis: min-content; +} + +.flex3:after { + content: 'min-content'; +} + +.flex4 { + flex-basis: fit-content; +} + +.flex4:after { + content: 'fit-content'; +} + +.flex5 { + flex-basis: content; +} + +.flex5:after { + content: 'content'; +} + +.flex6 { + flex-basis: fill; +} + +.flex6:after { + content: 'fill'; +} +</pre> + +<h3 id="Results">Results</h3> + +<p>{{EmbedLiveSample('Example', '860', '360', '', 'Web/CSS/flex-basis')}}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Specification</th> + <th>Status</th> + <th>Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Flexbox', '#propdef-flex-basis', 'flex-basis')}}</td> + <td>{{Spec2('CSS3 Flexbox')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<p>{{cssinfo}}</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("css.properties.flex-basis")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>CSS Flexbox Guide: <em><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox">Basic Concepts of Flexbox</a></em></li> + <li>CSS Flexbox Guide: <em><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Controlling_Ratios_of_Flex_Items_Along_the_Main_Ax">Controlling Ratios of flex items along the main axis</a></em></li> + <li>{{cssxref("width")}}</li> +</ul> + +<div id="eJOY__extension_root" style=""></div> diff --git a/files/vi/web/css/flex-wrap/index.html b/files/vi/web/css/flex-wrap/index.html new file mode 100644 index 0000000000..b033cd54e5 --- /dev/null +++ b/files/vi/web/css/flex-wrap/index.html @@ -0,0 +1,173 @@ +--- +title: flex-wrap +slug: Web/CSS/flex-wrap +tags: + - CSS + - CSS Flexible Boxes + - CSS Property +translation_of: Web/CSS/flex-wrap +--- +<p>{{ CSSRef}}</p> + +<h2 id="Tóm_tắt">Tóm tắt</h2> + +<p>Thuộc tính <strong>flex-wrap</strong> xác định xem flex item có bị ép vào một dòng đơn hay có thể được rớt dòng thành nhiều dòng. Nếu việc rớt dòng được chấp nhận, thuộc tính này còn cho phép bạn xác định hướng để rớt dùng.</p> + +<p>{{cssinfo}}</p> + +<p>Xem bài <a href="/en/CSS/Using_CSS_flexible_boxes">sử dụng flexible box</a> để biết thêm thông tin cũng như đọc thêm về các thuộc tính khác.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="brush:css">flex-wrap: nowrap; +flex-wrap: wrap; +flex-wrap: wrap-reverse; + +/* Global values */ +flex-wrap: inherit; +flex-wrap: initial; +flex-wrap: unset; +</pre> + +<h3 id="Các_giá_trị">Các giá trị</h3> + +<p>Thuộc tính <strong>flex-wrap</strong> chấp nhận những giá trị sau đây.:</p> + +<dl> + <dt><code>nowrap</code></dt> + <dd>Các flex item phải nằm trên một dòng đơn, việc này có thể khiến cho các item này tràn ra ngoài container.</dd> + <dd><strong>Cross-start</strong> sẽ tương đương với <strong>start</strong> hoặc <strong>before</strong> tùy thuộc vào giá trị của {{cssxref("flex-direction")}}.</dd> + <dt><code>wrap</code></dt> + <dd>Những flex item sẽ có thể bị tách thành hai dòng nếu như tổng chiều rộng của các item lớn hơn chiều rộng của container. C<strong>ross-start</strong> sẽ tương đương với <strong>start</strong> hoặc <strong>before</strong> tùy thuộc vào giá trị của <code>flex-direction</code> và <strong>cross-end</strong> sẽ có giá trị ngược lại với <strong>cross-start</strong>.</dd> + <dt><code>wrap-reverse</code></dt> + <dd>Nó giống như <code>wrap</code> nhưng <strong>cross-start</strong> và <strong>cross-end</strong> thì có giá trị ngược lại.</dd> + <dt> + <h3 id="Cú_pháp_chính_quy">Cú pháp chính quy</h3> + </dt> +</dl> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="HTML">HTML</h3> + +<div id="Live_Sample"> +<pre class="brush: html"><h4>This is an example for flex-wrap:wrap </h4> +<div class="content"> + <div class="red">1</div> + <div class="green">2</div> + <div class="blue">3</div> +</div> +<h4>This is an example for flex-wrap:nowrap </h4> +<div class="content1"> + <div class="red">1</div> + <div class="green">2</div> + <div class="blue">3</div> +</div> +<h4>This is an example for flex-wrap:wrap-reverse </h4> +<div class="content2"> + <div class="red">1</div> + <div class="green">2</div> + <div class="blue">3</div> +</div> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">/* Common Styles */ +.content, +.content1, +.content2 { + color: #fff; + font: 100 24px/100px sans-serif; + height: 150px; + text-align: center; +} + +.content div, +.content1 div, +.content2 div { + height: 50%; + width: 50%; +} +.red { + background: orangered; +} +.green { + background: yellowgreen; +} +.blue { + background: steelblue; +} + +/* Flexbox Styles */ +.content { + display: -webkit-box; + display: -moz-box; + display: -ms-flexbox; + display: -moz-flex; + display: -webkit-flex; + display: flex; + flex-wrap: wrap; +} +.content1 { + display: -webkit-box; + display: -moz-box; + display: -ms-flexbox; + display: -moz-flex; + display: -webkit-flex; + display: flex; + flex-wrap: nowrap; +} +.content2 { + display: -webkit-box; + display: -moz-box; + display: -ms-flexbox; + display: -moz-flex; + display: -webkit-flex; + display: flex; + flex-wrap: wrap-reverse; +} + +</pre> +</div> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{ EmbedLiveSample('Examples', '700px', '700px', '', 'Web/CSS/flex-wrap') }}</p> + +<h2 id="Các_thông_số_kỹ_thuật">Các thông số kỹ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Thông số</th> + <th>Trang thái</th> + <th>Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Flexbox', '#flex-wrap-property', 'flex-wrap') }}</td> + <td>{{ Spec2('CSS3 Flexbox') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích">Tương thích</h2> + +<p> </p> + +<p class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("css.properties.flex-wrap")}}</p> + +<p> </p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Using_CSS_flexible_boxes" title="/en-US/docs/CSS/Using_CSS_flexible_boxes">Sử dụng flexible boxes</a></li> +</ul> diff --git a/files/vi/web/css/flex/index.html b/files/vi/web/css/flex/index.html new file mode 100644 index 0000000000..9b253f0e98 --- /dev/null +++ b/files/vi/web/css/flex/index.html @@ -0,0 +1,347 @@ +--- +title: flex +slug: Web/CSS/flex +tags: + - CSS + - CSS Flexible Boxes + - Tham khảo + - Tham số CSS +translation_of: Web/CSS/flex +--- +<div>{{CSSRef}}</div> + +<div>Tham số CSS flex qui định những thành phần con bên trong thành phần cha sẽ co lại hoặc giản ra như thế nào.</div> + +<div>Dưới đây là các giá trị có thể:</div> + +<div>{{cssxref("flex-grow")}}, {{cssxref("flex-shrink")}}, và {{cssxref("flex-basis")}}</div> + +<div> </div> + +<pre class="brush:css no-line-numbers">/* Giá trị cơ bản */ +flex: auto; +flex: initial; +flex: none; +flex: 2; + +/* Một giá trị thể hiện cho flex-grow */ +flex: 2; + +/* Một giá trị (độ rộng hoặc chiều cao) thể hiện cho flex-basis */ +flex: 10em; +flex: 30px; + +/* Hai giá trị thể hiện cho flex-grow (1) và flex-basis (30px) */ +/* Bởi vì 30px nên thể hiện cho flex-basis */ +flex: 1 30px; + +/* Hai giá trị thể hiện cho flex-grow và flex-shrink */ +flex: 2 2; + +/* Ba giá trị thể hiện cho flex-grow và flex-shrink và flex-basis */ +flex: 2 2 10%; + +/* Nhữg giá trị khái quát */ +flex: inherit; +flex: initial; +flex: unset; +</pre> + +<p>Trong hầu hết các trường hợp, Bạn nên sử dụng những giá trị sau: auto, initial, none, hoặc những số dương duy nhất. Để nhìn thấy hiệu quả của những giá trị này thử thay đổi kích thước của những "thành phần cha" sau đây:</p> + +<div id="flex"> +<pre class="hidden brush: html"><div class="flex-container"> + <div class="item auto">auto</div> + <div class="item auto">auto</div> + <div class="item auto">auto</div> +</div> + +<div class="flex-container"> + <div class="item auto">auto</div> + <div class="item initial">initial</div> + <div class="item initial">initial</div> +</div> + +<div class="flex-container"> + <div class="item auto">auto</div> + <div class="item auto">auto</div> + <div class="item none">none</div> +</div> + +<div class="flex-container"> + <div class="item initial">initial</div> + <div class="item none">none</div> + <div class="item none">none</div> +</div> + +<div class="flex-container"> + <div class="item four">4</div> + <div class="item two">2</div> + <div class="item one">1</div> +</div> +</pre> + +<pre class="hidden brush: css">* { + box-sizing: border-box; +} + +.flex-container { + background-color: #F4F7F8; + resize: horizontal; + overflow: hidden; + display: flex; + margin: 1em; +} + +.item { + margin: 1em; + padding: 0.5em; + width: 110px; + min-width: 0; + background-color: #1B5385; + color: white; + font-family: monospace; + font-size: 13px; +} + +.initial { + flex: initial; +} + +.auto { + flex: auto; +} + +.none { + flex: none; +} + +.four { + flex: 4; +} + +.two { + flex: 2; +} + +.one { + flex: 1; +} +</pre> + +<p>{{EmbedLiveSample("flex", 1200, 370, "", "", "example-outcome-frame")}}</p> + +<dl> + <dt><code>auto</code></dt> + <dt> </dt> + <dd>Những "thành phần con" được quy định kích thước bởi những tham số width và height, nhưng "thành phần con" này sẽ cố gắng lấp đầy hoặc là thu nhỏ lại để phù hợp với "thành phần cha". Cú pháp này tương ứng với: "flex: 1 1 auto".</dd> + <dt><code>initial</code></dt> + <dd>Đây là giá trị mặc định ( giá trị khi bạn không khai báo cho "thành phần con"). "Thành phần con" có kích thước tùy theo tham số width và height. "Thành phần con" sẽ co lại để phù hợp với "thành phần cha", nhưng nó sẽ không phình to ra để lấp đầy khoảng trống trong thành phần cha. Cú pháp này tương ứng với: "flex: 0 1 auto."</dd> + <dt><code>none</code></dt> + <dd>"Thành phần con" có kích thước tùy theo tham số width và height. Nó sẽ không co lại hay phình to trong "thành phần cha". Cú pháp này tương ứng với: "flex: 0 0 auto"</dd> + <dt><code><số dương></code></dt> + <dd>"Thành phần con" được cho một tỉ lệ cụ thể trong khoảng trống của thành phần cha. Cú pháp này tương ứng với: "flex: <số dương> 1 0"</dd> +</dl> + +<p>Theo quy định, thì "thành phần con" không thu nhỏ lại quá kích thước nhỏ nhất mà nó cho phép. Để thay đổi kích thước nhỏ nhất bạn có thể dùng: {{cssxref("min-width")}} hoặc {{cssxref("min-height")}}.</p> +</div> + +<p>{{cssinfo}}</p> + +<h2 id="Syntax" name="Syntax">Cú pháp</h2> + +<p>Tham số flex có thể sử dụng với một, hai hoặc 3 giá trị.</p> + +<p><strong>Cú pháp với 1 giá trị</strong>: Giá trị đó có thể là:</p> + +<ul> + <li>một giá trị đơn lẻ {{cssxref("<number>")}}: được xem nư là <code><a href="#<'flex-grow'>"><flex-grow></a></code>.</li> + <li>một giá trị với đơn vị là độ rộng {{cssxref("width")}}: khi đó được xem như là <code><a href="#<'flex-basis'>"><flex-basis></a></code>.</li> + <li>một giá trị là các từ sau: <code><a href="#none">none</a></code>, <code>auto</code>, or <code>initial</code>.</li> +</ul> + +<p><strong>Cú pháp với 2 giá trị</strong>: giá trị đầu phải là giá trị đơn lẻ {{cssxref("<number>")}} được xem là <code><a href="#<'flex-grow'>"><flex-grow></a></code>. Giá trị thứ 2 phải thuộc 1 trong 2 giá trị sau:</p> + +<ul> + <li>một giá trị lẻ {{cssxref("<number>")}}: được xem là <code><a href="#<'flex-grow'>"><flex-shrink></a></code>.</li> + <li>một giá trị với đơn vị (độ rộng hoặc chiều cao) {{cssxref("width")}}: được xem là <code><a href="#<'flex-basis'>"><flex-basis></a></code>.</li> +</ul> + +<p><strong>Cú pháp với 3 giá trị:</strong></p> + +<ul> + <li>Giá trị đầu phải đơn lẻ {{cssxref("<number>")}} được xem như là <code><a href="#<'flex-grow'>"><flex-grow></a></code>.</li> + <li>Giá trị thứ 2 phải đơn lẻ {{cssxref("<number>")}} được xem như là <code><a href="#<'flex-grow'>"><flex-shrink></a></code>.</li> + <li>Giá trị thứ 3 phải là hợp lý như độ rộng hoặc chiều cao {{cssxref("width")}} được xem như là <code><a href="#<'flex-basis'>"><flex-basis></a></code>.</li> +</ul> + +<h3 id="Values" name="Values">Values</h3> + +<dl> + <dt><a id="<'flex-grow'>" name="<'flex-grow'>"><code><'flex-grow'></code></a></dt> + <dd>Định nghĩa {{cssxref("flex-grow")}} cho "thành phần con". Tìm hiểu {{cssxref("<number>")}} để biết thêm thông tin chi tiết Giá trị âm là không hợp lệ. Giá trị mặc định là 0 nếu không cung cấp.</dd> + <dt><a id="<'flex-shrink'>" name="<'flex-shrink'>"><code><'flex-shrink'></code></a></dt> + <dd>Định nghĩa {{cssxref("flex-shrink")}} cho "thành phần con". Tìm hiểu {{cssxref("<number>")}} để biết thêm thông tin chi tiết. Giá trị âm là không hợp lệ. Giá trị mặc định là 1 nếu không cung cấp.</dd> + <dt><a id="<'flex-basis'>" name="<'flex-basis'>"><code><'flex-basis'></code></a></dt> + <dd>Định nghĩa {{cssxref("flex-basis")}} cho "thành phần con". Bất cứ giá trị hợp lệ nào cho độ rộng hoặc chiều cao điều sử dụng được. Tốt nhất là phải cung cấp đơn vị. Giá trị mặc định là auto nếu không cung cấp.</dd> + <dt><a id="none" name="none"><code>none</code></a></dt> + <dd>Định nghĩa này tương đương với 0 0 auto.</dd> +</dl> + +<div class="note"> +<p>Khi sử dụng một hoặc nhiều giá trị đơn lẻ, flex-basis sẽ đổi từ auto tới 0. Để biết thêm chi tiết có thể xem bản draft <a href="https://drafts.csswg.org/css-flexbox/#flex-common">Flexible Box Layout Module.</a></p> +</div> + +<dl> + <dt> + <h3 id="Formal_syntax">Formal syntax</h3> + </dt> +</dl> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: css">#flex-container { + display: flex; + flex-direction: row; +} + +#flex-container > .flex-item { + flex: auto; +} + +#flex-container > .raw-item { + width: 5rem; +} +</pre> + +<pre class="brush: html"><div id="flex-container"> + <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div> + <div class="raw-item" id="raw">Raw box</div> +</div> +</pre> + +<div class="hidden"> +<pre class="brush: js">var flex = document.getElementById("flex"); +var raw = document.getElementById("raw"); +flex.addEventListener("click", function() { + raw.style.display = raw.style.display == "none" ? "block" : "none"; +}); +</pre> + +<pre class="brush: css">#flex-container { + width: 100%; + font-family: Consolas, Arial, sans-serif; +} + +#flex-container > div { + border: 1px solid #f00; + padding: 1rem; +} + +#flex-container > .raw-item { + border: 1px solid #000; +} +</pre> +</div> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{EmbedLiveSample('Example','100%','60')}}</p> + +<h2 id="Specifications" name="Specifications">Thông số kỷ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Specification</th> + <th>Status</th> + <th>Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Flexbox', '#flex-property', 'flex')}}</td> + <td>{{Spec2('CSS3 Flexbox')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Độ_tương_thích_với_các_trình_duyệt_hiện_tại">Độ tương thích với các trình duyệt hiện tại</h2> + +<p>{{CompatibilityTable()}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("18.0")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("20.0")}}<br> + {{CompatGeckoDesktop("28.0")}}<sup>[2]</sup></td> + <td>21.0{{property_prefix("-webkit")}}<br> + 29.0</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatVersionUnknown}}</td> + <td>10.0{{property_prefix("-ms")}}<sup>[3]</sup><br> + 11.0<sup>[3]</sup></td> + <td>12.10</td> + <td> + <p>6.1{{property_prefix("-webkit")}}<br> + 9.0</p> + </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>Edge</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>4.4</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatVersionUnknown}}</td> + <td>11</td> + <td>12.10</td> + <td>7.1{{property_prefix("-webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] In Gecko 18.0 {{geckoRelease("18.0")}} và 19.0 {{geckoRelease("19.0")}} tính năng flexbox hổ trợ ẩn trong <code>about:config</code> với cấu hình <code>layout.css.flexbox.enabled</code>, giá trị mặc định là <code>false</code>.</p> + +<p>[2] Multi-line flexbox được hỗ trợ từ Gecko 28.0 {{geckoRelease("28.0")}}.</p> + +<p>Thêm nửa về hỗ trợ unprefixed, Gecko 48.0 {{geckoRelease("48.0")}} được hỗ trợ với tiền tố <code>-webkit</code> vì lý do tương thích xem <code>layout.css.prefixes.webkit</code>, giá trị mặc định to <code>false</code>. Từ Gecko 49.0 {{geckoRelease("49.0")}} giá trị mặc định là <code>true</code>.</p> + +<p>[3] Internet Explorer 10-11 (but not 12+) bỏ qua việc sử dụng <a href="/en-US/docs/Web/CSS/calc"><code>calc()</code></a> trong phần flex-basis part của cú pháp <code>flex</code> . Có thể dùng longhand thay thế cho shorthand như một sự thay thế. Nhìn <a href="https://github.com/philipwalton/flexbugs#8-flex-basis-doesnt-support-calc">Flexbug #8</a> để tìm hiểu thêm. Thêm nửa cú pháp flex với một giá trị đơn lẻ trong <code>flex-basis</code> được xem như không hợp lệ trong những version trên và vì vậy sẽ bị phớt lờ . Một cách để giải quyết vấn đề này là luôn luôn thêm một đơn vị cho phần <code>flex-basis</code> trong cú pháp đơn giản. Nhìn <a href="https://github.com/philipwalton/flexbugs#4-flex-shorthand-declarations-with-unitless-flex-basis-values-are-ignored">Flexbug #4</a> để tìm hiểu thêm.</p> + +<h2 id="See_also" name="See_also">Nên xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/Guide/CSS/Flexible_boxes" title="CSS/Using_CSS_flexible_boxes">Using CSS flexible boxes</a></li> +</ul> diff --git a/files/vi/web/css/index.html b/files/vi/web/css/index.html new file mode 100644 index 0000000000..25d2c39f23 --- /dev/null +++ b/files/vi/web/css/index.html @@ -0,0 +1,114 @@ +--- +title: CSS +slug: Web/CSS +tags: + - CSS + - Design + - Layout + - NeedsTranslation + - References + - TopicStub +translation_of: Web/CSS +--- +<p><span class="seoSummary"><strong>Cascading Style Sheets</strong>, viết tắt là <strong>CSS</strong>, là một ngôn ngữ <a href="/en-US/docs/DOM/stylesheet">định kiểu</a> được sử dụng để mô tả việc trình bày một tài liệu được viết bằng <a href="/en-US/docs/HTML" title="The HyperText Mark-up Language">HTML</a></span> or <a href="/en-US/docs/XML" title="en-US/docs/XML">XML</a> (bao gồm các ngôn ngữ khác nhau như XML, <a href="/en-US/docs/SVG" title="en-US/docs/SVG">SVG</a> or <a href="/en-US/docs/XHTML" title="en-US/docs/XHTML">XHTML</a>)<span class="seoSummary">. CSS mô tả cách các phần tử được hiển thị trên màn hình, trên giấy, trong lời nói, hoặc trên các phương tiện khác.</span></p> + +<p>CSS là một trong những ngôn ngữ cốt lõi của<em> web</em> mở và có đặt tả <a class="external" href="http://w3.org/Style/CSS/#specs">W3C specification</a>. Được phát triển theo cấp độ, CSS1 hiện tại đã lỗi thời, CSS2.1 là một đề xuất và <a href="/en-US/docs/CSS/CSS3" title="CSS3">CSS3</a>, hiên được chia thành các mô-đun nhỏ hơn, đang tiến triển trên bản theo dõi chuẩn. Bản thảo đầu tiên của các mô-đun CSS4 đang được viết.</p> + +<div style="margin: auto; text-align: center;"> +<div class="callout-box action-driven"> +<div>Tài liệu tham khảo CSS</div> + +<p><a href="/en-US/docs/CSS/CSS_Reference" title="en-US/docs/CSS/CSS_Reference">Tài liệu tham khảo</a> đầy đủ của chúng tôi dành cho <u>các nhà phát triển web dày dặn kinh nghiệm</u> mô tả mọi thuộc tính và khái niệm về CSS.</p> +</div> + +<div class="callout-box action-driven"> +<div>Hướng dẫn CSS</div> + +<p><a href="/en-US/docs/CSS/Getting_Started" title="en-US/docs/CSS/Getting_Started">Giới thiệu từng bước</a> hỗ trợ đầy đủ cho <u>người mới</u> bắt đầu. Nó trình bày tất cả các nguyên tắc cơ bản cần thiết.</p> +</div> + +<div class="callout-box action-driven"> +<div>CSS3 Demos</div> + +<p>Một <a href="/en-US/demos/tag/tech:css3" title="https://developer.mozilla.org/en-US/demos/tag/tech:css3">bộ sưa tập các bản trình diễn</a> hiển thị <u>các công nghệ CSS mới nhất</u> đang hoạt động: một sự thúc đẩy cho sự sáng tạo.</p> +</div> +</div> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Documentation" name="Documentation">Tài liệu và hướng dẫn về CSS</h2> + +<dl> + <dt>Các khái niệm chính về CSS</dt> + <dd>Mô tả <a href="/en-US/docs/CSS/Syntax" title="/en-US/docs/CSS/Syntax">cú pháp của ngôn ngữ</a> và giới thiệu các nguyên tắc cơ bản như <a href="/en-US/docs/CSS/Specificity" title="Specificity">đặc tính</a> và <a href="/en-US/docs/CSS/inheritance" title="inheritance">sự kế thừa</a>, <a href="/en-US/docs/CSS/box_model" title="Box model">mô hình hộp</a> và <a href="/en-US/docs/CSS/margin_collapsing" title="Margin collapsing">biên độ thu hẹp</a>, <a href="/en-US/docs/CSS/Understanding_z-index/The_stacking_context" title="The stacking context">xếp chồng</a> và các <a href="/en-US/docs/CSS/block_formatting_context" title="block formatting context">định dạng khối</a>, hoặc các giá trị <a href="/en-US/docs/CSS/initial_value" title="initial value">ban đầu</a>, <a href="/en-US/docs/CSS/computed_value" title="computed value">được tính toán</a>, <a href="/en-US/docs/CSS/used_value" title="used value">được sử dụng</a> và <a href="/en-US/docs/CSS/actual_value" title="actual value">thực tế</a>. Các thực thể như <a href="/en-US/docs/CSS/Shorthand_properties" title="CSS/Shorthand_properties">các thuộc tính CSS viết tắt</a> cũng được xác định.</dd> + <dt><a href="/en-US/docs/CSS/Writing_Efficient_CSS" title="CSS/Writing_Efficient_CSS">Viết CSS hiệu quả</a></dt> + <dd>Giải thích cách các công cụ định kiểu thực hiện việc so khớp bộ chọn và mô tả các quy tắc để viết CSS hiệu quả hơn.</dd> + <dt><a href="/en-US/docs/CSS/Tutorials/Using_CSS_transforms" title="How to use CSS3 Transforms (2D and 3D)">Chuyển đổi CSS</a></dt> + <dd>Trình bày các hoạt động 2D có thể được áp dụng cho từng phần tử để xoay, nghiêng, dịch chuyển nó.</dd> + <dt><a href="/en-US/docs/CSS/Tutorials/Using_CSS_transitions" title="How to use a CSS transition">Chuyển tiếp CSS</a></dt> + <dd>Giải thích cách thay của một phần tử bằng cách sử dụng một động mượt giữa trạng thái ban đầu và trạng thái cuối cùng.</dd> + <dt><a href="/en-US/docs/CSS/Tutorials/Using_CSS_animations" title="How to use a CSS animation">Hoạt ảnh trong CSS</a></dt> + <dd>Mô tả cách xác định hoạt ảnh của một phần tử mà còn cách <a href="/en-US/docs/CSS/CSS_animations/Detecting_CSS_animation_support">phát hiện</a> trong Javascript nếu trình duyệt hỗ trợ nó.</dd> + <dt><a href="/en-US/docs/CSS/Using_CSS_gradients" title="How to use CSS3 Gradients">Sử dụng Gradient trong CSS</a></dt> + <dd>Giải thích cách xác định gradient, hình ảnh bao gồm các biến thể mượt mà của màu sắc.</dd> + <dt><a href="/en-US/docs/CSS/Using_CSS_multi-column_layouts" title="How to use CSS3 Multicol layout">Bố cục nhiều cột trong CSS</a></dt> + <dd>Trình bày cách tạo trang nhiều cột bằng cách sử dụng bố cục nhiều cột CSS3.</dd> + <dt><a href="/en-US/docs/CSS/Multiple_backgrounds" title="How to use the CSS3 multiple background feature">Sử dụng nhiều nền trong CSS</a></dt> + <dd>Mô tả cách xác định một số hình nền trên cùng một thành phần.</dd> + <dt><a href="/en-US/docs/CSS/Scaling_background_images" title="CSS/Scaling_background_images">Chia tỷ lệ hình ảnh nền</a></dt> + <dd>Hiển thị cách kiểm soát hình nền khi hình ảnh và vùng chứa không cùng kích thước.</dd> + <dt><a class="internal" href="/en-US/docs/CSS/Media_queries" title="How to use CSS3 Media Queries">CSS media queries</a></dt> + <dd>Trình bày cách chọn các định kiểu dựa trên những chi tiết của thiết bị được hiển thị, như kích thước màn hình, độ phân giải hoặc nếu nó có màn hình cảm ứng.</dd> + <dt><a href="/en-US/docs/CSS_Counters" title="CSS Counters">Bộ đếm trong CSS</a></dt> + <dd>Giải thích cách sử dụng bộ đếm tự động và đánh số, về cơ bản được sử dụng làm bộ đếm cho danh sách.</dd> + <dt>Fonts và Typography</dt> + <dd>Thông báo về quản lý <a href="/en-US/docs/CSS/font" title="font">phông chữ</a> bằng cách sử dụng {{ cssxref("@font-face") }} và định dạng <a href="/en-US/docs/WOFF" title="About_WOFF">phông chữ WOFF</a>.</dd> + <dt><a href="/en-US/docs/CSS/Using_CSS_flexible_boxes" title="Using CSS flexible boxes">Sử dụng các hộp linh hoạt CSS</a></dt> + <dd>Mô tả cách sử dụng các hộp linh hoạt để thiết kế bố cục.</dd> + <dt><a href="/en-US/docs/Consistent_List_Indentation" title="Consistent_List_Indentation">Consistent List Indentation</a></dt> + <dd>Việc cố gắng thay đổi thụt đầu dòng của các danh sách bằng CSS thì phức tạp hơn, nhưng vì các trình duyệt tuân thủ CSS có các đường dẫn khác nhau để thụt lề mặc định. Tìm hiểu làm thế nào để có được tất cả trong dòng.</dd> + <dt><a href="/en-US/docs/DOM/Using_dynamic_styling_information" title="DOM/Using_dynamic_styling_information">Using dynamic styling information</a></dt> + <dd>Cách lấy thông tin và thao tác kiểu dáng thông qua DOM..</dd> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/CSS" title="/en-US/docs/tag/CSS">Xem tất cả ...</a></span></p> +</div> + +<div class="section"> +<h2 class="Community" id="Community" name="Community">Hỗ trợ từ cộng đồng</h2> + +<p>Bạn cần trợ giúp về vấn đề liên quan đến CSS và không thể tìm thấy giải pháp trong tài liệu?</p> + +<ul> + <li>Kiểm tra <a href="/en-US/docs/CSS/Common_CSS_Questions" title="en-US/docs/CSS/Common_CSS_Questions">các câu hỏi CSS phổ biến</a> để có gợi ý giải quyết vấn đề CSS.</li> + <li><a href="http://stackoverflow.com/questions/tagged/css" title="http://stackoverflow.com/questions/tagged/css">Stack Overflow</a>, một trang web hỏi - đáp được xây dựng và duy trì, tại đây bạn có thể tìm thấy đáp án cho câu hỏi của mình hay không. Nếu không bạn sẽ có thể đặt câu hỏi của mình ở đó.</li> + <li>Tham khảo diễn đàn về bố cục, bao gồm CSS và HTML + <ul> + <li>Đặt câu hỏi của bạn trên kên Mozilla IRC: <a class="link-irc" href="irc://irc.mozilla.org/css">#css</a></li> + <li>Đặt câu hỏi của bạn trên <a href="http://www.css-discuss.org/">trang web và danh sách thảo luận CSS</a></li> + </ul> + </li> +</ul> + +<p><span class="alllinks"><a class="external" href="http://www.catb.org/~esr/faqs/smart-questions.html" title="http://www.catb.org/~esr/faqs/smart-questions.html">Don't forget about the <em>netiquette</em>...</a></span></p> + +<h2 class="Tools" id="Tools" name="Tools">Công cụ dễ dàng phát triển CSS</h2> + +<ul> + <li><a class="external" href="http://jigsaw.w3.org/css-validator/">Dịch vụ Xác thực CSS W3C </a>kiểm tra CSS có hợp lệ. Nó là một công cụ gỡ lỗi vô cùng hữu ích.</li> + <li><a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug tiện ích mở rộng</a> của Firefox<span class="external">, một phần mở rộng phổ biến đó cho phép chỉnh sửa CSS trực tiếp trên các trang web mà bạn muốn xem</span>. Rất thực tế để kiểm tra một số thay đổi, mặc dù tiện ích mở rộng này làm được nhiều hơn nữa.</li> + <li><a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/60">Tiện ích mở rộng Web Developer</a> của Firefox cũng cho phép xem và chỉnh sửa trực tuyến trên trang web bạn đang xem. Đơn giản hơn Firebug, mặc dù ít mạnh mẽ hơn.</li> + <li><a class="external link-https" href="https://addons.mozilla.org/en-US/firefox/addon/179">Tiện ích EditCSS </a>của Firefox' cho phép sửa CSS trên Sidebar.</li> +</ul> + +<p><span class="alllinks"><a href="/en-US/docs/tag/CSS:Tools" title="/en-US/docs/tag/CSS:Tools">Xem tất cả...</a></span></p> + +<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Chủ đề liên quan</h2> + +<ul> + <li>Mozilla Learn <a href="/en-US/learn/css" title="https://developer.mozilla.org/en-US/learn/css">CSS resources</a>.</li> + <li>Các ngôn ngữ Web mở trên CSS, thường được áp dụng như: <a href="/en-US/docs/HTML" title="en-US/docs/HTML">HTML</a>, <a href="/en-US/docs/SVG" title="SVG">SVG</a>, <a href="/en-US/docs/XHTML" title="en-US/docs/XHTML">XHTML</a>, <a href="/en-US/docs/XML" title="en-US/docs/XML">XML</a>.</li> + <li>Các công nghệ của Mozilla sử dụng CSS: <a href="/en-US/docs/XUL" title="en-US/docs/XUL">XUL</a>, <a href="/en-US/docs/Extensions" title="en-US/docs/Extensions">Tiện ích mở rộng</a> của Firefox và Thunderbird, và <a href="/en-US/docs/Themes" title="en-US/docs/Themes">các chủ đề</a>.</li> +</ul> +</div> +</div> diff --git a/files/vi/web/css/length/index.html b/files/vi/web/css/length/index.html new file mode 100644 index 0000000000..a73aeee55f --- /dev/null +++ b/files/vi/web/css/length/index.html @@ -0,0 +1,324 @@ +--- +title: <length> +slug: Web/CSS/length +translation_of: Web/CSS/length +--- +<div>{{CSSRef}}</div> + +<p>The <code><length></code> <a href="/en-US/docs/Web/CSS">CSS</a> data type denotes distance measurements. It is a {{cssxref("<number>")}} immediately followed by a length unit (<code>px</code>, <code>em</code>, <code>pc</code>, <code>in</code>, <code>mm</code>, …). Like for any CSS dimension, there is no space between the unit literal and the number. The length unit is optional after the {{cssxref("<number>")}} <code>0</code>.</p> + +<p>Many CSS properties take<code> <length> </code>values, such as {{Cssxref("width")}}, {{Cssxref("margin")}}, {{Cssxref("padding")}}, {{Cssxref("font-size")}}, {{Cssxref("border-width")}}, {{Cssxref("text-shadow")}}, …</p> + +<p>For some properties, using negative lengths is a syntax error, but for some properties, negative lengths are allowed. Please note that although {{cssxref("<percentage>")}} values are also CSS dimensions and are accepted by some CSS properties that accept<code> <length></code> values, they are not themselves, <code><length></code> values.</p> + +<h2 id="Interpolation">Interpolation</h2> + +<p>Values of the <code><length></code> CSS data type can be interpolated in order to allow animations. In that case they are interpolated as real, floating-point, numbers. The interpolation happens on the calculated value. The speed of the interpolation is determined by the <a href="/en-US/docs/Web/CSS/timing-function">timing function</a> associated with the animation.</p> + +<h2 id="Units">Units</h2> + +<h3 id="Relative_length_units">Relative length units</h3> + +<h4 id="Font-relative_lengths">Font-relative lengths</h4> + +<dl> + <dt id="em"><code>em</code></dt> + <dd>This unit represents the calculated {{Cssxref("font-size")}} of the element. If used on the {{Cssxref("font-size")}} property itself, it represents the <em>inherited</em> font-size of the element. + <div class="note">This unit is often used to create scalable layouts, which keep the <a href="http://24ways.org/2006/compose-to-a-vertical-rhythm">vertical rhythm of the page</a>, even when the user changes the size of the fonts. The CSS properties {{cssxref("line-height")}}, {{cssxref("font-size")}}, {{cssxref("margin-bottom")}} and {{cssxref("margin-top")}} often have values expressed in <strong>em</strong>.</div> + </dd> + <dt id="ex"><code>ex</code></dt> + <dd>This unit represents the <a href="http://en.wikipedia.org/wiki/X-height">x-height</a> of the element's {{Cssxref("font")}}. On fonts with the 'x' letter, this is generally the height of lowercase letters in the font;<code style="white-space: nowrap;"> 1ex ≈ 0.5em </code>in many fonts.</dd> + <dt id="ch"><code>ch</code></dt> + <dd>This unit represents the width, or more precisely the advance measure, of the glyph '0' (zero, the Unicode character U+0030) in the element's {{Cssxref("font")}}.</dd> + <dt id="rem"><code>rem</code></dt> + <dd>This unit represents the {{Cssxref("font-size")}} of the root element (e.g. the font-size of the {{HTMLElement("html")}} element). When used on the {{Cssxref("font-size")}} on this root element, it represents its initial value. + <div class="note">This unit is practical in creating perfectly scalable layout. If not supported by the targeted browsers, such layout can be achieved using the <strong>em</strong> unit, though this is slightly more complex.</div> + </dd> +</dl> + +<h4 id="Viewport-percentage_lengths">Viewport-percentage lengths</h4> + +<p>Viewport-percentage lengths defined a length relatively to the size of viewport, that is the visible portion of the document. Only Gecko-based browsers are updating the viewport values dynamically, when the size of the viewport is modified (by modifying the size of the window on a desktop computer or by turning the device on a phone or a tablet).</p> + +<p>In conjunction with <code>overflow:auto</code>, space taken by eventual scrollbars is not subtracted from the viewport, whereas in the case of <code>overflow:scroll</code>, it is.</p> + +<p>In a {{cssxref("@page")}} at-rule declaration block, the use of the viewport lengths are invalid and the declaration will be dropped.</p> + +<dl> + <dt id="vh"><code>vh</code></dt> + <dd>1/100th of the height of the viewport.</dd> + <dt id="vw"><code>vw</code></dt> + <dd>1/100th of the width of the viewport.</dd> + <dt id="vmin"><code>vmin</code></dt> + <dd>1/100th of the minimum value between the height and the width of the viewport.</dd> + <dt id="vmax"><code>vmax</code></dt> + <dd>1/100th of the maximum value between the height and the width of the viewport.</dd> +</dl> + +<h3 id="Absolute_length_units">Absolute length units</h3> + +<p>Absolute length units represents a physical measurement and when the physical properties of the output medium are known, such as for print layout. This is done by anchored one of the unit to a physical unit and to defined the other relatively to it. The anchor is done differently for low-resolution devices, like screens, and high-resolution devices, like printers.</p> + +<p>For low-dpi devices, the unit <strong>px</strong> represents the physical <em>reference pixel</em> and the others are defined relative to it. Thus, <code>1in</code> is defined as <code>96px</code> which equals <code>72pt</code>. The consequence of this definition is that on such devices, length described in inches (<code>in</code>), centimeters (<code>cm</code>), millimeters (<code>mm</code>) doesn't necessary match the length of the physical unit with the same name.</p> + +<p>For high-dpi devices, inches (<code>in</code>), centimeters (<code>cm</code>), millimeters (<code>mm</code>) are defined as their physical counterparts. Therefore the <strong>px</strong> unit is defined relative to them (1/96 of 1 inch).</p> + +<div class="note"> +<p>Users may increase font size for accessibility purpose. To allow for usable layouts whatever is the used font size, use only absolute length units when the physical characteristics of the output medium are known, such as bitmap images. When setting length related to font-size, prefer relative units like <code>em</code> or <code>rem</code>.</p> +</div> + +<dl> + <dt id="px"><code>px</code></dt> + <dd>Relative to the viewing device.<br> + For screen display, typically one device pixel (dot) of the display.<br> + For <em>printers</em> and very <em>high resolution screens</em> one CSS pixel implies multiple device pixels, so that the number of pixel per inch stays around 96.</dd> + <dt id="mm"><code>mm</code></dt> + <dd>One millimeter.</dd> + <dt id="q"><code>q</code></dt> + <dd>A quarter of a millimeter (1/40th of a centimeter).</dd> + <dt id="cm"><code>cm</code></dt> + <dd>One centimeter (10 millimeters).</dd> + <dt id="in"><code>in</code></dt> + <dd>One inch (2.54 centimeters).</dd> + <dt id="pt"><code>pt</code></dt> + <dd>One point (1/72th of an inch).</dd> + <dt id="pc"><code>pc</code></dt> + <dd>One pica (12 points).</dd> + <dt id="mozmm"><code>mozmm</code> {{non-standard_inline}}</dt> + <dd>An experimental unit which attempts to render at exactly one millimeter regardless of the size or resolution of the display. This is rarely actually what you want, but may be useful in particular for mobile devices.</dd> +</dl> + +<h2 id="CSS_units_and_dots-per-inch">CSS units and dots-per-inch</h2> + +<p class="note">The unit <code>in</code> doesn't represent a physical inch on screen, but represents <code>96px</code>. That means that whatever is the real screen pixel density, it is assumed to be <code>96dpi</code>. On devices with a greater pixel density, <code>1in</code> will be smaller than 1 physical inch. Similarly <code>mm</code>, <code>cm</code>, and <code>pt</code> are not absolute length.</p> + +<p>Some specific examples:</p> + +<ul> + <li><code>1in</code> is always <code>96px,</code></li> + <li><code>3pt</code> is always <code>4px</code>,</li> + <li><code>25.4mm</code> is always <code>96px.</code></li> +</ul> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Values', '#lengths', '<length>')}}</td> + <td>{{Spec2('CSS3 Values')}}</td> + <td>Added <code>ch</code>, <code>rem</code>, <code>vw</code>, <code>vh</code>, <code>vmin</code>, <code>vmax</code> and <code>q</code></td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'syndata.html#length-units', '<length>')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td><code>pt</code>, <code>pc</code>, <code>px</code> are explicitly defined (were implicitly defined in CSS1)</td> + </tr> + <tr> + <td>{{SpecName('CSS1', '#length-units', '<length>')}}</td> + <td>{{Spec2('CSS1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}} </p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1</td> + <td>{{ CompatGeckoDesktop("1.0")}}</td> + <td>3.0</td> + <td>3.5</td> + <td>1.0</td> + </tr> + <tr> + <td><code>ch</code></td> + <td> + <p>27</p> + </td> + <td>{{ CompatGeckoDesktop("1.0")}}<sup>[1]</sup></td> + <td>9.0</td> + <td>20.0</td> + <td>7.0</td> + </tr> + <tr> + <td>ex</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>rem</code></td> + <td>4 (532.3)</td> + <td>{{ CompatGeckoDesktop("1.9.2")}}</td> + <td>9.0</td> + <td>11.6</td> + <td>4.1</td> + </tr> + <tr> + <td><code>vh, vw</code></td> + <td>20</td> + <td>{{CompatGeckoDesktop("19")}}</td> + <td>9.0</td> + <td>20.0</td> + <td>6.0</td> + </tr> + <tr> + <td><code>vmin</code></td> + <td> + <p>20</p> + </td> + <td>{{CompatGeckoDesktop("19")}}</td> + <td>9.0<sup>[2]</sup></td> + <td>20.0</td> + <td>6.0</td> + </tr> + <tr> + <td><code>vmax</code></td> + <td>26</td> + <td>{{CompatGeckoDesktop("19")}}</td> + <td>{{CompatNo}}</td> + <td>20.0</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Viewport-percentage lengths invalid in {{cssxref("@page")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("21")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>mozmm</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>1in</code> always is <code>96dpi</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>q</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("49.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>ch</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>7.8</td> + <td>{{CompatUnknown}}</td> + <td>7.1.1</td> + </tr> + <tr> + <td>ex</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>rem</code></td> + <td>2.1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>12.0</td> + <td>4.0</td> + </tr> + <tr> + <td><code>vh, vw, vmin</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("19")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>6.0</td> + </tr> + <tr> + <td><code>vmax</code></td> + <td>1.5</td> + <td>{{CompatGeckoMobile("19")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>4.0</td> + </tr> + <tr> + <td>Viewport-percentage lengths invalid in {{cssxref("@page")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("21.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>q</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("49.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] In Gecko 1.0-1.9.0 (Firefox 1.0-3.0)<code> ch </code>was the width of 'M' and it didn't work for {{CSSxref("border-width")}} and {{CSSxref("outline-width")}} CSS properties.</p> + +<p>[2] Internet Explorer implements this with the non-standard name <code>vm</code>.</p> diff --git a/files/vi/web/css/perspective/index.html b/files/vi/web/css/perspective/index.html new file mode 100644 index 0000000000..4af62b0eab --- /dev/null +++ b/files/vi/web/css/perspective/index.html @@ -0,0 +1,289 @@ +--- +title: perspective +slug: Web/CSS/perspective +translation_of: Web/CSS/perspective +--- +<div>{{CSSRef}}</div> + +<p>Thuộc tính <strong><code>perspective</code></strong> của <a href="/en-US/docs/Web/CSS">CSS</a> xác định khoảng cách từ mặt phẳng z=0 cho đến người dùng, việc này nhằm tạo ra một phối cảnh xa-gần cho những phần tử muốn hiển thị dưới dạng 3D. Mỗi phần tử hiển thị dạng 3D với z > 0 sẽ trở nên to ra (vì "gần" với người xem hơn); ngược lại phần tử dạng 3D có z < 0 sẽ trở nên bé lại (vì "xa" người xem hơn). Giá trị của thuộc tính này sẽ quyết định cường độ của hiệu ứng.</p> + +<pre class="brush: css no-line-numbers">/* Keyword value */ +perspective: none; + +/* <length> values */ +perspective: 20px; +perspective: 3.5em; + +/* Global values */ +perspective: inherit; +perspective: initial; +perspective: unset; +</pre> + +<p>Những phần của phần tử 3D có toạ độ trục z lớn hơn giá trị của thuộc tính <code>perspective</code> sẽ không được vẽ (nó xuất hiện ở "phía sau" người xem). </p> + +<p>Mặc định thì điểm "biến mất" (vanishing point) được đặt tại chính giữa của phẩn tử, nhưng lập trình viên có thể thay điểm vị trí của điểm này thông qua thuộc tính {{cssxref("perspective-origin")}}.</p> + +<p>Đặt giá trị của thuộc tính <code>perspective-origin</code> bằng <code>0</code> hoặc <code>none</code> sẽ tạo một cụm môi trường mới (<a href="/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context" title="en/CSS/Understanding_z-index/The_stacking_context">stacking context</a>).</p> + +<p>{{cssinfo}}</p> + +<h2 id="Syntax">Syntax</h2> + +<h3 id="Giá_trị">Giá trị</h3> + +<dl> + <dt><code>none</code></dt> + <dd>là từ khoá chỉ thị việc không áp dụng phối cảnh xa gần.</dd> + <dt><code><length></code></dt> + <dd>{{cssxref("<length>")}} giá trị này là khoảng cáh từ người xem đến mặt phẳng z = 0. Khi giá trị này lớn hơn <code>0</code>, phối cảnh xa gần sẽ được thiết lập cho phần tử. Khi nó bằng <code>0</code> hoặc nhỏ hơn <code>0</code>, thì bỏ đi phối cảnh xa-gần. </dd> +</dl> + +<h3 id="Cú_pháp">Cú pháp</h3> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Nội_dung_file_HTML">Nội dung file HTML </h3> + +<pre class="brush: html"><table> + <tbody> + <tr> + <th><code>perspective: 250px;</code> + </th> + <th><code>perspective: 350px;</code> + </th> + <th><code>perspective: 500px;</code> + </th> + </tr> + <tr> + <td> + <div class="container"> + <div class="cube pers250"> + <div class="face front">1</div> + <div class="face back">2</div> + <div class="face right">3</div> + <div class="face left">4</div> + <div class="face top">5</div> + <div class="face bottom">6</div> + </div> + </div> + </td> + <td> + <div class="container"> + <div class="cube pers350"> + <div class="face front">1</div> + <div class="face back">2</div> + <div class="face right">3</div> + <div class="face left">4</div> + <div class="face top">5</div> + <div class="face bottom">6</div> + </div> + </div> + </td> + <td> + <div class="container"> + <div class="cube pers500"> + <div class="face front">1</div> + <div class="face back">2</div> + <div class="face right">3</div> + <div class="face left">4</div> + <div class="face top">5</div> + <div class="face bottom">6</div> + </div> + </div> + </td> + </tr> + </tbody> +</table></pre> + +<h3 id="Nội_dung_file_CSS">Nội dung file CSS</h3> + +<pre class="brush: css">/* Shorthand classes for different perspective values */ +.pers250 { + perspective: 250px; + -webkit-perspective: 250px; +} + +.pers350 { + perspective: 350px; + -webkit-perspective: 350px; +} + +.pers500 { + perspective: 500px; + -webkit-perspective: 500px; +} + +/* Define the container div, the cube div, and a generic face */ + .container { + width: 200px; + height: 200px; + margin: 75px 0 0 75px; + border: none; +} + +.cube { + width: 100%; + height: 100%; + backface-visibility: visible; + perspective-origin: 150% 150%; + transform-style: preserve-3d; + -webkit-backface-visibility: visible; + -webkit-perspective-origin: 150% 150%; + -webkit-transform-style: preserve-3d; +} + +.face { + display: block; + position: absolute; + width: 100px; + height: 100px; + border: none; + line-height: 100px; + font-family: sans-serif; + font-size: 60px; + color: white; + text-align: center; +} + +/* Define each face based on direction */ +.front { + background: rgba(0, 0, 0, 0.3); + transform: translateZ(50px); + -webkit-transform: translateZ(50px); +} + +.back { + background: rgba(0, 255, 0, 1); + color: black; + transform: rotateY(180deg) translateZ(50px); + -webkit-transform: rotateY(180deg) translateZ(50px); +} + +.right { + background: rgba(196, 0, 0, 0.7); + transform: rotateY(90deg) translateZ(50px); + -webkit-transform: rotateY(90deg) translateZ(50px); +} + +.left { + background: rgba(0, 0, 196, 0.7); + transform: rotateY(-90deg) translateZ(50px); + -webkit-transform: rotateY(-90deg) translateZ(50px); +} + +.top { + background: rgba(196, 196, 0, 0.7); + transform: rotateX(90deg) translateZ(50px); + -webkit-transform: rotateX(90deg) translateZ(50px) +} + +.bottom { + background: rgba(196, 0, 196, 0.7); + transform: rotateX(-90deg) translateZ(50px); + -webkit-transform: rotateX(-90deg) translateZ(50px); +} + +/* Make the table a little nicer */ +th, p, td { + background-color: #EEEEEE; + padding: 10px; + font-family: sans-serif; + text-align: left; +}</pre> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{EmbedLiveSample('Example', 940, 460)}}</p> + +<h2 id="Chi_tiết_kỹ_thuật">Chi tiết kỹ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Specname('CSS Transforms 2', '#propdef-perspective', 'perspective')}}</td> + <td>{{Spec2('CSS Transforms 2')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Danh_sách_trình_duyệt_tương_thích">Danh sách trình duyệt tương thích</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td> + <p>12{{property_prefix('-webkit')}}{{CompatGeckoDesktop("10")}}<br> + 45</p> + </td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatVersionUnknown}}</td> + <td> + <p>{{CompatGeckoDesktop("10")}}{{property_prefix('-moz')}}<br> + {{CompatGeckoDesktop("16")}}<sup>[1]</sup></p> + </td> + <td>10</td> + <td>15{{property_prefix('-webkit')}}</td> + <td>{{CompatVersionUnknown}}{{property_prefix('-webkit')}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>3.0{{property_prefix('-webkit')}}</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("10")}}{{property_prefix('-moz')}}<br> + {{CompatGeckoMobile("16")}}<sup>[1]</sup></td> + <td>8.1</td> + <td>{{CompatVersionUnknown}}{{property_prefix('-webkit')}}</td> + <td>{{CompatVersionUnknown}}{{property_prefix('-webkit')}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] In addition to the unprefixed support, Gecko 45.0 {{geckoRelease("45.0")}} added support for a <code>-webkit</code> prefixed version of the property for web compatibility reasons behind the preference <code>layout.css.prefixes.webkit</code>, defaulting to <code>false</code>. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to <code>true</code>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms">Using CSS Transforms</a></li> +</ul> diff --git a/files/vi/web/css/transform-function/index.html b/files/vi/web/css/transform-function/index.html new file mode 100644 index 0000000000..2237c7c1fb --- /dev/null +++ b/files/vi/web/css/transform-function/index.html @@ -0,0 +1,160 @@ +--- +title: <transform-function> +slug: Web/CSS/transform-function +tags: + - CSS + - CSS Data Type + - CSS Transforms + - Layout + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/transform-function +--- +<div>{{CSSRef}}</div> + +<p>The <strong><code><transform-function></code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> <a href="/en-US/docs/Web/CSS/CSS_Types">data type</a> represents a transformation that affects an element's appearance. Transformation functions can rotate, resize, distort, or move an element in 2D or 3D space. It is used in the {{cssxref("transform")}} property.</p> + +<h2 id="Describing_transformations_mathematically">Describing transformations mathematically</h2> + +<p>Various coordinate models can be used to describe an HTML element's size and shape, as well as any transformations applied to it. The most common is the <a href="https://en.wikipedia.org/wiki/Cartesian_coordinate_system">Cartesian coordinate system</a>, although <a href="https://en.wikipedia.org/wiki/Homogeneous_coordinates">homogeneous coordinates</a> are also sometimes used.</p> + +<h3 id="Cartesian_coordinates"><a href="/@api/deki/files/5796/=coord_in_R2.png"><img src="/files/3438/coord_in_R2.png" style="float: right; width: 171px;"></a>Cartesian coordinates</h3> + +<p>In the Cartesian coordinate system, a two-dimensional point is described using two values: an x coordinate (abscissa) and a y coordinate (ordinate). This is represented by the vector notation <code>(x, y)</code>.</p> + +<p>In CSS (and most computer graphics), the origin <code>(0, 0)</code> represents the<em> top-left</em> corner of any element. Positive coordinates are down and to the right of the origin, while negative ones are up and to the left. Thus, a point that's 2 units to the right and 5 units down would be <code>(2, 5)</code>, while a point 3 units to the left and 12 units up would be <code>(-3, -12)</code>.</p> + +<h3 id="Transformation_functions">Transformation functions</h3> + +<p>Transformation functions alter the appearance of an element by manipulating the values of its coordinates. A linear transformation function is described using a 2×2 matrix, like this:</p> + +<p style="text-align: center;"><math> <mfenced> <mtable> <mtr><mtd><mi>a</mi></mtd><mtd><mi>c</mi></mtd></mtr> <mtr><mtd><mi>b</mi></mtd><mtd><mi>d</mi></mtd></mtr> </mtable> </mfenced> </math></p> + +<p>The function is applied to an element by using matrix multiplication. Thus, each coordinate changes based on the values in the matrix:</p> + +<p style="text-align: center;"><math> <mfenced> <mtable> <mtr><mtd><mi>a</mi></mtd><mtd><mi>c</mi></mtd></mtr> <mtr><mtd><mi>b</mi></mtd><mtd><mi>d</mi></mtd></mtr> </mtable> </mfenced> <mfenced> <mtable> <mtr><mtd><mi>x</mi></mtd></mtr><mtr><mtd><mi>y</mi></mtd></mtr> </mtable> </mfenced> <mo>=</mo> <mfenced> <mtable> <mtr> <mtd><mi>a</mi><mi>x</mi><mo>+</mo><mi>c</mi><mi>y</mi></mtd> </mtr> <mtr> <mtd><mi>b</mi><mi>x</mi><mo>+</mo><mi>d</mi><mi>y</mi></mtd> </mtr> </mtable> </mfenced> </math></p> + +<p>It is even possible to apply several transformations in a row:</p> + +<p style="text-align: center;"><math> <mfenced> <mtable> <mtr> <mtd><msub><mi>a</mi><mn>1</mn></msub></mtd> <mtd><msub><mi>c</mi><mn>1</mn></msub></mtd> </mtr> <mtr> <mtd><msub><mi>b</mi><mn>1</mn></msub></mtd> <mtd><msub><mi>d</mi><mn>1</mn></msub></mtd> </mtr> </mtable> </mfenced> <mfenced> <mtable> <mtr> <mtd><msub><mi>a</mi><mn>2</mn></msub></mtd> <mtd><msub><mi>c</mi><mn>2</mn></msub></mtd> </mtr> <mtr> <mtd><msub><mi>b</mi><mn>2</mn></msub></mtd> <mtd><msub><mi>d</mi><mn>2</mn></msub></mtd> </mtr> </mtable> </mfenced> <mo>=</mo> <mfenced> <mtable> <mtr> <mtd> <msub><mi>a</mi><mn>1</mn></msub> <msub><mi>a</mi><mn>2</mn></msub> <mo>+</mo> <msub><mi>c</mi><mn>1</mn></msub> <msub><mi>b</mi><mn>2</mn></msub> </mtd> <mtd> <msub><mi>a</mi><mn>1</mn></msub> <msub><mi>c</mi><mn>2</mn></msub> <mo>+</mo> <msub><mi>c</mi><mn>1</mn></msub> <msub><mi>d</mi><mn>2</mn></msub> </mtd> </mtr> <mtr> <mtd> <msub><mi>b</mi><mn>1</mn></msub> <msub><mi>a</mi><mn>2</mn></msub> <mo>+</mo> <msub><mi>d</mi><mn>1</mn></msub> <msub><mi>b</mi><mn>2</mn></msub> </mtd> <mtd> <msub><mi>b</mi><mn>1</mn></msub> <msub><mi>c</mi><mn>2</mn></msub> <mo>+</mo> <msub><mi>d</mi><mn>1</mn></msub> <msub><mi>d</mi><mn>2</mn></msub> </mtd> </mtr> </mtable> </mfenced> </math></p> + +<p>With this notation, it is possible to describe, and therefore compose, most common transformations: rotations, scaling, or skewing. (In fact, all transformations that are linear functions can be described.) Composite transformations are effectively applied in order from right to left.</p> + +<p>However, one major transformation is not linear, and therefore must be special-cased when using this notation: translation. The translation vector <code>(tx, ty)</code> must be expressed separately, as two additional parameters.</p> + +<div class="note"> +<p><strong>Note:</strong> Though trickier than Cartesian coordinates, <a class="external" href="https://en.wikipedia.org/wiki/Homogeneous_coordinates">homogeneous coordinates</a> in <a class="external" href="https://en.wikipedia.org/wiki/Projective_geometry">projective geometry</a> lead to 3×3 transformation matrices, and can simply express translations as linear functions.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<p>The <code><transform-function></code> data type is specified using one of the transformation functions listed below. Each function applies a geometric operation in either 2D or 3D.</p> + +<h3 id="Matrix_transformation">Matrix transformation</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/matrix">matrix()</a></code></dt> + <dd>Describes a homogeneous 2D transformation matrix.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/matrix3d">matrix3d()</a></code></dt> + <dd>Describes a 3D transformation as a 4×4 homogeneous matrix.</dd> +</dl> + +<h3 id="Perspective">Perspective</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/perspective">perspective()</a></code></dt> + <dd>Sets the distance between the user and the z=0 plane.</dd> +</dl> + +<h3 id="Rotation">Rotation</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/rotate">rotate()</a></code></dt> + <dd>Rotates an element around a fixed point on the 2D plane.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/rotate3d">rotate3d()</a></code></dt> + <dd>Rotates an element around a fixed axis in 3D space.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/rotateX">rotateX()</a></code></dt> + <dd>Rotates an element around the horizontal axis.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/rotateY">rotateY()</a></code></dt> + <dd>Rotates an element around the vertical axis.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/rotateZ">rotateZ()</a></code></dt> + <dd>Rotates an element around the z-axis.</dd> +</dl> + +<h3 id="Scaling_resizing">Scaling (resizing)</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/scale">scale()</a></code></dt> + <dd>Scales an element up or down on the 2D plane.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/scale3d">scale3d()</a></code></dt> + <dd>Scales an element up or down in 3D space.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/scaleX">scaleX()</a></code></dt> + <dd>Scales an element up or down horizontally.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/scaleY">scaleY()</a></code></dt> + <dd>Scales an element up or down vertically.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/scaleZ">scaleZ()</a></code></dt> + <dd>Scales an element up or down along the z-axis.</dd> +</dl> + +<h3 id="Skewing_distortion">Skewing (distortion)</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/skew">skew()</a></code></dt> + <dd>Skews an element on the 2D plane.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/skewX">skewX()</a></code></dt> + <dd>Skews an element in the horizontal direction.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/skewY">skewY()</a></code></dt> + <dd>Skews an element in the vertical direction.</dd> +</dl> + +<h3 id="Translation_moving">Translation (moving)</h3> + +<dl> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/translate">translate()</a></code></dt> + <dd>Translates an element on the 2D plane.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/translate3d">translate3d()</a></code></dt> + <dd>Translates an element in 3D space.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/translateX">translateX()</a></code></dt> + <dd>Translates an element horizontally.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/translateY">translateY()</a></code></dt> + <dd>Translates an element vertically.</dd> + <dt><code><a href="/en-US/docs/Web/CSS/transform-function/translateZ">translateZ()</a></code></dt> + <dd>Translates an element along the z-axis.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS Transforms 2', '#transform-functions', '<transform-function>')}}</td> + <td>{{Spec2('CSS Transforms 2')}}</td> + <td>Added 3D transform functions.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Transforms', '#transform-functions', '<transform-function>')}}</td> + <td>{{Spec2('CSS3 Transforms')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("css.types.transform-function")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>CSS {{cssxref("transform")}} property</li> +</ul> diff --git a/files/vi/web/css/transform-function/perspective()/index.html b/files/vi/web/css/transform-function/perspective()/index.html new file mode 100644 index 0000000000..a69e46e094 --- /dev/null +++ b/files/vi/web/css/transform-function/perspective()/index.html @@ -0,0 +1,153 @@ +--- +title: perspective() +slug: Web/CSS/transform-function/perspective() +translation_of: Web/CSS/transform-function/perspective() +--- +<div>{{CSSRef}}</div> + +<p>The <strong><code>perspective()</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> function defines a transformation that sets the distance between the user and the z=0 plane, the perspective from which the viewer would be if the 2-dimensional interface were 3-dimensional. Its result is a {{cssxref("<transform-function>")}} data type.</p> + +<div>{{EmbedInteractiveExample("pages/css/function-perspective.html")}}</div> + + + +<p>The <code>perspective()</code> transform function is part of the {{cssxref('transform')}} value applied on the element being transformed. This differs from the {{cssxref('perspective')}} and {{cssxref('perspective-origin')}} properties which are attached to the parent of a child transformed in 3-dimensional space.</p> + +<h2 id="Syntax">Syntax</h2> + +<p>The perspective distance used by <code>perspective()</code> is specified by a {{cssxref("<length>")}} value, which represents the distance between the user and the z=0 plane. The z=0 plane is the plane where everything appears in a 2-dimensional view, or the screen. A positive value makes the element appear closer to the user than the rest of the interface, a negative value farther. The greater the value, the further away the perspective of the user is.</p> + +<pre class="syntaxbox">perspective(d) +</pre> + +<h3 id="Values">Values</h3> + +<dl> + <dt><var>d</var></dt> + <dd>Is a {{cssxref("<length>")}} representing the distance from the user to the z=0 plane. If it is 0 or a negative value, no perspective transform is applied.</dd> +</dl> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Cartesian coordinates on ℝ<sup>2</sup></th> + <th scope="col">Homogeneous coordinates on ℝℙ<sup>2</sup></th> + <th scope="col">Cartesian coordinates on ℝ<sup>3</sup></th> + <th scope="col">Homogeneous coordinates on ℝℙ<sup>3</sup></th> + </tr> + </thead> + <tbody> + <tr> + <td colspan="2" rowspan="2"> + <p>This transformation applies to the 3D space and can't be represented on the plane.</p> + </td> + <td colspan="1" rowspan="2">This transformation is not a linear transformation in ℝ<sup>3</sup>, and can't be represented using a Cartesian-coordinate matrix.</td> + <td colspan="1" rowspan="2"><math> <mfenced><mtable><mtr>1<mtd>0</mtd><mtd>0</mtd><mtd>0</mtd></mtr><mtr>0<mtd>1</mtd><mtd>0</mtd><mtd>0</mtd></mtr><mtr><mtd>0</mtd><mtd>0</mtd><mtd>1</mtd><mtd>0</mtd></mtr><mtr><mtd>0</mtd><mtd>0</mtd><mtd><mo>−</mo>1<mo>/</mo>d</mtd><mtd>1</mtd></mtr></mtable> </mfenced> </math></td> + </tr> + </tbody> +</table> + +<h2 id="Examples">Examples</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p>Without perspective:</p> +<div class="no-perspective-box"> + <div class="face front">A</div> + <div class="face top">B</div> + <div class="face left">C</div> +</div> + +<p>With perspective (9cm):</p> +<div class="perspective-box-far"> + <div class="face front">A</div> + <div class="face top">B</div> + <div class="face left">C</div> +</div> + +<p>With perspective (4cm):</p> +<div class="perspective-box-closer"> + <div class="face front">A</div> + <div class="face top">B</div> + <div class="face left">C</div> +</div> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">.face { + position: absolute; + width: 100px; + height: 100px; + line-height: 100px; + font-size: 100px; + text-align: center; +} + +p + div { + width: 100px; + height: 100px; + transform-style: preserve-3d; + margin-left: 100px; +} +.no-perspective-box { + transform: rotateX(-15deg) rotateY(30deg); +} + +.perspective-box-far { + transform: perspective(9cm) rotateX(-15deg) rotateY(30deg); +} + +.perspective-box-closer { + transform: perspective(4cm) rotateX(-15deg) rotateY(30deg); +} + +.top { + background-color: skyblue; + transform: rotateX(90deg) translate3d(0, 0, 50px); +} + +.left { + background-color: pink; + transform: rotateY(-90deg) translate3d(0, 0, 50px); +} + +.front { + background-color: limegreen; + transform: translate3d(0, 0, 50px); +} +</pre> + +<h3 id="Result">Result</h3> + +<p>{{ EmbedLiveSample('Examples', '250', '350') }}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS Transforms 2", "#funcdef-perspective", "perspective()")}}</td> + <td>{{Spec2("CSS Transforms 2")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>Please see the <code><a href="/en-US/docs/Web/CSS/transform-function#Browser_compatibility"><transform-function></a></code> data type for compatibility info.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{cssxref("transform")}}</li> + <li>{{cssxref("<transform-function>")}}</li> +</ul> diff --git a/files/vi/web/css/universal_selectors/index.html b/files/vi/web/css/universal_selectors/index.html new file mode 100644 index 0000000000..da87129972 --- /dev/null +++ b/files/vi/web/css/universal_selectors/index.html @@ -0,0 +1,101 @@ +--- +title: Universal selectors +slug: Web/CSS/Universal_selectors +translation_of: Web/CSS/Universal_selectors +--- +<div>{{CSSRef}}</div> + +<p><strong>Ký hiệu chọn toàn bộ</strong> của CSS (<code>*</code>) sẽ chọn mọi đối tượng thuộc bất kỳ loại nào.</p> + +<pre class="brush: css no-line-numbers">/* Chọn tất cả đối tượng */ +* { + color: green; +}</pre> + +<p>Bắt đầu từ CSS3, dấu sao * có thể được dùng kết hợp cùng với {{cssxref("CSS_Namespaces", "namespaces")}}:</p> + +<ul> + <li><code>ns|*</code> - khớp với mọi đối tượng trong namespace <em>ns</em></li> + <li><code>*|*</code> - khớp với mọi đối tượng</li> + <li><code>|*</code> - khớp với mọi đối tượng không được khai báo namespace</li> +</ul> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">* { <em>các thuộc tính</em> }</pre> + +<p>Dấu * không bắt buộc đối với những bộ chọn đơn giản. Ví dụ, <code>*.warning</code> và <code>.warning</code> tương đương nhau.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">* [lang^=en] { + color: green; +} + +*.warning { + color: red; +} + +*#maincontent { + border: 1px solid blue; +} + +.floating { + float: left +} + +/* tự động giãn cách đối tượng liền kề sau một đối tượng float */ +.floating + * { + clear: left; +} +</pre> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p class="warning"> + <span lang="en-us">A green span</span> in a red paragraph.</span> +</p> +<p id="maincontent" lang="en-gb"> + <span class="warning">A red span</span> in a green paragraph.</span> +</p></pre> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{EmbedLiveSample('Examples')}}</p> + +<h2 id="Quy_cách">Quy cách</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Quy cách</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS4 Selectors', '#the-universal-selector', 'universal selector')}}</td> + <td>{{Spec2('CSS4 Selectors')}}</td> + <td>Không đổi</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Selectors', '#universal-selector', 'universal selector')}}</td> + <td>{{Spec2('CSS3 Selectors')}}</td> + <td>Defines behavior regarding namespaces and adds hint that omitting the selector is allowed within pseudo-elements</td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'selector.html#universal-selector', 'universal selector')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td>Định nghĩa ban đầu</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + + + +<p>{{Compat("css.selectors.universal")}}</p> diff --git a/files/vi/web/events/index.html b/files/vi/web/events/index.html new file mode 100644 index 0000000000..9fffbd92ed --- /dev/null +++ b/files/vi/web/events/index.html @@ -0,0 +1,3078 @@ +--- +title: Event reference +slug: Web/Events +tags: + - Event + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/Events +--- +<p>Sự kiện DOM được gửi để thông báo những điều thú vị đã diễn ra trong code. Mỗi sự kiện được đại diện bởi một đối tượng dựa trên interface {{DOMxRef("Event")}}, và có thể có các trường và / hoặc chức năng tùy chỉnh bổ sung được sử dụng để có thêm thông tin về những gì đã xảy ra. Sự kiện có thể đại diện cho mọi thứ, từ tương tác người dùng cơ bản đến thông báo tự động về những điều xảy ra trong mô hình kết xuất.</p> + +<p>Bài viết này cung cấp một danh sách các sự kiện có thể được gửi; một số là sự kiện tiêu chuẩn được định nghĩa trong những đặc điểm chính thức, trong khi những sự kiện khác được sử dụng dành riêng cho một số trình duyệt ; ví dụ, Các sự kiện dành riêng cho Mozilla được liệt kê để các tiện ích bổ sung (add-on) có thể sử dụng chúng để tương tác với trình duyệt.</p> + +<h2 id="Danh_mục_phổ_biến_nhất">Danh mục phổ biến nhất</h2> + +<table class="standard-table"> + <caption> + <h3 id="Sự_kiện_tài_nguyên">Sự kiện tài nguyên</h3> + </caption> + <thead> + <tr> + <th scope="col">Tên sự kiện</th> + <th scope="col">Bắt đầu khi</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("cached")}}</td> + <td>Các tài nguyên được liệt kê trong tệp kê khai đã được tải xuống và ứng dụng hiện được lưu trữ.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>Một tài nguyên không thể tải được.</td> + </tr> + <tr> + <td>{{Event("abort")}}</td> + <td> + <p>Việc tải tài nguyên đã bị hủy bỏ</p> + </td> + </tr> + <tr> + <td>{{Event("load")}}</td> + <td>Một tài nguyên và tài nguyên phụ thuộc của nó đã được tải xong..</td> + </tr> + <tr> + <td>{{Event("beforeunload")}}</td> + <td>Cửa sổ, tài liệu và tài nguyên của nó sắp được dỡ bỏ.</td> + </tr> + <tr> + <td>{{Event("unload")}}</td> + <td>Tài liệu hoặc tài nguyên phụ thuộc đang được dỡ bỏ.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Sự_kiện_mạng">Sự kiện mạng</h3> + </caption> + <thead> + <tr> + <th scope="col">Tên sự kiện</th> + <th scope="col">Bắt đầu khi</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("online")}}</td> + <td>Trình duyệt đã giành được quyền truy cập vào mạng</td> + </tr> + <tr> + <td>{{Event("offline")}}</td> + <td>Trình duyệt đã mất quyền truy cập vào mạng</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Focus_events">Focus events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("focus")}}</td> + <td>An element has received focus (does not bubble).</td> + </tr> + <tr> + <td>{{Event("blur")}}</td> + <td>An element has lost focus (does not bubble).</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="WebSocket_events">WebSocket events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/open_websocket">open</a></code></td> + <td>A WebSocket connection has been established.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_websocket">message</a></code></td> + <td>A message is received through a WebSocket.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/close_websocket">close</a></code></td> + <td>A WebSocket connection has been closed.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Session_History_events">Session History events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("pagehide")}}</td> + <td>A session history entry is being traversed from.</td> + </tr> + <tr> + <td>{{Event("pageshow")}}</td> + <td>A session history entry is being traversed to.</td> + </tr> + <tr> + <td>{{Event("popstate")}}</td> + <td>A session history entry is being navigated to (in certain cases).</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="CSS_Animation_events">CSS Animation events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("animationstart")}}</td> + <td>A <a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_animations">CSS animation</a> has started.</td> + </tr> + <tr> + <td>{{Event("animationend")}}</td> + <td>A <a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_animations">CSS animation</a> has completed.</td> + </tr> + <tr> + <td>{{Event("animationiteration")}}</td> + <td>A <a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_animations">CSS animation</a> is repeated.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="CSS_Transition_events">CSS Transition events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("transitionstart")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has actually started (fired after any delay).</td> + </tr> + <tr> + <td>{{Event("transitioncancel")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has been cancelled.</td> + </tr> + <tr> + <td>{{Event("transitionend")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has completed.</td> + </tr> + <tr> + <td>{{Event("transitionrun")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has begun running (fired before any delay starts).</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Form_events">Form events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("reset")}}</td> + <td>The reset button is pressed</td> + </tr> + <tr> + <td>{{Event("submit")}}</td> + <td>The submit button is pressed</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Printing_events">Printing events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("beforeprint")}}</td> + <td>The print dialog is opened</td> + </tr> + <tr> + <td>{{Event("afterprint")}}</td> + <td>The print dialog is closed</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Text_Composition_events">Text Composition events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("compositionstart")}}</td> + <td>The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).</td> + </tr> + <tr> + <td>{{Event("compositionupdate")}}</td> + <td>A character is added to a passage of text being composed.</td> + </tr> + <tr> + <td>{{Event("compositionend")}}</td> + <td>The composition of a passage of text has been completed or canceled.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="View_events">View events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("fullscreenchange")}}</td> + <td>An element was turned to fullscreen mode or back to normal mode.</td> + </tr> + <tr> + <td>{{Event("fullscreenerror")}}</td> + <td>It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{Event("resize")}}</td> + <td>The document view has been resized.</td> + </tr> + <tr> + <td>{{Event("scroll")}}</td> + <td>The document view or an element has been scrolled.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Clipboard_events">Clipboard events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("cut")}}</td> + <td>The selection has been cut and copied to the clipboard</td> + </tr> + <tr> + <td>{{Event("copy")}}</td> + <td>The selection has been copied to the clipboard</td> + </tr> + <tr> + <td>{{Event("paste")}}</td> + <td>The item from the clipboard has been pasted</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Keyboard_events">Keyboard events</h3> + </caption> + <tbody> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + <tr> + <td>{{Event("keydown")}}</td> + <td>ANY key is pressed</td> + </tr> + <tr> + <td>{{Event("keypress")}}</td> + <td>ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)</td> + </tr> + <tr> + <td>{{Event("keyup")}}</td> + <td>ANY key is released</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Mouse_events">Mouse events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("auxclick")}}</td> + <td>A pointing device button (ANY non-primary button) has been pressed and released on an element.</td> + </tr> + <tr> + <td>{{Event("click")}}</td> + <td>A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.</td> + </tr> + <tr> + <td>{{Event("contextmenu")}}</td> + <td>The right button of the mouse is clicked (before the context menu is displayed).</td> + </tr> + <tr> + <td>{{Event("dblclick")}}</td> + <td>A pointing device button is clicked twice on an element.</td> + </tr> + <tr> + <td>{{Event("mousedown")}}</td> + <td>A pointing device button is pressed on an element.</td> + </tr> + <tr> + <td>{{Event("mouseenter")}}</td> + <td>A pointing device is moved onto the element that has the listener attached.</td> + </tr> + <tr> + <td>{{Event("mouseleave")}}</td> + <td>A pointing device is moved off the element that has the listener attached.</td> + </tr> + <tr> + <td>{{Event("mousemove")}}</td> + <td>A pointing device is moved over an element. (Fired continously as the mouse moves.)</td> + </tr> + <tr> + <td>{{Event("mouseover")}}</td> + <td>A pointing device is moved onto the element that has the listener attached or onto one of its children.</td> + </tr> + <tr> + <td>{{Event("mouseout")}}</td> + <td>A pointing device is moved off the element that has the listener attached or off one of its children.</td> + </tr> + <tr> + <td>{{Event("mouseup")}}</td> + <td>A pointing device button is released over an element.</td> + </tr> + <tr> + <td>{{Event("pointerlockchange")}}</td> + <td>The pointer was locked or released.</td> + </tr> + <tr> + <td>{{Event("pointerlockerror")}}</td> + <td>It was impossible to lock the pointer for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{Event("select")}}</td> + <td>Some text is being selected.</td> + </tr> + <tr> + <td>{{Event("wheel")}}</td> + <td>A wheel button of a pointing device is rotated in any direction.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption> + <h3 id="Drag_Drop_events">Drag & Drop events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("drag")}}</td> + <td>An element or text selection is being dragged (Fired continuously every 350ms).</td> + </tr> + <tr> + <td>{{Event("dragend")}}</td> + <td>A drag operation is being ended (by releasing a mouse button or hitting the escape key).</td> + </tr> + <tr> + <td>{{Event("dragenter")}}</td> + <td>A dragged element or text selection enters a valid drop target.</td> + </tr> + <tr> + <td>{{Event("dragstart")}}</td> + <td>The user starts dragging an element or text selection.</td> + </tr> + <tr> + <td>{{Event("dragleave")}}</td> + <td>A dragged element or text selection leaves a valid drop target.</td> + </tr> + <tr> + <td>{{Event("dragover")}}</td> + <td>An element or text selection is being dragged over a valid drop target. (Fired continuously every 350ms.)</td> + </tr> + <tr> + <td>{{Event("drop")}}</td> + <td>An element is dropped on a valid drop target.</td> + </tr> + </tbody> +</table> + +<div style="overflow: auto;"> +<table class="standard-table"> + <caption> + <h3 id="Media_events">Media events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("audioprocess")}}</td> + <td>The input buffer of a {{DOMxRef("ScriptProcessorNode")}} is ready to be processed.</td> + </tr> + <tr> + <td>{{Event("canplay")}}</td> + <td>The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.</td> + </tr> + <tr> + <td>{{Event("canplaythrough")}}</td> + <td>The browser estimates it can play the media up to its end without stopping for content buffering.</td> + </tr> + <tr> + <td>{{Event("complete")}}</td> + <td>The rendering of an {{DOMxRef("OfflineAudioContext")}} is terminated.</td> + </tr> + <tr> + <td>{{Event("durationchange")}}</td> + <td>The <code>duration</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{Event("emptied")}}</td> + <td>The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <a href="/en-US/docs/XPCOM_Interface_Reference/NsIDOMHTMLMediaElement" rel="internal"><code>load()</code></a> method is called to reload it.</td> + </tr> + <tr> + <td>{{Event("ended")}}</td> + <td>Playback has stopped because the end of the media was reached.</td> + </tr> + <tr> + <td>{{Event("loadeddata")}}</td> + <td>The first frame of the media has finished loading.</td> + </tr> + <tr> + <td>{{Event("loadedmetadata")}}</td> + <td>The metadata has been loaded.</td> + </tr> + <tr> + <td>{{Event("pause")}}</td> + <td>Playback has been paused.</td> + </tr> + <tr> + <td>{{Event("play")}}</td> + <td>Playback has begun.</td> + </tr> + <tr> + <td>{{Event("playing")}}</td> + <td>Playback is ready to start after having been paused or delayed due to lack of data.</td> + </tr> + <tr> + <td>{{Event("ratechange")}}</td> + <td>The playback rate has changed.</td> + </tr> + <tr> + <td>{{Event("seeked")}}</td> + <td>A <em>seek</em> operation completed.</td> + </tr> + <tr> + <td>{{Event("seeking")}}</td> + <td>A <em>seek</em> operation began.</td> + </tr> + <tr> + <td>{{Event("stalled")}}</td> + <td>The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.</td> + </tr> + <tr> + <td>{{Event("suspend")}}</td> + <td>Media data loading has been suspended.</td> + </tr> + <tr> + <td>{{Event("timeupdate")}}</td> + <td>The time indicated by the <code>currentTime</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{Event("volumechange")}}</td> + <td>The volume has changed.</td> + </tr> + <tr> + <td>{{Event("waiting")}}</td> + <td>Playback has stopped because of a temporary lack of data.</td> + </tr> + </tbody> +</table> +</div> + +<table class="standard-table"> + <caption> + <h3 id="Progress_events">Progress events</h3> + </caption> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Fired When</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/abort_(ProgressEvent)">abort</a></code></td> + <td>Progression has been terminated (not due to an error).</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>Progression has failed.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/load_(ProgressEvent)">load</a></code></td> + <td>Progression has been successful.</td> + </tr> + <tr> + <td>{{Event("loadend")}}</td> + <td>Progress has stopped (after "error", "abort" or "load" have been dispatched).</td> + </tr> + <tr> + <td>{{Event("loadstart")}}</td> + <td>Progress has begun.</td> + </tr> + <tr> + <td>{{Event("progress")}}</td> + <td>In progress.</td> + </tr> + <tr> + <td>{{Event("timeout")}}</td> + <td>Progression is terminated due to preset time expiring.</td> + </tr> + </tbody> +</table> + +<h3 id="Storage_events">Storage events</h3> + +<p>{{Event("change")}} (see {{anch("Non-standard events")}})<br> + {{Event("storage")}}</p> + +<h3 id="Update_events">Update events</h3> + +<p>{{Event("checking")}}<br> + {{Event("downloading")}}<br> + {{Event("error")}}<br> + {{Event("noupdate")}}<br> + {{Event("obsolete")}}<br> + {{Event("updateready")}}</p> + +<h3 id="Value_change_events">Value change events</h3> + +<p>{{Event("broadcast")}}<br> + {{Event("CheckboxStateChange")}}<br> + {{Event("hashchange")}}<br> + {{Event("input")}}<br> + {{Event("RadioStateChange")}}<br> + {{Event("readystatechange")}}<br> + {{Event("ValueChange")}}</p> + +<h3 id="Uncategorized_events">Uncategorized events</h3> + +<p>{{Event("invalid")}}<br> + {{Event("localized")}}<br> + <code><a href="/en-US/docs/Web/Reference/Events/message_webworker">message</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/message_webmessaging">message</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/message_serversentevents">message</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/open_serversentevents">open</a></code><br> + {{Event("show")}}</p> + +<h2 id="Less_common_and_non-standard_events">Less common and non-standard events</h2> + +<h3 id="Abortable_Fetch_events">Abortable Fetch events</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Event name</th> + <th scope="col">Fired when</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("abort_(dom_abort_api)", "abort")}}</td> + <td>A DOM request is aborted, i.e. using {{DOMxRef("AbortController.abort()")}}.</td> + </tr> + </tbody> +</table> + +<h3 id="WebVR_events">WebVR events</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Event name</th> + <th scope="col">Fired when</th> + </tr> + <tr> + <td>{{Event("vrdisplayactivate")}}</td> + <td>When a VR display is able to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.</td> + </tr> + <tr> + <td>{{Event("vrdisplayblur")}}</td> + <td>when presentation to a {{DOMxRef("VRDisplay")}} has been paused for some reason by the browser, OS, or VR hardware — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.</td> + </tr> + <tr> + <td>{{Event("vrdisplayconnect")}}</td> + <td>when a compatible {{DOMxRef("VRDisplay")}} is connected to the computer.</td> + </tr> + <tr> + <td>{{Event("vrdisplaydeactivate")}}</td> + <td>When a {{DOMxRef("VRDisplay")}} can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.</td> + </tr> + <tr> + <td>{{Event("vrdisplaydisconnect")}}</td> + <td>When a compatible {{DOMxRef("VRDisplay")}} is disconnected from the computer.</td> + </tr> + <tr> + <td>{{Event("vrdisplayfocus")}}</td> + <td>When presentation to a {{DOMxRef("VRDisplay")}} has resumed after being blurred.</td> + </tr> + <tr> + <td>{{Event("vrdisplaypresentchange")}}</td> + <td>The presenting state of a {{DOMxRef("VRDisplay")}} changes — i.e. goes from presenting to not presenting, or vice versa.</td> + </tr> + </thead> +</table> + +<h3 id="SVG_events">SVG events</h3> + +<p>{{Event("SVGAbort")}}<br> + {{Event("SVGError")}}<br> + {{Event("SVGLoad")}}<br> + {{Event("SVGResize")}}<br> + {{Event("SVGScroll")}}<br> + {{Event("SVGUnload")}}<br> + {{Event("SVGZoom")}}</p> + +<h3 id="Database_events">Database events</h3> + +<p><code><a href="/en-US/docs/Web/Reference/Events/abort_indexedDB">abort</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/blocked_indexedDB">blocked</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/complete_indexedDB">complete</a></code><br> + {{Event("error")}} (<a href="/en-US/docs/Web/Reference/Events/error">link</a>)<br> + <code><a href="/en-US/docs/Web/Reference/Events/success_indexedDB">success</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/upgradeneeded_indexedDB">upgradeneeded</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/versionchange_indexedDB">versionchange</a></code></p> + +<h3 id="Notification_events">Notification events</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/AlertActive">AlertActive</a><br> + <a href="/en-US/docs/Web/Reference/Events/AlertClose">AlertClose</a></p> + +<h3 id="CSS_events">CSS events</h3> + +<ul> + <li><a href="/en-US/docs/Web/Reference/Events/CssRuleViewChanged">CssRuleViewChanged</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/CssRuleViewCSSLinkClicked">CssRuleViewCSSLinkClicked</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">CssRuleViewRefreshed</a></li> +</ul> + +<h3 id="Script_events"><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">Script events</a></h3> + +<p><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">{{Event("afterscriptexecute")}}<br> + {{Event("beforescriptexecute")}}</a></p> + +<h3 id="Menu_events"><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">Menu events</a></h3> + +<p><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">{{Event("DOMMenuItemActive")}}<br> + {{Event("DOMMenuItemInactive")}}</a></p> + +<h3 id="Window_events"><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">Window events</a></h3> + +<ul> + <li><a href="/en-US/docs/Web/Reference/Events/close_event">close</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/DOMTitleChanged">DOMTitleChanged</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/DOMWindowClose">DOMWindowClose</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/SSWindowClosing">SSWindowClosing</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/DOMWindowCreated">DOMWindowCreated</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/SSWindowStateBusy">SSWindowStateBusy</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/SSWindowStateReady">SSWindowStateReady</a></li> +</ul> + +<h3 id="Document_events">Document events</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/DOMLinkAdded">DOMLinkAdded</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMLinkRemoved">DOMLinkRemoved</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMMetaAdded">DOMMetaAdded</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMMetaRemoved">DOMMetaRemoved</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMModalDialogClosed">DOMModalDialogClosed</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMWillOpenModalDialog">DOMWillOpenModalDialog</a></p> + +<h3 id="Popup_events">Popup events</h3> + +<p>{{Event("popuphidden")}}<br> + {{Event("popuphiding")}}<br> + {{Event("popupshowing")}}<br> + {{Event("popupshown")}}<br> + <a href="/en-US/docs/Web/Reference/Events/DOMPopupBlocked">DOMPopupBlocked</a></p> + +<h3 id="Tab_events">Tab events</h3> + +<ul> + <li><a href="/en-US/docs/Web/Reference/Events/TabClose">TabClose</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/TabHide">TabHide</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/TabOpen">TabOpen</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/TabPinned">TabPinned</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/TabSelect">TabSelect</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/TabShow">TabShow</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/TabUnpinned">TabUnpinned</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/SSTabClosing">SSTabClosing</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/SSTabRestored">SSTabRestored</a></li> + <li><a href="/en-US/docs/Web/Reference/Events/SSTabRestoring">SSTabRestoring</a></li> + <li>{{Event("visibilitychange")}}</li> +</ul> + +<h3 id="Battery_events">Battery events</h3> + +<p>{{Event("chargingchange")}}<br> + {{Event("chargingtimechange")}}<br> + {{Event("dischargingtimechange")}}<br> + {{Event("levelchange")}}</p> + +<h3 id="Call_events">Call events</h3> + +<p>{{Event("alerting")}}<br> + {{Event("busy")}}<br> + {{Event("callschanged")}}<br> + {{Event("cfstatechange")}}<br> + {{Event("connected")}}<br> + {{Event("connecting")}}<br> + {{Event("dialing")}}<br> + {{Event("disconnected")}}<br> + {{Event("disconnecting")}}<br> + {{Event("error_(Telephony)","error")}}<br> + {{Event("held")}}, {{Event("holding")}}<br> + {{Event("incoming")}}<br> + {{Event("resuming")}}<br> + {{Event("statechange")}}<br> + {{Event("voicechange")}}</p> + +<h3 id="Sensor_events">Sensor events</h3> + +<p>{{Event("compassneedscalibration")}}<br> + {{Event("devicelight")}}<br> + {{Event("devicemotion")}}<br> + {{Event("deviceorientation")}}<br> + {{Event("deviceproximity")}}<br> + {{Event("MozOrientation")}}<br> + {{Event("orientationchange")}}<br> + {{Event("userproximity")}}</p> + +<h3 id="Smartcard_events">Smartcard events</h3> + +<p>{{Event("icccardlockerror")}}<br> + {{Event("iccinfochange")}}<br> + {{Event("smartcard-insert")}}<br> + {{Event("smartcard-remove")}}<br> + {{Event("stkcommand")}}<br> + {{Event("stksessionend")}}<br> + {{Event("cardstatechange")}}</p> + +<h3 id="SMS_and_USSD_events">SMS and USSD events</h3> + +<p>{{Event("delivered")}}<br> + {{Event("received")}}<br> + {{Event("sent")}}<br> + {{Event("ussdreceived")}}</p> + +<h3 id="Frame_events">Frame events</h3> + +<p>{{Event("mozbrowserclose")}}<br> + {{Event("mozbrowsercontextmenu")}}<br> + {{Event("mozbrowsererror")}}<br> + {{Event("mozbrowsericonchange")}}<br> + {{Event("mozbrowserlocationchange")}}<br> + {{Event("mozbrowserloadend")}}<br> + {{Event("mozbrowserloadstart")}}<br> + {{Event("mozbrowseropenwindow")}}<br> + {{Event("mozbrowsersecuritychange")}}<br> + {{Event("mozbrowsershowmodalprompt")}} (<a href="/en-US/docs/Web/Reference/Events/mozbrowsershowmodalprompt">link</a>)<br> + {{Event("mozbrowsertitlechange")}}<br> + <a href="/en-US/docs/Web/Reference/Events/DOMFrameContentLoaded">DOMFrameContentLoaded</a></p> + +<h3 id="DOM_mutation_events">DOM mutation events</h3> + +<p><code><a href="/en-US/docs/DOM/Mutation_events">DOMAttributeNameChanged</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMAttrModified</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMCharacterDataModified</a></code><br> + {{Event("DOMContentLoaded")}}<br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMElementNameChanged</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInserted</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInsertedIntoDocument</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemoved</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemovedFromDocument</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMSubtreeModified</a></code></p> + +<h3 id="Touch_events">Touch events</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/MozEdgeUIGesture">MozEdgeUIGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozMagnifyGesture">MozMagnifyGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureStart">MozMagnifyGestureStart</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureUpdate">MozMagnifyGestureUpdate</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozPressTapGesture">MozPressTapGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozRotateGesture">MozRotateGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozRotateGestureStart">MozRotateGestureStart</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozRotateGestureUpdate">MozRotateGestureUpdate</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozSwipeGesture">MozSwipeGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozTapGesture">MozTapGesture</a><br> + <a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchDown</a><br> + <a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchMove</a><br> + <a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchUp</a><br> + {{Event("touchcancel")}}<br> + {{Event("touchend")}}<br> + {{Event("touchenter")}}<br> + {{Event("touchleave")}}<br> + {{Event("touchmove")}}<br> + {{Event("touchstart")}}</p> + +<h3 id="Pointer_events">Pointer events</h3> + +<p>{{Event("pointerover")}}<br> + {{Event("pointerenter")}}<br> + {{Event("pointerdown")}}<br> + {{Event("pointermove")}}<br> + {{Event("pointerup")}}<br> + {{Event("pointercancel")}}<br> + {{Event("pointerout")}}<br> + {{Event("pointerleave")}}<br> + {{Event("gotpointercapture")}}<br> + {{Event("lostpointercapture")}}</p> + +<h2 id="Standard_events">Standard events</h2> + +<p>These events are defined in official Web specifications, and should be common across browsers. Each event is listed along with the interface representing the object sent to recipients of the event (so you can find information about what data is provided with each event) as well as a link to the specification or specifications that define the event.</p> + +<div style="overflow: auto;"> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Event Type</th> + <th scope="col">Specification</th> + <th scope="col">Fired when...</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("abort")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-abort" style="white-space: nowrap;">DOM L3</a></td> + <td>The loading of a resource has been aborted.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/abort_(ProgressEvent)">abort</a></code></td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/progress-events/">Progress</a> and <a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-abort">XMLHttpRequest</a></td> + <td>Progression has been terminated (not due to an error).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/abort_indexedDB">abort</a></code></td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/IndexedDB/#database-interface">IndexedDB</a></td> + <td>A transaction has been aborted.</td> + </tr> + <tr> + <td>{{Event("afterprint")}}{{gecko_minversion_inline("6")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/html5/webappapis.html#printing">HTML5</a></td> + <td>The associated document has started printing or the print preview has been closed.</td> + </tr> + <tr> + <td>{{Event("animationend")}}</td> + <td>{{DOMxRef("AnimationEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/css3-animations/#animation-events" style="white-space: nowrap;">CSS Animations</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_animations">CSS animation</a> has completed.</td> + </tr> + <tr> + <td>{{Event("animationiteration")}}</td> + <td>{{DOMxRef("AnimationEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/css3-animations/#animation-events" style="white-space: nowrap;">CSS Animations</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_animations">CSS animation</a> is repeated.</td> + </tr> + <tr> + <td>{{Event("animationstart")}}</td> + <td>{{DOMxRef("AnimationEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/css3-animations/#animation-events" style="white-space: nowrap;">CSS Animations</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_animations">CSS animation</a> has started.</td> + </tr> + <tr> + <td>{{Event("appinstalled")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="/en-US/docs/Web/Manifest" style="white-space: nowrap;">Web App Manifest</a></td> + <td>A web application is successfully installed as a <a href="https://developer.mozilla.org/en-US/Apps/Progressive">progressive web app</a>.</td> + </tr> + <tr> + <td>{{Event("audioprocess")}}</td> + <td>{{DOMxRef("AudioProcessingEvent")}} {{Deprecated_Inline}}</td> + <td>{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}</td> + <td>The input buffer of a {{DOMxRef("ScriptProcessorNode")}} is ready to be processed.</td> + </tr> + <tr> + <td>{{Event("audioend")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The user agent has finished capturing audio for speech recognition.</td> + </tr> + <tr> + <td>{{Event("audiostart")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The user agent has started to capture audio for speech recognition.</td> + </tr> + <tr> + <td>{{Event("beforeprint")}} {{gecko_minversion_inline("6")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/html5/webappapis.html#printing">HTML5</a></td> + <td>The associated document is about to be printed or previewed for printing.</td> + </tr> + <tr> + <td>{{Event("beforeunload")}}</td> + <td>{{DOMxRef("BeforeUnloadEvent")}}</td> + <td><a href="http://www.w3.org/TR/html5/browsers.html#unloading-documents">HTML5</a></td> + <td>The window, the document and its resources are about to be unloaded.</td> + </tr> + <tr> + <td>{{Event("beginEvent")}}</td> + <td>{{DOMxRef("TimeEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>A <a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SMIL</a> animation element begins.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/blocked_indexedDB">blocked</a></code></td> + <td></td> + <td><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>An open connection to a database is blocking a <code>versionchange</code> transaction on the same database.</td> + </tr> + <tr> + <td>{{Event("blur")}}</td> + <td>{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-blur" style="white-space: nowrap;">DOM L3</a></td> + <td>An element has lost focus (does not bubble).</td> + </tr> + <tr> + <td>{{Event("boundary")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechSynthesisEvent")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The spoken utterance reaches a word or sentence boundary</td> + </tr> + <tr> + <td>{{Event("cached")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The resources listed in the manifest have been downloaded, and the application is now cached.</td> + </tr> + <tr> + <td>{{Event("canplay")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-canplay" style="white-space: nowrap;">HTML5 media</a></td> + <td>The user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.</td> + </tr> + <tr> + <td>{{Event("canplaythrough")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-canplaythrough" style="white-space: nowrap;">HTML5 media</a></td> + <td>The user agent can play the media up to its end without having to stop for further buffering of content.</td> + </tr> + <tr> + <td>{{Event("change")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM L2</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#event-input-change">HTML5</a></td> + <td>The <code>change</code> event is fired for {{HTMLElement("input")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}} elements when a change to the element's value is committed by the user.</td> + </tr> + <tr> + <td>{{Event("chargingchange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html" style="white-space: nowrap;">Battery status</a></td> + <td>The battery begins or stops charging.</td> + </tr> + <tr> + <td>{{Event("chargingtimechange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html" style="white-space: nowrap;">Battery status</a></td> + <td>The <code>chargingTime</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{Event("checking")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The user agent is checking for an update, or attempting to download the cache manifest for the first time.</td> + </tr> + <tr> + <td>{{Event("click")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-click" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device button has been pressed and released on an element.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/close_websocket">close</a></code></td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A WebSocket connection has been closed.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/complete_indexedDB">complete</a></code></td> + <td></td> + <td><a href="http://www.w3.org/TR/IndexedDB/#transaction">IndexedDB</a></td> + <td>A transaction successfully completed.</td> + </tr> + <tr> + <td>{{Event("complete")}}</td> + <td>{{DOMxRef("OfflineAudioCompletionEvent")}} {{Deprecated_Inline}}</td> + <td>{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}</td> + <td>The rendering of an {{DOMxRef("OfflineAudioContext")}} is terminated.</td> + </tr> + <tr> + <td>{{Event("compositionend")}}{{gecko_minversion_inline("9")}}</td> + <td>{{DOMxRef("CompositionEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-compositionend" style="white-space: nowrap;">DOM L3</a></td> + <td>The composition of a passage of text has been completed or canceled.</td> + </tr> + <tr> + <td>{{Event("compositionstart")}}{{gecko_minversion_inline("9")}}</td> + <td>{{DOMxRef("CompositionEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-compositionstart" style="white-space: nowrap;">DOM L3</a></td> + <td>The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).</td> + </tr> + <tr> + <td>{{Event("compositionupdate")}}{{gecko_minversion_inline("9")}}</td> + <td>{{DOMxRef("CompositionEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-compositionupdate" style="white-space: nowrap;">DOM L3</a></td> + <td>A character is added to a passage of text being composed.</td> + </tr> + <tr> + <td>{{Event("contextmenu")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="https://html.spec.whatwg.org/multipage/forms.html#context-menus">HTML5</a></td> + <td>The right button of the mouse is clicked (before the context menu is displayed).</td> + </tr> + <tr> + <td>{{Event("copy")}}</td> + <td>{{DOMxRef("ClipboardEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/clipboard-apis/#copy-event">Clipboard</a></td> + <td>The text selection has been added to the clipboard.</td> + </tr> + <tr> + <td>{{Event("cut")}}</td> + <td>{{DOMxRef("ClipboardEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/clipboard-apis/#cut-event">Clipboard</a></td> + <td>The text selection has been removed from the document and added to the clipboard.</td> + </tr> + <tr> + <td>{{Event("dblclick")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-dblclick" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device button is clicked twice on an element.</td> + </tr> + <tr> + <td>{{Event("devicechange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName("Media Capture")}}</td> + <td>A media device such as a camera, microphone, or speaker is connected or removed from the system.</td> + </tr> + <tr> + <td>{{Event("devicelight")}}</td> + <td>{{DOMxRef("DeviceLightEvent")}} {{Experimental_Inline}}</td> + <td><a class="external" href="http://dvcs.w3.org/hg/dap/raw-file/tip/light/Overview.html" lang="en" title="The definition of 'Ambient Light Events' in that specification.">Ambient Light Events</a></td> + <td>Fresh data is available from a light sensor.</td> + </tr> + <tr> + <td>{{Event("devicemotion")}}</td> + <td>{{DOMxRef("DeviceMotionEvent")}} {{Experimental_Inline}}</td> + <td><a class="external" href="http://dev.w3.org/geo/api/spec-source-orientation.html" lang="en" title="The 'Device Orientation Events' specification">Device Orientation Events</a></td> + <td>Fresh data is available from a motion sensor.</td> + </tr> + <tr> + <td>{{Event("deviceorientation")}}</td> + <td>{{DOMxRef("DeviceOrientationEvent")}} {{Experimental_Inline}}</td> + <td><a class="external" href="http://dev.w3.org/geo/api/spec-source-orientation.html" lang="en" title="The 'Device Orientation Events' specification">Device Orientation Events</a></td> + <td>Fresh data is available from an orientation sensor.</td> + </tr> + <tr> + <td>{{Event("deviceproximity")}}</td> + <td>{{DOMxRef("DeviceProximityEvent")}} {{Experimental_Inline}}</td> + <td><a class="external" href="http://dvcs.w3.org/hg/dap/raw-file/tip/proximity/Overview.html" lang="en" title="The definition of 'Proximity Events' in that specification.">Proximity Events</a></td> + <td>Fresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).</td> + </tr> + <tr> + <td>{{Event("dischargingtimechange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html">Battery status</a></td> + <td>The <code>dischargingTime</code> attribute has been updated.</td> + </tr> + <tr> + <td><code>DOMActivate</code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMActivate" style="white-space: nowrap;">DOM L3</a></td> + <td>A button, link or state changing element is activated (use {{Event("click")}} instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMAttributeNameChanged</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationNameEvent")}}</td> + <td><a href="http://www.w3.org/TR/2011/WD-DOM-Level-3-Events-20110531/#event-type-DOMAttributeNameChanged" style="white-space: nowrap;">DOM L3</a> Removed</td> + <td>The name of an attribute changed (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMAttrModified</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified" style="white-space: nowrap;">DOM L3</a></td> + <td>The value of an attribute has been modified (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMCharacterDataModified</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMCharacterDataModified" style="white-space: nowrap;">DOM L3</a></td> + <td>A text or another <a href="/en-US/docs/DOM/CharacterData">CharacterData</a> has changed (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td>{{Event("DOMContentLoaded")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#the-end">HTML5</a></td> + <td>The document has finished loading (but not its dependent resources).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMElementNameChanged</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationNameEvent")}}</td> + <td><a href="http://www.w3.org/TR/2011/WD-DOM-Level-3-Events-20110531/#event-type-DOMElementNameChanged" style="white-space: nowrap;">DOM L3</a> Removed</td> + <td>The name of an element changed (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code>DOMFocusIn</code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMFocusIn" style="white-space: nowrap;">DOM L3</a></td> + <td>An element has received focus (use {{Event("focus")}} or {{Event("focusin")}} instead).</td> + </tr> + <tr> + <td><code>DOMFocusOut</code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMFocusOut" style="white-space: nowrap;">DOM L3</a></td> + <td>An element has lost focus (use {{Event("blur")}} or {{Event("focusout")}} instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInserted</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted" style="white-space: nowrap;">DOM L3</a></td> + <td>A node has been added as a child of another node (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInsertedIntoDocument</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInsertedIntoDocument" style="white-space: nowrap;">DOM L3</a></td> + <td>A node has been inserted into the document (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemoved</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved" style="white-space: nowrap;">DOM L3</a></td> + <td>A node has been removed from its parent node (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemovedFromDocument</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemovedFromDocument" style="white-space: nowrap;">DOM L3</a></td> + <td>A node has been removed from the document (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMSubtreeModified</a></code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("MutationEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMSubtreeModified" style="white-space: nowrap;">DOM L3</a></td> + <td>A change happened in the document (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td>{{Event("downloading")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.</td> + </tr> + <tr> + <td>{{Event("drag")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-drag">HTML5</a></td> + <td>An element or text selection is being dragged (every 350ms).</td> + </tr> + <tr> + <td>{{Event("dragend")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragend">HTML5</a></td> + <td>A drag operation is being ended (by releasing a mouse button or hitting the escape key).</td> + </tr> + <tr> + <td>{{Event("dragenter")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragenter">HTML5</a></td> + <td>A dragged element or text selection enters a valid drop target.</td> + </tr> + <tr> + <td>{{Event("dragleave")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragleave">HTML5</a></td> + <td>A dragged element or text selection leaves a valid drop target.</td> + </tr> + <tr> + <td>{{Event("dragover")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragover">HTML5</a></td> + <td>An element or text selection is being dragged over a valid drop target (every 350ms).</td> + </tr> + <tr> + <td>{{Event("dragstart")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragstart">HTML5</a></td> + <td>The user starts dragging an element or text selection.</td> + </tr> + <tr> + <td>{{Event("drop")}}</td> + <td>{{DOMxRef("DragEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-drop">HTML5</a></td> + <td>An element is dropped on a valid drop target.</td> + </tr> + <tr> + <td>{{Event("durationchange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-durationchange">HTML5 media</a></td> + <td>The <code>duration</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{Event("emptied")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-emptied">HTML5 media</a></td> + <td>The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <a href="/en-US/docs/XPCOM_Interface_Reference/NsIDOMHTMLMediaElement" rel="internal"><code>load()</code></a> method is called to reload it.</td> + </tr> + <tr> + <td>{{Event("end_(SpeechRecognition)","end")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service has disconnected.</td> + </tr> + <tr> + <td>{{Event("end_(SpeechSynthesis)","end")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechSynthesisEvent")}}</td> + <td>{{SpecName("Web Speech API")}}</td> + <td>The utterance has finished being spoken.</td> + </tr> + <tr> + <td>{{Event("ended")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-ended">HTML5 media</a></td> + <td>Playback has stopped because the end of the media was reached.</td> + </tr> + <tr> + <td>{{Event("ended_(Web_Audio)", "ended")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName("Web Audio API")}}</td> + <td>Playback has stopped because the end of the media was reached.</td> + </tr> + <tr> + <td>{{Event("endEvent")}}</td> + <td>{{DOMxRef("TimeEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>A <a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SMIL</a> animation element ends.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-error" style="white-space: nowrap;">DOM L3</a></td> + <td>A resource failed to load.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> and </span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-error">XMLHttpRequest</a></td> + <td>Progression has failed.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>An error occurred while downloading the cache manifest or updating the content of the application.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a></td> + <td>An event source connection has been failed.</td> + </tr> + <tr> + <td>{{Event("error")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>A request caused an error and failed.</td> + </tr> + <tr> + <td>{{Event("error_(SpeechRecognitionError)","error")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>A speech recognition error occurs.</td> + </tr> + <tr> + <td>{{Event("error_(SpeechSynthesisError)","error")}}</td> + <td>{{DOMxRef("SpeechSynthesisErrorEvent")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>An error occurs that prevents the utterance from being successfully spoken.</td> + </tr> + <tr> + <td>{{Event("focus")}}</td> + <td>{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focus" style="white-space: nowrap;">DOM L3</a></td> + <td>An element has received focus (does not bubble).</td> + </tr> + <tr> + <td>{{Event("focusin")}}</td> + <td>{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focusIn" style="white-space: nowrap;">DOM L3</a></td> + <td>An element is about to receive focus (bubbles).</td> + </tr> + <tr> + <td>{{Event("focusout")}}</td> + <td>{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focusout" style="white-space: nowrap;">DOM L3</a></td> + <td>An element is about to lose focus (bubbles).</td> + </tr> + <tr> + <td>{{Event("fullscreenchange")}}{{gecko_minversion_inline("9")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api">Full Screen</a></td> + <td>An element was turned to fullscreen mode or back to normal mode.</td> + </tr> + <tr> + <td>{{Event("fullscreenerror")}}{{gecko_minversion_inline("9")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api">Full Screen</a></td> + <td>It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{Event("gamepadconnected")}}</td> + <td>{{DOMxRef("GamepadEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/gamepad/#the-gamepadconnected-event">Gamepad</a></td> + <td>A gamepad has been connected.</td> + </tr> + <tr> + <td>{{Event("gamepaddisconnected")}}</td> + <td>{{DOMxRef("GamepadEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/gamepad/#the-gamepaddisconnected-event">Gamepad</a></td> + <td>A gamepad has been disconnected.</td> + </tr> + <tr> + <td>{{Event("gotpointercapture")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-gotpointercapture-event">Pointer Events</a></td> + <td>Element receives pointer capture.</td> + </tr> + <tr> + <td>{{Event("hashchange")}}</td> + <td>{{DOMxRef("HashChangeEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-hashchange">HTML5</a></td> + <td>The fragment identifier of the URL has changed (the part of the URL after the #).</td> + </tr> + <tr> + <td>{{Event("lostpointercapture")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-lostpointercapture-event">Pointer Events</a></td> + <td>Element lost pointer capture.</td> + </tr> + <tr> + <td>{{Event("input")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/html5/forms.html#common-event-behaviors">HTML5</a></td> + <td>The value of an element changes or the content of an element with the attribute <a href="/en-US/docs/DOM/Element.contentEditable">contenteditable</a> is modified.</td> + </tr> + <tr> + <td>{{Event("invalid")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constraint-validation">HTML5</a></td> + <td>A submittable element has been checked and doesn't satisfy its constraints.</td> + </tr> + <tr> + <td>{{Event("keydown")}}</td> + <td>{{DOMxRef("KeyboardEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keydown" style="white-space: nowrap;">DOM L3</a></td> + <td>A key is pressed down.</td> + </tr> + <tr> + <td>{{Event("keypress")}}</td> + <td>{{DOMxRef("KeyboardEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress" style="white-space: nowrap;">DOM L3</a></td> + <td>A key is pressed down and that key normally produces a character value (use input instead).</td> + </tr> + <tr> + <td>{{Event("keyup")}}</td> + <td>{{DOMxRef("KeyboardEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keyup" style="white-space: nowrap;">DOM L3</a></td> + <td>A key is released.</td> + </tr> + <tr> + <td>{{Event("languagechange")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}</td> + <td>The user's preferred languages have changed.</td> + </tr> + <tr> + <td>{{Event("levelchange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html">Battery status</a></td> + <td>The <code>level</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{Event("load")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-load" style="white-space: nowrap;">DOM L3</a></td> + <td>A resource and its dependent resources have finished loading.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/load_(ProgressEvent)">load</a></code></td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-load">XMLHttpRequest</a></td> + <td>Progression has been successful.</td> + </tr> + <tr> + <td>{{Event("loadeddata")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-loadeddata">HTML5 media</a></td> + <td>The first frame of the media has finished loading.</td> + </tr> + <tr> + <td>{{Event("loadedmetadata")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-loadedmetadata">HTML5 media</a></td> + <td>The metadata has been loaded.</td> + </tr> + <tr> + <td>{{Event("loadend")}}</td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-loadend">XMLHttpRequest</a></td> + <td>Progress has stopped (after "error", "abort" or "load" have been dispatched).</td> + </tr> + <tr> + <td>{{Event("loadstart")}}</td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/progress-events/">Progress </a><span>and </span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-loadstart">XMLHttpRequest</a></td> + <td>Progress has begun.</td> + </tr> + <tr> + <td>{{Event("mark")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechSynthesisEvent")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The spoken utterance reaches a named SSML "mark" tag.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_websocket">message</a></code></td> + <td>{{DOMxRef("MessageEvent")}}</td> + <td><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A message is received through a WebSocket.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_webworker">message</a></code></td> + <td>{{DOMxRef("MessageEvent")}}</td> + <td><a href="http://www.w3.org/TR/workers/#communicating-with-a-dedicated-worker">Web Workers</a></td> + <td>A message is received from a Web Worker.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_webmessaging">message</a></code></td> + <td>{{DOMxRef("MessageEvent")}}</td> + <td><a href="http://www.w3.org/TR/webmessaging/">Web Messaging</a></td> + <td>A message is received from a child (i)frame or a parent window.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_serversentevents">message</a></code></td> + <td>{{DOMxRef("MessageEvent")}}</td> + <td><a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a></td> + <td>A message is received through an event source.</td> + </tr> + <tr> + <td>{{Event("messageerror")}}</td> + <td>{{DOMxRef("MessageEvent")}}</td> + <td>{{DOMxRef("MessagePort")}}, <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>, <a href="/en-US/docs/Web/API/Broadcast_Channel_API">Broadcast Channel</a>, {{DOMxRef("Window")}}</td> + <td>A message error is raised when a message is received by an object.</td> + </tr> + <tr> + <td>{{Event("message_(ServiceWorker)","message")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("ServiceWorkerMessageEvent")}} or {{DOMxRef("ExtendableMessageEvent")}}, depending on context.</td> + <td><a href="/en-US/docs/Web/API/Service_Worker_API">Service Workers</a></td> + <td>A message is received from a service worker, or a message is received in a service worker from another context.</td> + </tr> + <tr> + <td>{{Event("mousedown")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mousedown" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device button (usually a mouse) is pressed on an element.</td> + </tr> + <tr> + <td>{{Event("mouseenter")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseenter" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device is moved onto the element that has the listener attached.</td> + </tr> + <tr> + <td>{{Event("mouseleave")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseleave" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device is moved off the element that has the listener attached.</td> + </tr> + <tr> + <td>{{Event("mousemove")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mousemove" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device is moved over an element.</td> + </tr> + <tr> + <td>{{Event("mouseout")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseout" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device is moved off the element that has the listener attached or off one of its children.</td> + </tr> + <tr> + <td>{{Event("mouseover")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseover" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device is moved onto the element that has the listener attached or onto one of its children.</td> + </tr> + <tr> + <td>{{Event("mouseup")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseup" style="white-space: nowrap;">DOM L3</a></td> + <td>A pointing device button is released over an element.</td> + </tr> + <tr> + <td>{{Event("nomatch")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechRecognitionEvent")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service returns a final result with no significant recognition.</td> + </tr> + <tr> + <td>{{Event("notificationclick")}}</td> + <td>{{DOMxRef("NotificationEvent")}} {{Experimental_Inline}}</td> + <td>{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}</td> + <td>A system notification<span style="line-height: 19.0909080505371px;"> spawned by {{DOMxRef("ServiceWorkerRegistration.showNotification()")}} has been clicked.</span></td> + </tr> + <tr> + <td>{{Event("noupdate")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The manifest hadn't changed.</td> + </tr> + <tr> + <td>{{Event("obsolete")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The manifest was found to have become a 404 or 410 page, so the application cache is being deleted.</td> + </tr> + <tr> + <td>{{Event("offline")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#event-offline">HTML5 offline</a></td> + <td>The browser has lost access to the network.</td> + </tr> + <tr> + <td>{{Event("online")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#event-online">HTML5 offline</a></td> + <td>The browser has gained access to the network (but particular websites might be unreachable).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/open_websocket">open</a></code></td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A WebSocket connection has been established.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/open_serversentevents">open</a></code></td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a></td> + <td>An event source connection has been established.</td> + </tr> + <tr> + <td>{{Event("orientationchange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/screen-orientation/">Screen Orientation</a></td> + <td>The orientation of the device (portrait/landscape) has changed</td> + </tr> + <tr> + <td>{{Event("pagehide")}}</td> + <td>{{DOMxRef("PageTransitionEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pagehide">HTML5</a></td> + <td>A session history entry is being traversed from.</td> + </tr> + <tr> + <td>{{Event("pageshow")}}</td> + <td>{{DOMxRef("PageTransitionEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pageshow">HTML5</a></td> + <td>A session history entry is being traversed to.</td> + </tr> + <tr> + <td>{{Event("paste")}}</td> + <td>{{DOMxRef("ClipboardEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/clipboard-apis/#paste-event">Clipboard</a></td> + <td>Data has been transferred from the system clipboard to the document.</td> + </tr> + <tr> + <td>{{Event("pause")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-pause">HTML5 media</a></td> + <td>Playback has been paused.</td> + </tr> + <tr> + <td>{{Event("pause_(SpeechSynthesis)", "pause")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechSynthesisEvent")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The utterance is paused part way through.</td> + </tr> + <tr> + <td>{{Event("pointercancel")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointercancel-event">Pointer Events</a></td> + <td>The pointer is unlikely to produce any more events.</td> + </tr> + <tr> + <td>{{Event("pointerdown")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointerdown-event">Pointer Events</a></td> + <td>The pointer enters the active buttons state.</td> + </tr> + <tr> + <td>{{Event("pointerenter")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointerenter-event">Pointer Events</a></td> + <td>Pointing device is moved inside the hit-testing boundary.</td> + </tr> + <tr> + <td>{{Event("pointerleave")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointerleave-event">Pointer Events</a></td> + <td>Pointing device is moved out of the hit-testing boundary.</td> + </tr> + <tr> + <td>{{Event("pointerlockchange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/pointerlock/#pointerlockchange-and-pointerlockerror-events">Pointer Lock</a></td> + <td>The pointer was locked or released.</td> + </tr> + <tr> + <td>{{Event("pointerlockerror")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/pointerlock/#pointerlockchange-and-pointerlockerror-events">Pointer Lock</a></td> + <td>It was impossible to lock the pointer for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{Event("pointermove")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointermove-event">Pointer Events</a></td> + <td>The pointer changed coordinates.</td> + </tr> + <tr> + <td>{{Event("pointerout")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointerout-event">Pointer Events</a></td> + <td>The pointing device moved out of hit-testing boundary or leaves detectable hover range.</td> + </tr> + <tr> + <td>{{Event("pointerover")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointerover-event">Pointer Events</a></td> + <td>The pointing device is moved into the hit-testing boundary.</td> + </tr> + <tr> + <td>{{Event("pointerup")}}</td> + <td>{{DOMxRef("PointerEvent")}}</td> + <td><a href="http://www.w3.org/TR/pointerevents/#the-pointerup-event">Pointer Events</a></td> + <td>The pointer leaves the active buttons state.</td> + </tr> + <tr> + <td>{{Event("play")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-play">HTML5 media</a></td> + <td>Playback has begun.</td> + </tr> + <tr> + <td>{{Event("playing")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-playing">HTML5 media</a></td> + <td>Playback is ready to start after having been paused or delayed due to lack of data.</td> + </tr> + <tr> + <td>{{Event("popstate")}}</td> + <td>{{DOMxRef("PopStateEvent")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-popstate">HTML5</a></td> + <td>A session history entry is being navigated to (in certain cases).</td> + </tr> + <tr> + <td>{{Event("progress")}}</td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-progress">XMLHttpRequest</a></td> + <td>In progress.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/progress_(appcache_event)">progress</a></code></td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The user agent is downloading resources listed by the manifest.</td> + </tr> + <tr> + <td>{{Event("push")}}</td> + <td>{{DOMxRef("PushEvent")}} {{Experimental_Inline}}</td> + <td>{{SpecName("Push API")}}</td> + <td>A <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker</a> has received a push message.</td> + </tr> + <tr> + <td>{{Event("pushsubscriptionchange")}}</td> + <td>{{DOMxRef("PushEvent")}} {{Experimental_Inline}}</td> + <td>{{SpecName("Push API")}}</td> + <td>A <a href="/en-US/docs/Web/API/PushSubscription">PushSubscription</a> has expired.</td> + </tr> + <tr> + <td>{{Event("ratechange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-ratechange">HTML5 media</a></td> + <td>The playback rate has changed.</td> + </tr> + <tr> + <td>{{Event("readystatechange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><span>HTML5 <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-readystatechange">XMLHttpRequest</a></td> + <td>The readyState attribute of a document has changed.</td> + </tr> + <tr> + <td>{{Event("repeatEvent")}}</td> + <td>{{DOMxRef("TimeEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>A <a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SMIL</a> animation element is repeated.</td> + </tr> + <tr> + <td>{{Event("reset")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM L2</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-0#resetting-a-form">HTML5</a></td> + <td>A form is reset.</td> + </tr> + <tr> + <td>{{Event("resize")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-resize" style="white-space: nowrap;">DOM L3</a></td> + <td>The document view has been resized.</td> + </tr> + <tr> + <td>{{Event("resourcetimingbufferfull")}}</td> + <td>{{DOMxRef("Performance")}}</td> + <td><a href="https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull">Resource Timing</a></td> + <td>The browser's resource timing buffer is full.</td> + </tr> + <tr> + <td>{{Event("result")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechRecognitionEvent")}} {{Experimental_Inline}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.</td> + </tr> + <tr> + <td>{{Event("resume")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("SpeechSynthesisEvent")}} {{Experimental_Inline}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>A paused utterance is resumed.</td> + </tr> + <tr> + <td>{{Event("scroll")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-scroll" style="white-space: nowrap;">DOM L3</a></td> + <td>The document view or an element has been scrolled.</td> + </tr> + <tr> + <td>{{Event("seeked")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-seeked">HTML5 media</a></td> + <td>A <em>seek</em> operation completed.</td> + </tr> + <tr> + <td>{{Event("seeking")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-seeking">HTML5 media</a></td> + <td>A <em>seek</em> operation began.</td> + </tr> + <tr> + <td>{{Event("select")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-select" style="white-space: nowrap;">DOM L3</a></td> + <td>Some text is being selected.</td> + </tr> + <tr> + <td>{{Event("selectstart")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{ SpecName('Selection API')}}</td> + <td>A selection just started.</td> + </tr> + <tr> + <td>{{Event("selectionchange")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{ SpecName('Selection API')}}</td> + <td>The selection in the document has been changed.</td> + </tr> + <tr> + <td>{{Event("show")}}</td> + <td>{{DOMxRef("MouseEvent")}}</td> + <td><a href="http://www.w3.org/TR/html5/interactive-elements.html#context-menus">HTML5</a></td> + <td>A contextmenu event was fired on/bubbled to an element that has a <a href="/en-US/docs/DOM/element.contextmenu">contextmenu</a> attribute</td> + </tr> + <tr> + <td>{{Event("slotchange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{ SpecName('DOM WHATWG')}}</td> + <td>The node contents of a {{DOMxRef("HTMLSlotElement")}} ({{htmlelement("slot")}}) have changed.</td> + </tr> + <tr> + <td>{{Event("soundend")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>Any sound — recognisable speech or not — has stopped being detected.</td> + </tr> + <tr> + <td>{{Event("soundstart")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>Any sound — recognisable speech or not — has been detected.</td> + </tr> + <tr> + <td>{{Event("speechend")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>Speech recognised by the speech recognition service has stopped being detected.</td> + </tr> + <tr> + <td>{{Event("speechstart")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>Sound that is recognised by the speech recognition service as speech has been detected.</td> + </tr> + <tr> + <td>{{Event("stalled")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-stalled">HTML5 media</a></td> + <td>The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.</td> + </tr> + <tr> + <td>{{Event("start_(SpeechRecognition)","start")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current <code>SpeechRecognition</code>.</td> + </tr> + <tr> + <td>{{Event("start_(SpeechSynthesis)","start")}}</td> + <td>{{DOMxRef("SpeechSynthesisEvent")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The utterance has begun to be spoken.</td> + </tr> + <tr> + <td>{{Event("storage")}}</td> + <td>{{DOMxRef("StorageEvent")}}</td> + <td><a href="http://www.w3.org/TR/webstorage/#the-storage-event">Web Storage</a></td> + <td>A storage area (<a href="/en-US/docs/DOM/Storage#localStorage">localStorage</a> or <a href="/en-US/docs/DOM/Storage#sessionStorage">sessionStorage</a>) has changed.</td> + </tr> + <tr> + <td>{{Event("submit")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM L2</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm">HTML5</a></td> + <td>A form is submitted.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/success_indexedDB">success</a></code></td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>A request successfully completed.</td> + </tr> + <tr> + <td>{{Event("suspend")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-suspend">HTML5 media</a></td> + <td>Media data loading has been suspended.</td> + </tr> + <tr> + <td>{{Event("SVGAbort")}}</td> + <td>{{DOMxRef("SVGEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>Page loading has been stopped before the <a href="/en-US/docs/SVG">SVG</a> was loaded.</td> + </tr> + <tr> + <td>{{Event("SVGError")}}</td> + <td>{{DOMxRef("SVGEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An error has occurred before the <a href="/en-US/docs/SVG">SVG</a> was loaded.</td> + </tr> + <tr> + <td>{{Event("SVGLoad")}}</td> + <td>{{DOMxRef("SVGEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document has been loaded and parsed.</td> + </tr> + <tr> + <td>{{Event("SVGResize")}}</td> + <td>{{DOMxRef("SVGEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document is being resized.</td> + </tr> + <tr> + <td>{{Event("SVGScroll")}}</td> + <td>{{DOMxRef("SVGEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document is being scrolled.</td> + </tr> + <tr> + <td>{{Event("SVGUnload")}}</td> + <td>{{DOMxRef("SVGEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document has been removed from a window or frame.</td> + </tr> + <tr> + <td>{{Event("SVGZoom")}}</td> + <td>{{DOMxRef("SVGZoomEvent")}}</td> + <td><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document is being zoomed.</td> + </tr> + <tr> + <td>{{Event("timeout")}}</td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-timeout">XMLHttpRequest</a></td> + <td></td> + </tr> + <tr> + <td>{{Event("timeupdate")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-timeupdate">HTML5 media</a></td> + <td>The time indicated by the <code>currentTime</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{Event("touchcancel")}}</td> + <td>{{DOMxRef("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/">Touch Events</a></td> + <td>A touch point has been disrupted in an implementation-specific manners (too many touch points for example).</td> + </tr> + <tr> + <td>{{Event("touchend")}}</td> + <td>{{DOMxRef("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchend-event">Touch Events</a></td> + <td>A touch point is removed from the touch surface.</td> + </tr> + <tr> + <td>{{Event("touchmove")}}</td> + <td>{{DOMxRef("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchmove-event">Touch Events</a></td> + <td>A touch point is moved along the touch surface.</td> + </tr> + <tr> + <td>{{Event("touchstart")}}</td> + <td>{{DOMxRef("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchstart---------event">Touch Events</a></td> + <td>A touch point is placed on the touch surface.</td> + </tr> + <tr> + <td>{{Event("transitionend")}}</td> + <td>{{DOMxRef("TransitionEvent")}} {{Experimental_Inline}}</td> + <td><a href="http://www.w3.org/TR/css3-transitions/#transition-events">CSS Transitions</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_transitions">CSS transition</a> has completed.</td> + </tr> + <tr> + <td>{{Event("unload")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-unload" style="white-space: nowrap;">DOM L3</a></td> + <td>The document or a dependent resource is being unloaded.</td> + </tr> + <tr> + <td>{{Event("updateready")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://dev.w3.org/html5/spec/offline.html">Offline</a></td> + <td>The resources listed in the manifest have been newly redownloaded, and the script can use <code>swapCache()</code> to switch to the new cache.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/upgradeneeded_indexedDB">upgradeneeded</a></code></td> + <td></td> + <td><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>An attempt was made to open a database with a version number higher than its current version. A <code>versionchange</code> transaction has been created.</td> + </tr> + <tr> + <td>{{Event("userproximity")}}</td> + <td>{{DOMxRef("UserProximityEvent")}} {{Experimental_Inline}}</td> + <td>{{SpecName("Proximity Events")}}</td> + <td>Fresh data is available from a proximity sensor (indicates whether the nearby object is <code>near</code> the device or not).</td> + </tr> + <tr> + <td>{{Event("voiceschanged")}} {{Experimental_Inline}}</td> + <td>{{DOMxRef("Event")}}</td> + <td>{{SpecName('Web Speech API')}}</td> + <td>The list of {{DOMxRef("SpeechSynthesisVoice")}} objects that would be returned by the {{DOMxRef("SpeechSynthesis.getVoices()")}} method has changed (when the {{Event("voiceschanged")}} event fires.)</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/versionchange_indexedDB">versionchange</a></code></td> + <td></td> + <td><a href="http://www.w3.org/TR/IndexedDB/#database-interface">IndexedDB</a></td> + <td>A <code>versionchange</code> transaction completed.</td> + </tr> + <tr> + <td>{{Event("visibilitychange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.w3.org/TR/page-visibility/#sec-visibilitychange-event">Page visibility</a></td> + <td>The content of a tab has become visible or has been hidden.</td> + </tr> + <tr> + <td>{{Event("volumechange")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-volumechange">HTML5 media</a></td> + <td>The volume has changed.</td> + </tr> + <tr> + <td>{{Event("waiting")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-waiting">HTML5 media</a></td> + <td>Playback has stopped because of a temporary lack of data.</td> + </tr> + <tr> + <td>{{Event("wheel")}}{{gecko_minversion_inline("17")}}</td> + <td>{{DOMxRef("WheelEvent")}}</td> + <td><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-wheel" style="white-space: nowrap;">DOM L3</a></td> + <td>A wheel button of a pointing device is rotated in any direction.</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Non-standard_events">Non-standard events</h2> + +<div style="overflow: auto;"> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Event Type</th> + <th scope="col">Specification</th> + <th scope="col">Fired when...</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("afterscriptexecute")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><em>Mozilla Specific</em></td> + <td>A script has been executed.</td> + </tr> + <tr> + <td>{{Event("beforescriptexecute")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><em>Mozilla Specific</em></td> + <td>A script is about to be executed.</td> + </tr> + <tr> + <td>{{Event("beforeinstallprompt")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><em>Chrome specific</em></td> + <td>A user is prompted to save a web site to a home screen on mobile.</td> + </tr> + <tr> + <td>{{Event("cardstatechange")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The {{DOMxRef("MozMobileConnection.cardState")}} property changes value.</td> + </tr> + <tr> + <td>{{Event("change")}}</td> + <td>{{DOMxRef("DeviceStorageChangeEvent")}}</td> + <td><em>Firefox OS specific</em></td> + <td>This event is triggered each time a file is created, modified or deleted on a given storage area.</td> + </tr> + <tr> + <td>{{Event("connectionInfoUpdate")}}</td> + <td></td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#176"><em>Firefox OS specific</em></a></td> + <td>The informations about the signal strength and the link speed have been updated.</td> + </tr> + <tr> + <td>{{Event("cfstatechange")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The call forwarding state changes.</td> + </tr> + <tr> + <td>{{Event("datachange")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The {{DOMxRef("MozMobileConnection.data")}} object changes values.</td> + </tr> + <tr> + <td>{{Event("dataerror")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The {{DOMxRef("MozMobileConnection.data")}} object receive an error from the <abbr title="Radio Interface Layer">RIL</abbr>.</td> + </tr> + <tr> + <td>{{Event("DOMMouseScroll")}}{{Deprecated_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>The wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{Event("wheel")}} instead)</td> + </tr> + <tr> + <td><code>dragdrop</code> {{Deprecated_Inline}}</td> + <td><code>DragEvent</code></td> + <td><em>Mozilla specific</em></td> + <td>An element is dropped (use {{Event("drop")}} instead).</td> + </tr> + <tr> + <td><code>dragexit</code> {{Deprecated_Inline}}</td> + <td><code>DragEvent</code></td> + <td><em>Mozilla specific</em></td> + <td>A drag operation is being ended(use {{Event("dragend")}} instead).</td> + </tr> + <tr> + <td><code>draggesture</code> {{Deprecated_Inline}}</td> + <td><code>DragEvent</code></td> + <td><em>Mozilla specific</em></td> + <td>The user starts dragging an element or text selection (use {{Event("dragstart")}} instead).</td> + </tr> + <tr> + <td>{{Event("icccardlockerror")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>the {{DOMxRef("MozMobileConnection.unlockCardLock()")}} or {{DOMxRef("MozMobileConnection.setCardLock()")}} methods fails.</td> + </tr> + <tr> + <td>{{Event("iccinfochange")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The {{DOMxRef("MozMobileConnection.iccInfo")}} object changes.</td> + </tr> + <tr> + <td>{{Event("localized")}}</td> + <td></td> + <td><em><a href="https://github.com/fabi1cazenave/webL10n">Mozilla Specific</a></em></td> + <td>The page has been localized using data-l10n-* attributes.</td> + </tr> + <tr> + <td>{{Event("mousewheel")}}{{Deprecated_Inline}}</td> + <td></td> + <td><a href="http://msdn.microsoft.com/en-us/library/ie/ms536951%28v=vs.85%29.aspx"><em>IE invented</em></a></td> + <td>The wheel button of a pointing device is rotated.</td> + </tr> + <tr> + <td>{{Event("MozAudioAvailable")}}</td> + <td>{{DOMxRef("Event")}}</td> + <td><em>Mozilla specific</em></td> + <td>The audio buffer is full and the corresponding raw samples are available.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozBeforeResize"><code>MozBeforeResize</code></a> {{Obsolete_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>A window is about to be resized.</td> + </tr> + <tr> + <td>{{Event("mozbrowseractivitydone")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when some activity has been completed (complete description TBD.)</td> + </tr> + <tr> + <td>{{Event("mozbrowserasyncscroll")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the scroll position within a browser<code> </code>{{HTMLElement("iframe")}} changes.</td> + </tr> + <tr> + <td>{{Event("mozbrowseraudioplaybackchange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.</td> + </tr> + <tr> + <td>{{Event("mozbrowsercaretstatechanged")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.</td> + </tr> + <tr> + <td>{{Event("mozbrowserclose")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when window.close() is called within a browser {{HTMLElement("iframe")}}.</td> + </tr> + <tr> + <td>{{Event("mozbrowsercontextmenu")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a browser {{HTMLElement("iframe")}} try to open a context menu.</td> + </tr> + <tr> + <td>{{Event("mozbrowserdocumentfirstpaint")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.</td> + </tr> + <tr> + <td>{{Event("mozbrowsererror")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when an error occured while trying to load a content within a browser iframe</td> + </tr> + <tr> + <td>{{Event("mozbrowserfindchange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see <a href="/en-US/docs/Web/API/HTMLIFrameElement#Search_methods">HTMLIFrameElement search methods</a>.)</td> + </tr> + <tr> + <td>{{Event("mozbrowserfirstpaint")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from <em>about:blank</em>.)</td> + </tr> + <tr> + <td>{{Event("mozbrowsericonchange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the favicon of a browser iframe changes.</td> + </tr> + <tr> + <td>{{Event("mozbrowserlocationchange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when an browser iframe's location changes.</td> + </tr> + <tr> + <td>{{Event("mozbrowserloadend")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser iframe has finished loading all its assets.</td> + </tr> + <tr> + <td>{{Event("mozbrowserloadstart")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser iframe starts to load a new page.</td> + </tr> + <tr> + <td>{{Event("mozbrowsermanifestchange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a the path to the app manifest changes, in the case of a browser {{HTMLElement("iframe")}} with an open web app embedded in it.</td> + </tr> + <tr> + <td>{{Event("mozbrowsermetachange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.</td> + </tr> + <tr> + <td>{{Event("mozbrowseropensearch")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a link to a search engine is found.</td> + </tr> + <tr> + <td>{{Event("mozbrowseropentab")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a new tab is opened within a browser {{HTMLElement("iframe")}} as a result of the user issuing a command to open a link target in a new tab (for example <kbd>ctrl</kbd>/<kbd>cmd</kbd> + click.)</td> + </tr> + <tr> + <td>{{Event("mozbrowseropenwindow")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when {{DOMxRef("window.open()")}} is called within a browser iframe.</td> + </tr> + <tr> + <td>{{Event("mozbrowserresize")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser {{HTMLElement("iframe")}}'s window size has changed.</td> + </tr> + <tr> + <td>{{Event("mozbrowserscroll")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser {{HTMLElement("iframe")}} content scrolls.</td> + </tr> + <tr> + <td>{{Event("mozbrowserscrollareachanged")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the available scrolling area in the browser {{HTMLElement("iframe")}} changes. This can occur on resize and when the page size changes (while loading for example.)</td> + </tr> + <tr> + <td>{{Event("mozbrowserscrollviewchange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when asynchronous scrolling (i.e. APCZ) starts or stops.</td> + </tr> + <tr> + <td>{{Event("mozbrowsersecuritychange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the SSL state changes within a browser iframe.</td> + </tr> + <tr> + <td>{{Event("mozbrowserselectionstatechanged")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{Event("mozbrowsercaretstatechanged")}} instead.</td> + </tr> + <tr> + <td>{{Event("mozbrowsershowmodalprompt")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when {{DOMxRef("window.alert","alert()")}}, {{DOMxRef("window.confirm","confirm()")}} or {{DOMxRef("window.prompt","prompt()")}} are called within a browser iframe</td> + </tr> + <tr> + <td>{{Event("mozbrowsertitlechange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the document.title changes within a browser iframe.</td> + </tr> + <tr> + <td>{{Event("mozbrowserusernameandpasswordrequired")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when an HTTP authentification is requested.</td> + </tr> + <tr> + <td>{{Event("mozbrowservisibilitychange")}}</td> + <td></td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{DOMxRef("HTMLIFrameElement.setVisible","setVisible()")}}.</td> + </tr> + <tr> + <td>{{Event("MozGamepadButtonDown")}}</td> + <td></td> + <td><em>To be specified</em></td> + <td>A gamepad button is pressed down.</td> + </tr> + <tr> + <td>{{Event("MozGamepadButtonUp")}}</td> + <td></td> + <td><em>To be specified</em></td> + <td>A gamepad button is released.</td> + </tr> + <tr> + <td>{{Event("MozMousePixelScroll")}} {{Deprecated_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>The wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)</td> + </tr> + <tr> + <td>{{Event("MozOrientation")}} {{Deprecated_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>Fresh data is available from an orientation sensor (see deviceorientation).</td> + </tr> + <tr> + <td>{{Event("MozScrolledAreaChanged")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><em>Mozilla specific</em></td> + <td>The document view has been scrolled or resized.</td> + </tr> + <tr> + <td>{{Event("moztimechange")}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>The time of the device has been changed.</td> + </tr> + <tr> + <td><a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchDown</a> {{Deprecated_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>A touch point is placed on the touch surface (use touchstart instead).</td> + </tr> + <tr> + <td><a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchMove</a> {{Deprecated_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>A touch point is moved along the touch surface (use touchmove instead).</td> + </tr> + <tr> + <td><a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchUp</a> {{Deprecated_Inline}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>A touch point is removed from the touch surface (use touchend instead).</td> + </tr> + <tr> + <td>{{Event("alerting")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The correspondent is being alerted (his/her phone is ringing).</td> + </tr> + <tr> + <td>{{Event("busy")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The line of the correspondent is busy.</td> + </tr> + <tr> + <td>{{Event("callschanged")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been added or removed from the list of current calls.</td> + </tr> + <tr> + <td><a href="/en-US/docs/DOM/onconnected">onconnected</a> {{Event("connected")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been connected.</td> + </tr> + <tr> + <td>{{Event("connecting")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to connect.</td> + </tr> + <tr> + <td>{{Event("delivered")}}</td> + <td>{{DOMxRef("SMSEvent")}}</td> + <td><em>To be specified</em></td> + <td>An SMS has been successfully delivered.</td> + </tr> + <tr> + <td>{{Event("dialing")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The number of a correspondent has been dialed.</td> + </tr> + <tr> + <td>{{Event("disabled")}}</td> + <td></td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#182"><em>Firefox OS specific</em></a></td> + <td>Wifi has been disabled on the device.</td> + </tr> + <tr> + <td>{{Event("disconnected")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been disconnected.</td> + </tr> + <tr> + <td>{{Event("disconnecting")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to disconnect.</td> + </tr> + <tr> + <td>{{Event("enabled")}}</td> + <td></td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#182"><em>Firefox OS specific</em></a></td> + <td>Wifi has been enabled on the device.</td> + </tr> + <tr> + <td>{{Event("error_(Telephony)","error")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>An error occurred.</td> + </tr> + <tr> + <td>{{Event("held")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been held.</td> + </tr> + <tr> + <td>{{Event("holding")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to be held.</td> + </tr> + <tr> + <td>{{Event("incoming")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is being received.</td> + </tr> + <tr> + <td>{{Event("received")}}</td> + <td>{{DOMxRef("SMSEvent")}}</td> + <td><em>To be specified</em></td> + <td>An SMS has been received.</td> + </tr> + <tr> + <td>{{Event("resuming")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to resume.</td> + </tr> + <tr> + <td>{{Event("sent")}}</td> + <td>{{DOMxRef("SMSEvent")}}</td> + <td><em>To be specified</em></td> + <td>An SMS has been sent.</td> + </tr> + <tr> + <td>{{Event("statechange")}}</td> + <td>{{DOMxRef("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The state of a call has changed.</td> + </tr> + <tr> + <td>{{Event("statuschange")}}</td> + <td></td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#156"><em>Firefox OS specific</em></a></td> + <td>The status of the Wifi connection changed.</td> + </tr> + <tr> + <td>{{Event("overflow")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><em>Mozilla specific</em></td> + <td>An element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with <code>overflow</code> != <code>visible</code>).</td> + </tr> + <tr> + <td>{{Event("smartcard-insert")}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>A <a href="/en-US/docs/JavaScript_crypto">smartcard</a> has been inserted.</td> + </tr> + <tr> + <td>{{Event("smartcard-remove")}}</td> + <td></td> + <td><em>Mozilla specific</em></td> + <td>A <a href="/en-US/docs/JavaScript_crypto">smartcard</a> has been removed.</td> + </tr> + <tr> + <td>{{Event("stkcommand")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The <abbr title="SIM Application Toolkit">STK</abbr> Proactive Command is issued from <abbr title="Integrated Circuit Card">ICC</abbr>.</td> + </tr> + <tr> + <td>{{Event("stksessionend")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The <abbr title="SIM Application Toolkit">STK</abbr> Session is terminated by <abbr title="Integrated Circuit Card">ICC</abbr>.</td> + </tr> + <tr> + <td>{{Event("touchenter")}}</td> + <td>{{DOMxRef("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchstart---------event">Touch Events</a> Removed</td> + <td></td> + </tr> + <tr> + <td>{{Event("touchleave")}}</td> + <td>{{DOMxRef("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchstart---------event">Touch Events</a> Removed</td> + <td></td> + </tr> + <tr> + <td>{{Event("underflow")}}</td> + <td>{{DOMxRef("UIEvent")}}</td> + <td><em>Mozilla specific</em></td> + <td>An element is no longer overflowed by its content (only works for elements styled with <code>overflow</code> != <code>visible</code>).</td> + </tr> + <tr> + <td><code>uploadprogress</code> {{Deprecated_Inline}}</td> + <td>{{DOMxRef("ProgressEvent")}}</td> + <td><em>Mozilla Specific</em></td> + <td>Upload is in progress (see {{Event("progress")}}).</td> + </tr> + <tr> + <td> + <p>{{Event("ussdreceived")}}</p> + </td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>A new <abbr title="Unstructured Supplementary Service Data">USSD</abbr> message is received</td> + </tr> + <tr> + <td>{{Event("voicechange")}}</td> + <td></td> + <td><em>Firefox OS specific</em></td> + <td>The {{DOMxRef("MozMobileConnection.voice")}} object changes values.</td> + </tr> + <tr> + <td>{{Event("msContentZoom")}}</td> + <td></td> + <td><em>Microsoft specific</em></td> + <td></td> + </tr> + <tr> + <td>{{Event("MSManipulationStateChanged")}}</td> + <td></td> + <td><em>Microsoft specific</em></td> + <td></td> + </tr> + <tr> + <td>{{Event("MSPointerHover")}} {{Deprecated_Inline}}</td> + <td></td> + <td><em>Microsoft specific</em></td> + <td></td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mozilla-specific_events">Mozilla-specific events</h2> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> those events are never exposed to web content and can only be used in chrome content context.</p> +</div> + +<h3 id="XUL_events">XUL events</h3> + +<div style="overflow: auto;"> +<table class="standard-table"> + <thead> + <tr> + <th>Event Name</th> + <th>Event Type</th> + <th>Specification</th> + <th>Fired when...</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{Event("broadcast")}}</td> + <td></td> + <td><a href="/en-US/docs/XUL/Tutorial/Broadcasters_and_Observers#Broadcast_event">XUL</a></td> + <td>An <code>observer</code> noticed a change to the attributes of a watched broadcaster.</td> + </tr> + <tr> + <td>{{Event("CheckboxStateChange")}}</td> + <td></td> + <td>XUL</td> + <td>The state of a <code>checkbox</code> has been changed either by a user action or by a script (useful for accessibility).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/close_event">close</a></td> + <td></td> + <td>XUL</td> + <td>The close button of the window has been clicked.</td> + </tr> + <tr> + <td>{{Event("command")}}</td> + <td></td> + <td>XUL</td> + <td>An element has been activated.</td> + </tr> + <tr> + <td>{{Event("commandupdate")}}</td> + <td></td> + <td>XUL</td> + <td>A command update occurred on a <code>commandset</code> element.</td> + </tr> + <tr> + <td>{{Event("DOMMenuItemActive")}}</td> + <td></td> + <td>XUL</td> + <td>A menu or menuitem has been hovered or highlighted.</td> + </tr> + <tr> + <td>{{Event("DOMMenuItemInactive")}}</td> + <td></td> + <td><em>XUL</em></td> + <td>A menu or menuitem is no longer hovered or highlighted.</td> + </tr> + <tr> + <td>{{Event("popuphidden")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip has been hidden.</td> + </tr> + <tr> + <td>{{Event("popuphiding")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip is about to be hidden.</td> + </tr> + <tr> + <td>{{Event("popupshowing")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip is about to become visible.</td> + </tr> + <tr> + <td>{{Event("popupshown")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip has become visible.</td> + </tr> + <tr> + <td>{{Event("RadioStateChange")}}</td> + <td></td> + <td>XUL</td> + <td>The state of a <code>radio</code> has been changed either by a user action or by a script (useful for accessibility).</td> + </tr> + <tr> + <td>{{Event("ValueChange")}}</td> + <td></td> + <td>XUL</td> + <td>The value of an element has changed (a progress bar for example, useful for accessibility).</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Add-on-specific_events">Add-on-specific events</h3> + +<div style="overflow: auto;"> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Event Type</th> + <th scope="col">Specification</th> + <th scope="col">Fired when...</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozSwipeGesture">MozSwipeGesture</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A touch point is swiped across the touch surface</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureStart">MozMagnifyGestureStart</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points start to move away from each other.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureUpdate">MozMagnifyGestureUpdate</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points move away from each other (after a MozMagnifyGestureStart).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozMagnifyGesture">MozMagnifyGesture</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozRotateGestureStart">MozRotateGestureStart</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points start to rotate around a point.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozRotateGestureUpdate">MozRotateGestureUpdate</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points rotate around a point (after a MozRotateGestureStart).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozRotateGesture">MozRotateGesture</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points rotate around a point (after a sequence of MozRotateGestureUpdate).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozTapGesture">MozTapGesture</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Two touch points are tapped on the touch surface.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozPressTapGesture">MozPressTapGesture</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozEdgeUIGesture">MozEdgeUIGesture</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A touch point is swiped across the touch surface to invoke the edge UI (Win8 only).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozAfterPaint">MozAfterPaint</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Content has been repainted.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMPopupBlocked">DOMPopupBlocked</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A popup has been blocked</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMWindowCreated">DOMWindowCreated</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A window has been created.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMWindowClose">DOMWindowClose</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A window is about to be closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMTitleChanged">DOMTitleChanged</a></td> + <td></td> + <td><em>Addons specifc</em></td> + <td>The title of a window has changed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMLinkAdded">DOMLinkAdded</a></td> + <td></td> + <td><em>Addons specifc</em></td> + <td>A link has been added a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMLinkRemoved">DOMLinkRemoved</a></td> + <td></td> + <td><em>Addons specifc</em></td> + <td>A link has been removed inside from a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMMetaAdded">DOMMetaAdded</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A <code>meta</code> element has been added to a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMMetaRemoved">DOMMetaRemoved</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A <code>meta</code> element has been removed from a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMWillOpenModalDialog">DOMWillOpenModalDialog</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A modal dialog is about to open.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMModalDialogClosed">DOMModalDialogClosed</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A modal dialog has been closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMAutoComplete">DOMAutoComplete</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>The content of an element has been auto-completed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMFrameContentLoaded">DOMFrameContentLoaded</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>The frame has finished loading (but not its dependent resources).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/AlertActive">AlertActive</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A <code><a href="/en-US/docs/XUL/notification">notification</a></code> element is shown.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/AlertClose">AlertClose</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A <code><a href="/en-US/docs/XUL/notification">notification</a></code> element is closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/fullscreen">fullscreen</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Browser fullscreen mode has been entered or left.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/sizemodechange">sizemodechange</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>Window has entered/left fullscreen mode, or has been minimized/unminimized.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozEnteredDomFullscreen">MozEnteredDomFullscreen</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td><a href="/en-US/docs/DOM/Using_full-screen_mode">DOM fullscreen</a> mode has been entered.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSWindowClosing">SSWindowClosing</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>The session store will stop tracking this window.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSTabClosing">SSTabClosing</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>The session store will stop tracking this tab.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSTabRestoring">SSTabRestoring</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab is about to be restored.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSTabRestored">SSTabRestored</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been restored.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSWindowStateReady">SSWindowStateReady</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A window state has switched to "ready".</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSWindowStateBusy">SSWindowStateBusy</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A window state has switched to "busy".</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabOpen">TabOpen</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been opened.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabClose">TabClose</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabSelect">TabSelect</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been selected.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabShow">TabShow</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been shown.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabHide">TabHide</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been hidden.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabPinned">TabPinned</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been pinned.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabUnpinned">TabUnpinned</a></td> + <td></td> + <td><em>Addons specific</em></td> + <td>A tab has been unpinned.</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Developer_tool-specific_events">Developer tool-specific events</h3> + +<div style="overflow: auto;"> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Event Name</th> + <th scope="col">Event Type</th> + <th scope="col">Specification</th> + <th scope="col">Fired when...</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">CssRuleViewRefreshed</a></td> + <td></td> + <td><em>devtools specific</em></td> + <td>The "Rules" view of the style inspector has been updated.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/CssRuleViewChanged">CssRuleViewChanged</a></td> + <td></td> + <td><em>devtools specific</em></td> + <td>The "Rules" view of the style inspector has been changed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/CssRuleViewCSSLinkClicked">CssRuleViewCSSLinkClicked</a></td> + <td></td> + <td><em>devtools specific</em></td> + <td>A link to a CSS file has been clicked in the "Rules" view of the style inspector.</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{DOMxRef("Event")}}</li> + <li><a href="/en-US/docs/Web/Guide/DOM/Events">Event developer guide</a></li> +</ul> diff --git a/files/vi/web/events/load/index.html b/files/vi/web/events/load/index.html new file mode 100644 index 0000000000..130d6b9af0 --- /dev/null +++ b/files/vi/web/events/load/index.html @@ -0,0 +1,124 @@ +--- +title: load +slug: Web/Events/load +tags: + - DOM + - Event + - Sự kiện +translation_of: Web/API/Window/load_event +--- +<p>Sự kiện <strong><code>load</code></strong> có hiệu lực (được kích hoạt) khi các tài nguyên của một đối tượng hoặc các tài nguyên phụ thuộc vào đối tượng đó đã được tải nạp hoàn tất.</p> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<h3 class="brush: html" id="Window">Window</h3> + +<pre class="brush: html"><script> + window.addEventListener("load", function(event) { + console.log("Tất cả các tài nguyên đã được tải nạp hoàn tất!"); + }); +</script></pre> + +<h3 class="brush: html" id="Phần_tử_script">Phần tử <code>script</code></h3> + +<pre class="brush: html"><script> + var script = document.createElement("script"); + script.addEventListener("load", function(event) { + console.log("Script đã được tải nạp xong và thực thi"); + }); + script.src = "http://example.com/example.js"; + script.async = true; + document.getElementsByTagName("script")[0].parentNode.appendChild(script); +</script></pre> + +<h2 id="Thông_tin_cơ_bản">Thông tin cơ bản</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-load">DOM L3</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Giao diện</dt> + <dd style="margin: 0 0 0 120px;">UIEvent</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">Không</dd> + <dt style="float: left; text-align: right; width: 120px;">Có thể hủy bỏ</dt> + <dd style="margin: 0 0 0 120px;">Không thể</dd> + <dt style="float: left; text-align: right; width: 120px;">Đối tượng</dt> + <dd style="margin: 0 0 0 120px;">Window, Document, Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Hành động mặc địch</dt> + <dd style="margin: 0 0 0 120px;">Không.</dd> +</dl> + +<h2 id="Các_thuộc_tính">Các thuộc tính</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Thuộc tính</th> + <th scope="col">Kiểu / Loại</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td><code>{{domxref("EventTarget")}}</code></td> + <td>Mục tiêu để áp dụng sự kiện (Đối tượng thuộc cây DOM).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td><code>{{domxref("DOMString")}}</code></td> + <td>Loại sự kiện</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td><code>{{domxref("Boolean")}}</code></td> + <td>Xác định sự kiện bình thường có bubbles hay không.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td><code>{{domxref("Boolean")}}</code></td> + <td>Xác định sự kiện liệu có thể hủy bỏ được hay không.</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td><code>{{domxref("WindowProxy")}}</code></td> + <td><code>{{domxref("Document.defaultView", "document.defaultView")}}</code> (<code>window</code> of the document)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>0.</td> + </tr> + </tbody> +</table> + +<h2 id="Các_thông_số_kỹ_thuật">Các thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số</th> + <th scope="col">Trạng thái</th> + <th scope="col">Diễn giải</th> + </tr> + <tr> + <td>{{SpecName('UI Events', '#event-type-load', 'load')}}</td> + <td>{{Spec2('UI Events')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'parsing.html#the-end:event-load', 'Load event')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Liên kết này đưa đến phần giải thích các bước được thực hiện khi quá trình tải nạp tài liệu kết thúc. Sự kiện 'load' cũng được kích hoạt ở nhiều phần tử. Và lưu ý rằng có nhiều chỗ trong Thông số kỹ thuật đề cập đến những thứ mà có thể "<a href="https://html.spec.whatwg.org/multipage/parsing.html#delay-the-load-event">Trì hoãn sự kiện load</a>".</td> + </tr> + </tbody> +</table> + +<h2 id="Các_sự_kiện_liên_quan">Các sự kiện liên quan</h2> + +<ul> + <li>{{event("DOMContentLoaded")}}</li> + <li>{{event("readystatechange")}}</li> + <li>{{event("beforeunload")}}</li> + <li>{{event("unload")}}</li> +</ul> diff --git a/files/vi/web/guide/api/index.html b/files/vi/web/guide/api/index.html new file mode 100644 index 0000000000..b27f6a95d9 --- /dev/null +++ b/files/vi/web/guide/api/index.html @@ -0,0 +1,23 @@ +--- +title: Hướng dẫn Web APIs +slug: Web/Guide/API +tags: + - API + - Hướng dẫn + - Landing +translation_of: Web/Guide/API +--- +<p><span class="tlid-translation translation" lang="vi"><span title="">Web bao gồm một loạt các API có thể được sử dụng từ JavaScript để xây dựng các ứng dụng ngày càng mạnh hơn và có khả năng hơn, chạy trên web, cục bộ hoặc thông qua công nghệ như</span></span> <a href="https://nodejs.org/">Node.js</a>, <span class="tlid-translation translation" lang="vi"><span title="">trên máy chủ.</span> <span title="">Trên trang này, bạn sẽ tìm thấy một danh sách đầy đủ tất cả các API được cung cấp bởi công nghệ web đầy đủ.</span></span></p> + +<h2 id="Web_APIs_từ_A_tới_Z">Web APIs từ A tới Z</h2> + +<p>{{ListGroups}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/API">Web API interface reference</a> (<span class="tlid-translation translation" lang="vi"><span title="">một chỉ mục của tất cả các interface bao gồm tất cả các API này</span></span> )</li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model">Document Object Model</a> (DOM)</li> + <li><a href="/en-US/docs/Web/Events">Web API event reference</a></li> + <li><a href="/en-US/docs/Learn">Learning web development</a></li> +</ul> diff --git a/files/vi/web/guide/css/getting_started/index.html b/files/vi/web/guide/css/getting_started/index.html new file mode 100644 index 0000000000..2d395bee37 --- /dev/null +++ b/files/vi/web/guide/css/getting_started/index.html @@ -0,0 +1,43 @@ +--- +title: Getting started with CSS +slug: Web/Guide/CSS/Getting_started +tags: + - Beginner + - CSS + - 'CSS:Getting_Started' + - Guide + - Needs + - NeedsBeginnerUpdate + - NeedsTranslation + - NeedsUpdate + - TopicStub + - Web +translation_of: Learn/CSS/First_steps +--- +<p><span class="seoSummary">This tutorial introduces you to the basic features and language (the syntax) for <a href="/en-US/docs/Web/Guide/CSS" title="/en-US/docs/Web/Guide/CSS"><strong>Cascading Style Sheets</strong></a> (CSS). You use CSS to change the look of a structured document, such as a web page. The tutorial also includes sample exercises you can try on your own computer to see the effects of CSS and features that work in modern browsers. </span></p> +<p>The tutorial is for beginners and anyone who would like to review the basics of CSS. If you have more experience with CSS, the CSS main page <a href="/en-US/docs/Web/Guide/CSS" title="/en-US/docs/Web/Guide/CSS">lists</a> more advanced resources.</p> +<nav class="fancyTOC"> + <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/What_is_CSS" rel="next" title="Chapter 'What is CSS' of the CSS tutorial">What is CSS</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Why_use_CSS" title="Chapter 'Why use CSS' of the CSS tutorial">Why use CSS</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/How_CSS_works" title="Chapter 'How CSS works' of the CSS tutorial">How CSS works</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Cascading_and_inheritance" title="Chapter 'Cascading and inheritance' of the CSS tutorial">Cascading and inheritance</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors" title="Chapter 'Selectors' of the CSS tutorial">Selectors</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Readable_CSS" title="Chapter 'Readable_CSS' of the CSS tutorial">Readable CSS</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Text_styles" title="Chapter 'Text_styles' of the CSS tutorial">Text styles</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Color" title="Chapter 'Color' of the CSS tutorial">Color</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Content" title="Chapter 'Content' of the CSS tutorial">Content</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Lists" title="Chapter 'Lists' of the CSS tutorial">Lists</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Boxes" title="Chapter 'Boxes' of the CSS tutorial">Boxes</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Layout" title="Chapter 'Layout' of the CSS tutorial">Layout</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Tables" title="Chapter 'Tables' of the CSS tutorial">Tables</a> <a class="button" href="/en-US/docs/Web/Guide/CSS/Getting_Started/Media" title="Chapter 'Media' of the CSS tutorial">Media</a></nav> +<h2 id="What_you_need_to_get_started">What you need to get started</h2> +<ul> + <li>A text editor</li> + <li>A modern browser</li> + <li>Some experience working with a text editor and browser</li> +</ul> +<p>Although the exercises can help you learn, you are not required to complete them. You can simply read the tutorial and look at the pictures.</p> +<p><strong>Note:</strong> The tutorial covers how CSS works with color. It will be easier to complete these sections with a color display and normal color vision.</p> +<h2 id="How_to_use_this_tutorial">How to use this tutorial</h2> +<p>To use this tutorial, read the pages carefully and in sequence. If you skip a page, it may be difficult to understand pages later in the tutorial.</p> +<h3 id="Part_I_The_Basics_of_CSS">Part I: The Basics of CSS</h3> +<p>On each page, use the <em>Information</em> section to understand how CSS works. Use the <em>Action</em> section to try using CSS on your own computer.</p> +<p>To test your understanding, take the challenge at the end of each page. Solutions to the challenges are linked under the challenges, so you don't need to look at them if you don't want to.</p> +<p>To understand CSS in more depth, read the information that you find in boxes captioned <em>More details</em>. Use the links there to find reference information about CSS.</p> +<h3 id="Part_II_The_Scope_of_CSS">Part II: The Scope of CSS</h3> +<p>A second part of the tutorial provides examples, which show the scope of CSS with other web and Mozilla technologies.</p> +<ol> + <li><a href="/en-US/docs/Web/Guide/CSS/Getting_Started/JavaScript" title="en/CSS/Getting_Started/JavaScript">JavaScript</a></li> + <li><a href="/en-US/docs/Web/Guide/CSS/Getting_Started/SVG_and_CSS" title="en/CSS/Getting_Started/SVG_graphics">SVG graphics</a></li> + <li><a href="/en-US/docs/Web/Guide/CSS/Getting_Started/XML_data" title="en/CSS/Getting_Started/XML_data">XML data</a></li> + <li><a href="/en-US/docs/Web/Guide/CSS/Getting_Started/XBL_bindings" title="en/CSS/Getting_Started/XBL_bindings">XBL bindings</a></li> + <li><a href="/en-US/docs/Web/Guide/CSS/Getting_Started/XUL_user_interfaces" title="en/CSS/Getting_Started/XUL_user_interfaces">XUL user interfaces</a></li> +</ol> diff --git a/files/vi/web/guide/html/html5/index.html b/files/vi/web/guide/html/html5/index.html new file mode 100644 index 0000000000..0900e23811 --- /dev/null +++ b/files/vi/web/guide/html/html5/index.html @@ -0,0 +1,173 @@ +--- +title: HTML5 +slug: Web/Guide/HTML/HTML5 +translation_of: Web/Guide/HTML/HTML5 +--- +<p class="summary">HTML5 là phiên bản mới nhất của HTML. Hai phiên bản này khá khác nhau. HTML5 là phiên bản mới về ngôn ngữ, thuộc tính và công nghệ mới cho phép xây dựng các trang web, ứng dụng đa dạng và mạnh mẽ hơn. Hai bản này thường được gọi là HTML5.</p> + +<p class="summary">HTML5 được thiết kế để có thể sử dụng trên tất cả cá nhà phát triển web mở, trang này liên kết với nhiều tài nguyeenn công nghệ HTML5, phân thành nhiều nhóm dựa vào từng chức năng.</p> + +<p class="summary"></p> + +<p class="summary"></p> + +<ul> +</ul> + +<div class="cleared row topicpage-table"> +<div class="section"> +<ul> + <li><em>Ngữ nghĩa:</em> cho phép mô tả chính xác nội dung.</li> + <li><em>Kết nối: </em>cho phép giao tiếp với máy chủ theo nhiều cách.</li> + <li><em>Ngoại tuyến và lưu trữ: </em>cho phép các trang web lưu trữ dữ liệu ở máy khách hàng và hoạt động ngoại tuyến hiệu quả hơn.</li> + <li><em>Đa phương tiện:</em> tạo video và âm thanh trong web mở.</li> + <li><em>Hiệu ứng và đồ họa 2D/3D: </em>cho phép phạm vi trình bày đa dạng hơn.</li> + <li><em>Hiệu suất và tích hợp:</em> tối ưu hóa tốc độ và phần cứng.</li> + <li><em>Truy cập thiết bị: </em>cho phép sử dụng các thiết bị đầu vào và ra khác nhau.</li> + <li><em>Chủ đề:</em> cho phép viết các chủ đề phức tạp.</li> +</ul> + +<h2 id="Ý_nghĩa" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3827/HTML5_Semantics_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">Ý nghĩa</h2> + +<p><a href="https://developer.mozilla.org/en-US/docs/Sections_and_Outlines_of_an_HTML5_document" title="Sections and Outlines of an HTML5 document">Sections and outlines in HTML5</a></p> + +<p>A look at the new outlining and sectioning elements in HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.</p> + +<dl> + <dt><a href="/en-US/docs/Using_HTML5_audio_and_video" title="Using_audio_and_video_in_Firefox">Using HTML5 audio and video</a></dt> + <dd>The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.</dd> + <dt><a href="/en-US/docs/Learn/HTML/Forms">Forms improvements</a></dt> + <dd>A look at the <a href="/en-US/docs/Learn/HTML/Forms/Form_validation">constraint validation API</a>, several new attributes, new values for the {{HTMLElement("input")}} attribute {{htmlattrxref("type", "input")}} and the new {{HTMLElement("output")}} element.</dd> + <dt>New semantic elements</dt> + <dd>Beside sections, media and forms elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the number of <a href="/en-US/docs/HTML/HTML5/HTML5_element_list" title="HTML/HTML5/HTML5_element_list">valid HTML5 elements</a>.</dd> + <dt>Improvement in {{HTMLElement("iframe")}}</dt> + <dd>Using the {{htmlattrxref("sandbox", "iframe")}} and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.</dd> + <dt><a href="/en-US/docs/MathML" title="MathML">MathML</a></dt> + <dd>Allows directly embedding mathematical formulas.</dd> + <dt><a href="/en-US/docs/HTML/HTML5/Introduction_to_HTML5" title="HTML/HTML5/Introduction_to_HTML5">Introduction to HTML5</a></dt> + <dd>This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application.</dd> + <dt><a href="https://websitesetup.org/html5-cheat-sheet/">Downloadable HTML5 Guide</a></dt> + <dd>A quick guide to HTML5, including the common HTML tags as well as the new HTML5 tags. Downloadable in PDF and PNG formats.</dd> + <dt><a href="https://www.wpkube.com/html5-cheat-sheet/">HTML5 Cheat Sheet</a> </dt> + <dd>A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility.</dd> + <dt><a href="/en-US/docs/HTML/HTML5/HTML5_Parser" title="HTML/HTML5/HTML5 parser">HTML5-compliant parser</a></dt> + <dd>The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.</dd> +</dl> + +<h2 id="Connectivity" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3839/HTML5_Connectivity_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">Connectivity</h2> + +<dl> + <dt><a href="/en-US/docs/WebSockets" title="WebSockets">Web Sockets</a></dt> + <dd>Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.</dd> + <dt><a href="/en-US/docs/Server-sent_events/Using_server-sent_events" title="Server-sent_events/Using_server-sent_events">Server-sent events</a></dt> + <dd>Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.</dd> + <dt><a href="/en-US/docs/WebRTC" title="WebRTC">WebRTC</a></dt> + <dd>This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.</dd> +</dl> + +<h2 id="Offline_storage" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3833/HTML5_Offline_Storage_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">Offline & storage</h2> + +<p><a href="/en-US/docs/HTML/Using_the_application_cache" title="Offline_resources_in_Firefox">Offline resources: The application cache</a></p> + +<dl> + <dd>Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.</dd> + <dt><a href="/en-US/docs/Online_and_offline_events" title="Online_and_offline_events">Online and offline events</a></dt> + <dd>Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.</dd> + <dt><a href="/en-US/docs/DOM/Storage" title="DOM/Storage">WHATWG client-side session and persistent storage (aka DOM storage)</a></dt> + <dd>Client-side session and persistent storage allows web applications to store structured data on the client side.</dd> + <dt><a href="/en-US/docs/IndexedDB" title="IndexedDB">IndexedDB</a></dt> + <dd>IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.</dd> + <dt><a href="/en-US/docs/Using_files_from_web_applications" title="Using_files_from_web_applications">Using files from web applications</a></dt> + <dd>Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the <span style="font-family: monospace;">{{HTMLElement("input")}}</span> of <a href="/en-US/docs/HTML/Element/Input#attr-type" title="HTML/Element/input#attr-type"><strong>type</strong></a> <span style="font-family: courier new;">file</span> HTML element's new <a href="/en-US/docs/HTML/Element/Input#attr-multiple" title="HTML/Element/input#attr-multiple"><strong>multiple</strong></a> attribute. There also is <a href="/en-US/docs/DOM/FileReader" title="DOM/FileReader"><code>FileReader</code></a>.</dd> +</dl> + +<h2 id="Multimedia" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3835/HTML5_Multimedia_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">Multimedia</h2> + +<dl> + <dt><a href="/en-US/docs/Using_HTML5_audio_and_video" title="Using_audio_and_video_in_Firefox">Using HTML5 audio and video</a></dt> + <dd>The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.</dd> + <dt><a href="/en-US/docs/WebRTC" title="WebRTC">WebRTC</a></dt> + <dd>This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.</dd> + <dt><a href="/en-US/docs/DOM/Using_the_Camera_API" title="DOM/Using_the_Camera_API">Using the Camera API</a></dt> + <dd>Allows using, manipulating, and storing an image from the computer's camera.</dd> + <dt>Track and WebVTT</dt> + <dd>The {{HTMLElement("track")}} element allows subtitles and chapters. <a href="/en-US/docs/HTML/WebVTT" title="HTML/WebVTT">WebVTT</a> is a text track format.</dd> +</dl> + +<h2 id="2D3D_graphics_AND_effects" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3841/HTML5_3D_Effects_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">2D/3D graphics AND effects</h2> + +<dl> + <dt><a href="/en-US/docs/Canvas_tutorial" title="Canvas tutorial">Canvas tutorial</a></dt> + <dd>Learn about the new <code>{{HTMLElement("canvas")}}</code> element and how to draw graphs and other objects in Firefox.</dd> + <dt><a href="/en-US/docs/Drawing_text_using_a_canvas" title="Drawing_text_using_a_canvas">HTML5 Text API for <code><canvas></code> elements</a></dt> + <dd>The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.</dd> + <dt><a href="/en-US/docs/WebGL" title="WebGL">WebGL</a></dt> + <dd>WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.</dd> + <dt><a href="/en-US/docs/SVG" title="SVG">SVG</a></dt> + <dd>An XML-based format of vectorial images that can directly be embedded in the HTML.</dd> +</dl> +</div> + +<div class="section"> +<h2 id="Performance_and_Integration" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3831/HTML5_Performance_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">Performance and Integration</h2> + +<dl> + <dt><a href="/en-US/docs/DOM/Using_web_workers" title="Using web workers">Web Workers</a></dt> + <dd>Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.</dd> + <dt><code><a href="/en-US/docs/DOM/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a></code> level 2</dt> + <dd>Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind <a href="/en-US/docs/AJAX" title="AJAX">Ajax</a>.</dd> + <dt>JIT-compiling JavaScript engines</dt> + <dd>The new generation of JavaScript engines is much more powerful, leading to greater performance.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history" title="DOM/Manipulating_the_browser_history">History API</a></dt> + <dd>Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.</dd> + <dt><a href="/en-US/docs/HTML/Content_Editable" title="HTML/Content Editable">The contentEditable Attribute: Transform your website to a wiki!</a></dt> + <dd>HTML5 has standardized the contentEditable attribute. Learn more about this feature.</dd> + <dt><a href="/en-US/docs/DragDrop/Drag_and_Drop" title="DragDrop/Drag_and_Drop">Drag and drop</a></dt> + <dd>The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.</dd> + <dt><a href="/en-US/docs/Focus_management_in_HTML" title="Focus_management_in_HTML">Focus management in HTML</a></dt> + <dd>The new HTML5 <code>activeElement</code> and <code>hasFocus</code> attributes are supported.</dd> + <dt><a href="/en-US/docs/Web-based_protocol_handlers" title="Web-based_protocol_handlers">Web-based protocol handlers</a></dt> + <dd>You can now register web applications as protocol handlers using the <code>navigator.registerProtocolHandler()</code> method.</dd> + <dt><a href="/en-US/docs/Web/API/Window/requestAnimationFrame" style="font-weight: bold;" title="Web-based_protocol_handlers">requestAnimationFrame</a></dt> + <dd>Allows control of animations rendering to obtain optimal performance.</dd> + <dt><a href="/en-US/docs/DOM/Using_full-screen_mode" title="DOM/Using_full-screen_mode">Fullscreen API</a></dt> + <dd>Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.</dd> + <dt><a href="/en-US/docs/API/Pointer_Lock_API" title="API/Pointer_Lock_API">Pointer Lock API</a></dt> + <dd>Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.</dd> + <dt><a href="/en-US/docs/Online_and_offline_events" title="Online_and_offline_events">Online and offline events</a></dt> + <dd>In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.</dd> +</dl> + +<h2 id="Device_access" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3837/HTML5_Device_Access_512.png" style="height: 66px; padding-right: 0.5em; vertical-align: middle; width: 77px;">Device access</h2> + +<dl> + <dt><a href="/en-US/docs/DOM/Using_the_Camera_API" title="DOM/Using_the_Camera_API">Using the Camera API</a></dt> + <dd>Allows using, manipulating, and storing an image from the computer's camera.</dd> + <dt><a href="/en-US/docs/DOM/Touch_events" title="DOM/Touch_events">Touch events</a></dt> + <dd>Handlers to react to events created by a user pressing touch screens.</dd> + <dt><a href="/en-US/docs/Using_geolocation" title="Using geolocation">Using geolocation</a></dt> + <dd>Let browsers locate the position of the user using geolocation.</dd> + <dt><a href="/en-US/docs/Detecting_device_orientation" title="Detecting_device_orientation">Detecting device orientation</a></dt> + <dd>Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).</dd> + <dt><a href="/en-US/docs/API/Pointer_Lock_API" title="API/Pointer_Lock_API">Pointer Lock API</a></dt> + <dd>Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.</dd> +</dl> + +<h2 id="StylIng" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3829/HTML5_Styling_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">StylIng</h2> + +<p id="CSS_has_been_extended_to_be_able_to_style_elements_in_a_much_more_complex_way._This_is_often_referred_as_CSS3_though_CSS_is_not_a_monolithic_specification_any_more_and_the_different_modules_are_not_all_at_level_3_some_are_at_level_1_and_others_at_level_4_with_all_the_intermediate_levels_covered."><a href="/en-US/docs/CSS" title="CSS">CSS</a> has been extended to be able to style elements in a much more complex way. This is often referred as <a href="/en-US/docs/CSS/CSS3" title="CSS/CSS3">CSS3</a>, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.</p> + +<dl> + <dt>New background styling features</dt> + <dd>It is now possible to put shadows on elements using {{cssxref("box-shadow")}}, <a href="/en-US/docs/CSS/Multiple_backgrounds" title="CSS/Multiple_backgrounds">multiple backgrounds</a>, and CSS {{cssxref("filter")}}s. You can learn more about these by reading <a href="/en-US/docs/Learn/CSS/Styling_boxes/Advanced_box_effects">Advanced box effects</a>.</dd> + <dt>More fancy borders</dt> + <dd>Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.</dd> + <dt>Animating your style</dt> + <dd>Using <a href="/en-US/docs/CSS/Using_CSS_transitions" title="CSS/Using_CSS_transitions">CSS Transitions</a> to animate between different states or using <a href="/en-US/docs/CSS/Using_CSS_animations" title="CSS/Using_CSS_animations">CSS Animations</a> to animate parts of the page without a triggering event, you can now control mobile elements on your page.</dd> + <dt>Typography improvement</dt> + <dd>Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and <a href="/en-US/docs/CSS/hyphens" title="CSS/hyphens">hyphenation</a>, but also can add a <a href="/en-US/docs/CSS/text-shadow" title="CSS/text-shadow">shadow</a> to it or control more precisely its <a href="/en-US/docs/CSS/text-decoration" title="SVG/Attribute/text-decoration">decorations</a>. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.</dd> + <dt>New presentational layouts</dt> + <dd>In order to improve the flexibility of designs, two new layouts have been added: the <a href="/en-US/docs/CSS/Using_CSS_multi-column_layouts" title="CSS/Using_CSS_multi-column_layouts">CSS multi-column layouts</a> and <a href="/en-US/docs/CSS/Flexbox" title="CSS/Flexbox">CSS flexible box layout</a>.</dd> +</dl> +</div> +</div> diff --git a/files/vi/web/guide/index.html b/files/vi/web/guide/index.html new file mode 100644 index 0000000000..00f533cf85 --- /dev/null +++ b/files/vi/web/guide/index.html @@ -0,0 +1,72 @@ +--- +title: Web developer guide +slug: Web/Guide +tags: + - Guide + - Landing + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/Guide +--- +<p><strong>Các bài dưới đây cung cấp những thông tin cần thiết nhằm giúp bạn tận dụng các công nghệ và API cụ thể.</strong></p> + +<div> +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML">HTML Learning Area</a></dt> + <dd><strong>HyperText Markup Language (HTML)</strong> là ngôn ngữ nền tảng của gần như toàn bộ các thành phần trong một trang Web. Hầu hết mọi thứ hiển thị trên màn hình của bạn đều được định dạng bởi HTML.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS">CSS Learning Area</a></dt> + <dd class="landingPageList">Cascading Style Sheets (CSS) là một ngôn ngữ quy định cách trình bày, được dùng để định ra các quy tắc thể hiện một tài liệu HTML.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery">Audio and video delivery</a></dt> + <dd>Video và audio có thể được cung cấp trên môi trường web thông qua một số cách, từ các file media tĩnh đến adaptive live streams. Bài này là một khởi điểm cho việc tìm hiểu về các phương thức cung cấp khác nhau cho web based media và sự tương thích với các trình duyệt thông dụng.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_manipulation">Audio and video manipulation</a></dt> + <dd>Sự tuyệt vời của web đó là chúng ta có thể tổ hợp các công nghệ khác nhau để tạo nên một dạng mới. Chẳng hạn như kết hợp các công nghệ Canvas, <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL">WebGL</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a> để thay đổi audio và video. Bài này cung cấp các tham khảo để giải thích những gì mà bạn cần để làm điều đó.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Events">Event developer guide</a></dt> + <dd class="landingPageList">Events liên hệ đến 2 vấn đề: nó là một design pattern sử dụng cho việc handling các sự kiện bất đồng bộ xảy ra đối với 1 web page; và nó là tên gọi chung, đặc tính của các sự kiện bất ngờ khác nhau xảy ra.</dd> + <dt><a href="/en-US/docs/Web/Guide/AJAX">AJAX</a></dt> + <dd>AJAX là một khái niệm xác định một nhóm các công nghệ cho phép tạo ra các ứng dụng web động nhanh nhạy cho giao diện người dùng mà không phải tải lại nguyên trang. Nó hỗ trợ các ứng dụng xử lý nhanh và hiệu quả hơn khi thực hiện tác vụ. </dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Graphics">Graphics on the Web</a></dt> + <dd class="landingPageList">Các trang Web và ứng dụng hiện đại thường cần hiển thị đồ hoạ với sự tinh tế riêng biệt.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API">Guide to Web APIs</a></dt> + <dd class="landingPageList">Danh sách những Web API và phương thức hoạt động của chúng.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/JavaScript" title="/en-US/docs/JavaScript">JavaScript</a></dt> + <dd>JavaScript là ngôn ngữ lập trình thông dịch cực kỳ mạnh mẽ, được dùng để khởi tạo các ứng dụng cho trang Web.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Localizations_and_character_encodings">Localizations a character encodings</a></dt> + <dd class="landingPageList">Trình duyệt xử lý văn bản dưới dạng Unicode. Tuy nhiên, trong quá trình truyền dữ liệu đến trình duyệt, các ký tự được biểu diễn dưới dạng bytes (mã hóa ký tự). Đặc tả HTML khuyến nghị việc sử dụng phương thức mã hóa UTF-8 (có thể biểu diễn được tất cả ký tự Unicode), bất kể hình thức khai báo mã hóa nào được yêu cầu.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Mobile">Mobile Web Development</a></dt> + <dd class="landingPageList">Bài này cung cấp một cái nhìn tổng quát về một vài công nghệ chính được sử dụng để thiết kế web sites có thể hoạt động tốt trên các thiết bị di động. Xem thêm tại <a href="https://developer.mozilla.org/en/Mozilla/Firefox_for_Android">Firefox for Android</a>.</dd> +</dl> + +<dl> +</dl> +</div> + +<div class="section"> +<dl> + <dt class="landingPageList"> </dt> + <dt><a href="https://developer.mozilla.org/en-US/Apps/Progressive#Core_PWA_guides">Progressive web apps</a></dt> + <dd>Progressive web apps (PWAs) sử dụng các web APIs tiên tiến cùng với chiến lược phát triển lũy tiến để tạo nên một web application đa nền tảng. Các apps này hoạt động được trên mọi thiết bị và cung cấp các tính năng đem lại trải nghiệm của một native app. Các bài hướng dẫn này sẽ cung cấp cho bạn các kiến thức cần thiết về PWAs.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Performance">Optimization and performance</a></dt> + <dd>Khi xây dựng web apps và site hiện nay, điều quan trọng đó là làm sao để chúng hoạt động một cách nhanh nhất và hiệu quả nhất. Chính điều này đem lại cho chúng khả năng hoạt động hiệu quả trên cả các thiết bị desktop với cấu hình mạnh mẽ và các thiết bị handheld với cấu hình yếu.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML">Parsing and serializing XML</a></dt> + <dd>Nền tảng web cung cấp các phương thức cho việc parsing và serializing XML, mỗi phương thức với các điểm mạnh và yếu khác nhau.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/WOFF">The Web Open Font Format (WOFF)</a></dt> + <dd>WOFF là một kiểu file cho font chữ được cung cấp miễn phí cho bất kỳ ai có nhu cầu sử dụng cho web.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects">Using FormData objects</a></dt> + <dd>FormData giúp cho việc tạo nên tổ hợp các key/value để gửi thông qua XMLHttpRequest. Mục đích ban đầu của nó là gửi dữ liệu form, nhưng nó cũng có thể hoạt động 1 cách độc lập với form để gửi các dữ liệu khác nhau. Cách thức truyền nhận tương tự như khi một form với type "multipart/form-data" thực thi method <code>submit()</code> .</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/User_input_methods">User input and controls</a></dt> + <dd>Input người dùng web hiện nay không chỉ đơn giản là chuột và bàn phím mà còn có các phương thức khác, chẳng hạn touchscreen. Bài này cung cấp các recommendations cho việc quản lý input người dùng và hiện thực việc điều khiển đối với web apps, cùng với các FAQs, ví dụ thực tế và đường dẫn đến các thông tin khác nếu bạn cần tìm hiểu chi tiết thêm về các công nghệ bên dưới.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Glossary">Glossary</a></dt> + <dd>Định nghĩa các khái niệm kỹ thuật liên quan đến Web và Internet.</dd> +</dl> +</div> +</div> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/Reference" title="/en-US/docs/Web/Reference">Web Developer Reference</a></li> +</ul> diff --git a/files/vi/web/html/element/center/index.html b/files/vi/web/html/element/center/index.html new file mode 100644 index 0000000000..8303b88549 --- /dev/null +++ b/files/vi/web/html/element/center/index.html @@ -0,0 +1,55 @@ +--- +title: '<center>: The Centered Text element (obsolete)' +slug: Web/HTML/Element/center +translation_of: Web/HTML/Element/center +--- +<div>{{obsolete_header}}</div> + +<p><span class="seoSummary"><strong>Phần tử trung tâm HTML</strong> lỗi thời ( <strong><code><center></code></strong>) là <a href="/en-US/docs/HTML/Block-level_elements" title="HTML / Block-level_elements">phần tử cấp</a> khối hiển thị nội dung cấp khối hoặc nội dòng được căn giữa theo chiều ngang bên trong phần tử chứa nó. </span>Vùng chứa thường là, nhưng không bắt buộc, {{HTMLElement ("body")}}.</p> + +<p>Thẻ này đã không được chấp nhận trong HTML 4 (và XHTML 1) vì thuộc tính <a href="/en-US/docs/Web/CSS" title="/ en-US / docs / Web / CSS">CSS</a> {{Cssxref("text-align")}}, có thể được áp dụng cho phần tử {{HTMLElement ("div")}} hoặc cho một cá nhân {{HTMLElement("p")}}. Đối với các khối căn giữa, hãy sử dụng các thuộc tính CSS khác như {{Cssxref ("margin-left")}} và {{Cssxref ("margin-right")}} và đặt chúng thành <code>auto</code>(hoặc đặt {{Cssxref ("margin")}} đến <code>0 auto</code>).</p> + +<h2 id="Giao_diện_DOM">Giao diện DOM</h2> + +<p>Phần tử này thực hiện giao diện {{domxref ("HTMLElement")}}.</p> + +<div class="note"> +<p><strong>Lưu ý triển khai:</strong> bao gồm cả Gecko 1.9.2, Firefox triển khai giao diện {{domxref("HTMLSpanElement")}} cho phần tử này.</p> +</div> + +<h2 id="ví_dụ_1">ví dụ 1</h2> + +<pre class="brush: html notranslate"><center> Văn bản này sẽ được căn giữa. +<p> Đoạn này cũng vậy. </p> </center> +</pre> + +<h2 id="Ví_dụ_2_CSS_thay_thế">Ví dụ 2 (CSS thay thế)</h2> + +<pre class="brush: html notranslate"><div style = "text-align: center"> Văn bản này sẽ được căn giữa. +<p> Đoạn này cũng vậy. </p> </div> +</pre> + +<h2 id="Ví_dụ_3_CSS_thay_thế">Ví dụ 3 (CSS thay thế)</h2> + +<pre class="brush: html notranslate"><p style = "text-align: center"> Dòng này sẽ được căn giữa. <br> +Và dòng này cũng vậy. </p> +</pre> + +<h2 id="Ghi_chú">Ghi chú</h2> + +<p>Việc áp dụng {{Cssxref ("text-align")}} <code>:center</code>cho phần tử {{HTMLElement("div")}} hoặc {{HTMLElement("p")}} sẽ căn giữa <em>nội dung</em> của các phần tử đó trong khi giữ nguyên kích thước tổng thể của chúng.</p> + +<h2 id="Tính_tương_thích_của_trình_duyệt_web">Tính tương thích của trình duyệt web</h2> + +<div class="hidden">Bảng tương thích trong trang này được tạo từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp vào dữ liệu, vui lòng xem <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi yêu cầu kéo cho chúng tôi.</div> + +<p>{{Compat("html.elements.center")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{Cssxref("text-align")}}</li> + <li>{{Cssxref("hiển thị")}}</li> +</ul> + +<div>{{HTMLRef}}</div> diff --git a/files/vi/web/html/element/dialog/index.html b/files/vi/web/html/element/dialog/index.html new file mode 100644 index 0000000000..d6d63404b4 --- /dev/null +++ b/files/vi/web/html/element/dialog/index.html @@ -0,0 +1,163 @@ +--- +title: '<dialog>: Phần tử Hộp thoại' +slug: Web/HTML/Element/dialog +tags: + - Dialog + - HTML + - Hộp thoại + - Phần tử + - Phần tử HTML tương tác được + - Tham khảo + - Thử nghiệm + - Web +translation_of: Web/HTML/Element/dialog +--- +<p><strong>Phần tử HTML</strong> <code><dialog></code> đại diện cho một hộp thoại hoặc một component tương tác được, chẳng hạn như giao diện cửa sổ hoặc khảo sát.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><a href="/en-US/docs/Web/HTML/Content_categories">Loại nội dung</a></th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">Flow content</a>, <a href="/en-US/docs/Web/HTML/Sections_and_Outlines_of_an_HTML5_document#Sectioning_roots">sectioning root</a></td> + </tr> + <tr> + <th scope="row">Nội dung cho phép</th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">Flow content</a></td> + </tr> + <tr> + <th scope="row">Thẻ được phép bỏ</th> + <td>{{no_tag_omission}}</td> + </tr> + <tr> + <th scope="row">Thẻ cha cho phép</th> + <td>Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">flow content</a></td> + </tr> + <tr> + <th scope="row">ARIA role cho phép</th> + <td>{{ARIARole("alertdialog")}}</td> + </tr> + <tr> + <th scope="row">Giao diện lập trình DOM</th> + <td>{{domxref("HTMLDialogElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<p>Phần tử này có các <a href="/en-US/docs/Web/HTML/Global_attributes">thuộc tính chung</a>. Thuộc tính <code>tabindex</code> không được phép sử dụng với phần tử <code><dialog></code>.</p> + +<dl> + <dt>{{htmlattrdef("open")}}</dt> + <dd>Cho biết hộp thoại có được kích hoạt và sẵn sàng tương tác hay không. Khi thuộc tính open này không được bật (không có trong thẻ), hộp thoại sẽ không hiện ra cho người dùng.</dd> +</dl> + +<h2 id="Lưu_ý_khi_sử_dụng">Lưu ý khi sử dụng</h2> + +<ul> + <li>Phần tử <code><form></code> có thể được tính hợp với dialog bằng cách thêm thuộc tính <code>method="dialog"</code> tại <code><form></code> bên trong. Khi form được gửi đi, hộp thoại sẽ đóng lại với <code>returnValue</code> là giá trị <code>value</code> của nút submit được bấm.</li> + <li>CSS pseudo-element {{cssxref('::backdrop')}} là một phần tử giả phía sau hộp thoại dùng để che đi hoặc làm mờ nội dung bên dưới khi mà hộp thoại đang hiện ra. Backdrop chỉ được hiển thị khi phần tử dialog được hiện với <code>dialog.showModal()</code>.</li> +</ul> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Ví_dụ_đơn_giản">Ví dụ đơn giản</h3> + +<pre class="brush: html"><dialog open> + <p>Greetings, one and all!</p> +</dialog> +</pre> + +<h3 id="Ví_dụ_nâng_cao">Ví dụ nâng cao</h3> + +<p>Trong ví dụ này, một hộp thoại sẽ hiện ra với một form bên trong khi mà nút "Update details" được bấm.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><!-- Simple pop-up dialog box containing a form --> +<dialog id="favDialog"> + <form method="dialog"> + <p><label>Favorite animal: + <select> + <option></option> + <option>Brine shrimp</option> + <option>Red panda</option> + <option>Spider monkey</option> + </select> + </label></p> + <menu> + <button>Cancel</button> + <button>Confirm</button> + </menu> + </form> +</dialog> + +<menu> + <button id="updateDetails">Update details</button> +</menu> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">(function() { + var updateButton = document.getElementById('updateDetails'); + var favDialog = document.getElementById('favDialog'); + + // “Update details” button opens the <dialog> modally + updateButton.addEventListener('click', function() { + favDialog.showModal(); + }); +})(); +</pre> + +<h3 id="Kết_quả_nhận_được">Kết quả nhận được</h3> + +<p>{{EmbedLiveSample("Ví_dụ_nâng_cao", "100%", 300)}}</p> + +<p>Nút submit nào được bấm có thể được xác định với <a href="/en-US/docs/Web/API/HTMLDialogElement/returnValue">returnValue</a> của <code>favDialog</code>.</p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'forms.html#the-dialog-element', '<dialog>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5.2', 'interactive-elements.html#the-dialog-element', '<dialog>')}}</td> + <td>{{Spec2('HTML5.2')}}</td> + <td>Định nghĩa ban đầu.</td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + + + +<p>{{Compat("html.elements.dialog")}}</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Dùng polyfill sau để hỗ trợ <code><dialog></code> cho các trình duyệt cũ:</p> + +<p><a href="https://github.com/GoogleChrome/dialog-polyfill">dialog-polyfill</a></p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>Sự kiện {{event("close")}}</li> + <li>Sự kiện {{event("cancel")}}</li> + <li><a href="/en-US/docs/Web/Guide/HTML/Forms">Hướng dẫn HTML form</a>.</li> +</ul> + +<div>{{HTMLRef}}</div> diff --git a/files/vi/web/html/element/em/index.html b/files/vi/web/html/element/em/index.html new file mode 100644 index 0000000000..3f52dea31a --- /dev/null +++ b/files/vi/web/html/element/em/index.html @@ -0,0 +1,122 @@ +--- +title: '<em>: The Emphasis element' +slug: Web/HTML/Element/em +translation_of: Web/HTML/Element/em +--- +<div>{{HTMLRef}}</div> + +<p>The <strong>HTML <code><em></code> element</strong> marks text that has stress emphasis. The <code><em></code> element can be nested, with each level of nesting indicating a greater degree of emphasis.</p> + +<div>{{EmbedInteractiveExample("pages/tabbed/em.html", "tabbed-shorter")}}</div> + + + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a></th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">Flow content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>, palpable content.</td> + </tr> + <tr> + <th scope="row">Permitted content</th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">Phrasing content</a>.</td> + </tr> + <tr> + <th scope="row">Tag omission</th> + <td>{{no_tag_omission}}</td> + </tr> + <tr> + <th scope="row">Permitted parents</th> + <td>Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>.</td> + </tr> + <tr> + <th scope="row">Implicit ARIA role</th> + <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role">No corresponding role</a></td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td>Any</td> + </tr> + <tr> + <th scope="row">DOM interface</th> + <td>{{domxref("HTMLElement")}} Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the {{domxref("HTMLSpanElement")}} interface for this element.</td> + </tr> + </tbody> +</table> + +<h2 id="Attributes">Attributes</h2> + +<p>This element only includes the <a href="/en-US/docs/Web/HTML/Global_attributes">global attributes</a>.</p> + +<h2 id="Usage_notes">Usage notes</h2> + +<p>The <code><em></code> element is for words that have a stressed emphasis compared to surrounding text, which is often limited to a word or words of a sentence and affects the meaning of the sentence itself.</p> + +<p>Typically this element is displayed in italic type. However, it should not be used simply to apply italic styling; use the CSS {{cssxref("font-style")}} property for that purpose. Use the {{HTMLElement("cite")}} element to mark the title of a work (book, play, song, etc.). Use the {{HTMLElement("i")}} element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages. Use the {{HTMLElement("strong")}} element to mark text that has greater importance than surrounding text.</p> + +<h3 id="<i>_vs._<em>"><i> vs. <em></h3> + +<p>New developers are often confused at seeing multiple elements that produce similar results. <code><em></code> and <code><i></code> are a common example, since they both italicize text. What's the difference? Which should you use?</p> + +<p>By default, the visual result is the same. However, the semantic meaning is different. The <code><em></code> element represents stress emphasis of its contents, while the <code><i></code> element represents text that is set off from the normal prose, such a foreign word, fictional character thoughts, or when the text refers to the definition of a word instead of representing its semantic meaning. (The title of a work, such as the name of a book or movie, should use <code><cite></code>.)</p> + +<p>This means the right one to use depends on the situation. Neither is for purely decorational purposes, that's what CSS styling is for.</p> + +<p>An example for <code><em></code> could be: "Just <em>do</em> it already!", or: "We <em>had</em> to do something about it". A person or software reading the text would pronounce the words in italics with an emphasis, using verbal stress.</p> + +<p>An example for <code><i></code> could be: "The <em>Queen Mary</em> sailed last night". Here, there is no added emphasis or importance on the word "Queen Mary". It is merely indicated that the object in question is not a queen named Mary, but a ship named<em> Queen Mary</em>. Another example for <code><i></code> could be: "The word <em>the</em> is an article".</p> + +<h2 id="Example">Example</h2> + +<p>The <code><em></code> element is often used to indicate an implicit or explicit contrast.</p> + +<pre class="brush: html notranslate"><p> + In HTML 5, what was previously called + <em>block-level</em> content is now called + <em>flow</em> content. +</p></pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample("Example")}}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'text-level-semantics.html#the-em-element', '<em>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'textlevel-semantics.html#the-em-element', '<em>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'struct/text.html#h-9.2.1', '<em>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + + + +<p>{{Compat("html.elements.em")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{HTMLElement("i")}}</li> +</ul> diff --git a/files/vi/web/html/element/header/index.html b/files/vi/web/html/element/header/index.html new file mode 100644 index 0000000000..6b3f3a7ecc --- /dev/null +++ b/files/vi/web/html/element/header/index.html @@ -0,0 +1,142 @@ +--- +title: <header> +slug: Web/HTML/Element/header +translation_of: Web/HTML/Element/header +--- +<div>{{HTMLRef}}</div> + +<p>The <strong>HTML <code><header></code> element</strong> represents a group of introductory or navigational aids. It may contain some heading elements but also other elements like a logo, a search form, and so on.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><a href="/en-US/docs/HTML/Content_categories">Content categories</a></th> + <td><a href="/en-US/docs/HTML/Content_categories#Flow_content">Flow content</a>, palpable content.</td> + </tr> + <tr> + <th scope="row">Permitted content</th> + <td><a href="/en-US/docs/HTML/Content_categories#Flow_content">Flow content</a>, but with no <code><header></code> or {{HTMLElement("footer")}} descendant.</td> + </tr> + <tr> + <th scope="row">Tag omission</th> + <td>{{no_tag_omission}}</td> + </tr> + <tr> + <th scope="row">Permitted parents</th> + <td>Any element that accepts <a href="/en-US/docs/HTML/Content_categories#Flow_content">flow content</a>. Note that a <code><header></code> element must not be a descendant of an {{HTMLElement("address")}}, {{HTMLElement("footer")}} or another {{HTMLElement("header")}} element.</td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td>{{ARIARole("group")}}, {{ARIARole("presentation")}}</td> + </tr> + <tr> + <th scope="row">DOM interface</th> + <td>{{domxref("HTMLElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Usage_notes">Usage notes</h2> + +<p>The <code><header></code> element is not sectioning content and therefore does not introduce a new section in the <a href="/en-US/docs/Sections_and_Outlines_of_an_HTML5_document">outline</a>. That said, a <code>header</code> element is intended to usually contain the surrounding <code>section</code>'s heading (an <code>h1</code>–<code>h6</code> element), but this is <strong>not</strong> required.</p> + +<h2 id="Attributes">Attributes</h2> + +<p>This element only includes the <a href="/en-US/docs/HTML/Global_attributes">global attributes</a>.</p> + +<h2 id="Example">Example</h2> + +<pre class="brush: html"><header> + <h1>Main Page Title</h1> + <img src="mdn-logo-sm.png" alt="MDN logo"> +</header> +</pre> + +<h1 id="Main_Page_Title">Main Page Title</h1> + +<h2 id="sect1"><img alt="MDN" src="https://developer.cdn.mozilla.net/media/img/mdn-logo-sm.png"></h2> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'semantics.html#the-header-element', '<header>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'sections.html#the-header-element', '<header>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>5</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>9.0</td> + <td>11.10</td> + <td>4.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.2</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>9.0</td> + <td>11.0</td> + <td>5.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Others section-related elements: {{HTMLElement("body")}}, {{HTMLElement("nav")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("footer")}}, {{HTMLElement("section")}}, {{HTMLElement("address")}}.</li> + <li class="last"><a class="deki-ns current" href="/en-US/docs/Web/Guide/HTML/Sections_and_Outlines_of_an_HTML5_document">Sections and outlines of a HTML5 document</a>.</li> +</ul> diff --git a/files/vi/web/html/element/html/index.html b/files/vi/web/html/element/html/index.html new file mode 100644 index 0000000000..8609afe4a2 --- /dev/null +++ b/files/vi/web/html/element/html/index.html @@ -0,0 +1,109 @@ +--- +title: <html> +slug: Web/HTML/Element/html +tags: + - HTML + - Phần tử + - Phần tử gốc HTML + - Tài liệu tham khảo + - Web +translation_of: Web/HTML/Element/html +--- +<p>{{HTMLRef}}</p> + +<p>The <strong>HTML <code><html></code> element</strong> represents the root (top-level element) of an HTML document, so it is also referred to as the <em>root element</em>. All other elements must be descendants of this element.</p> + +<table class="properties"> + <tbody> + <tr> + <th><a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a></th> + <td>None.</td> + </tr> + <tr> + <th>Permitted content</th> + <td>One {{HTMLElement("head")}} element, followed by one {{HTMLElement("body")}} element.</td> + </tr> + <tr> + <th>Tag omission</th> + <td>The start tag may be omitted if the first thing inside the <code><html></code> element is not a comment.<br> + The end tag may be omitted if the <code><html></code> element is not immediately followed by a comment, and it contains a {{HTMLElement("body")}} element either that is not empty or whose start tag is present.</td> + </tr> + <tr> + <th>Perimitted parents</th> + <td>As the root element of a document, or wherever a subdocument fragment is allowed in a compound document.</td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td>None</td> + </tr> + <tr> + <th>DOM interface</th> + <td>{{domxref("HTMLHtmlElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Attributes">Attributes</h2> + +<p>This element includes the <a href="/en-US/docs/Web/HTML/Global_attributes">global attributes</a>.</p> + +<dl> + <dt>{{htmlattrdef("manifest")}} {{obsolete_inline}}</dt> + <dd>Specifies the URI of a resource manifest indicating resources that should be cached locally. See <a href="/en-US/docs/Web/HTML/Using_the_application_cache">Using the application cache</a> for details.</dd> + <dt>{{htmlattrdef("version")}} {{obsolete_inline}}</dt> + <dd>Specifies the version of the HTML {{glossary("DTD", "Document Type Definition")}} that governs the current document. This attribute is not needed, because it is redundant with the version information in the document type declaration.</dd> + <dt>{{htmlattrdef("xmlns")}} </dt> + <dd>Specifies the XML Namespace of the document. Default value is <code>"http://www.w3.org/1999/xhtml"</code>. This is required in documents parsed with XML parsers, and optional in text/html documents.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head>...</head> + <body>...</body> +</html> +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'semantics.html#the-html-element', '<html>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'semantics.html#the-html-element', '<html>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Added support for the <code>manifest</code> attribute (deprecated later).<br> + Obsoleted the <code>version</code> attribute</td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'struct/global.html#h-7.3', '<html>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td>Deprecated the <code>version</code> attribute</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("html.elements.html")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>MathML top-level element: {{MathMLElement("math")}}</li> + <li>SVG top-level element: {{SVGElement("svg")}}</li> +</ul> diff --git a/files/vi/web/html/element/index.html b/files/vi/web/html/element/index.html new file mode 100644 index 0000000000..4823538f65 --- /dev/null +++ b/files/vi/web/html/element/index.html @@ -0,0 +1,86 @@ +--- +title: Phần tử HTML +slug: Web/HTML/Element +translation_of: Web/HTML/Element +--- +<p>{{HTMLSidebar("Elements")}}</p> + +<p>Trang này bao gồm {{Glossary("HTML"){{Glossary("Element","elements")}}<span class="seoSummary">.</span> Chúng được chia thành các nhóm bởi chức năng với mong muốn giúp bạn dễ dàng tìm kiếm để có thể đạt được điều mà bạn có trong tâm trí một cách dễ dàng . Dù cho bản hướng dẫn này được viết ra để dành cho những người mới hoặc những người mới bắt đầu trong việc mã hóa, chúng tôi mong rằng đây có thể là tài liệu tham khảo hữu ích cho tất cả mọi người. </p> + +<h2 id="Các_phần_tử_căn_bản">Các phần tử căn bản</h2> + +<p>Các phần tử căn bản là cột sống cho tất cả các văn bản HTML nào. bạn sẽ thấy rằng những nguyên tố này nằm trong mã nguồn của bất cứ trang web nào đằng sau dòng trên cùng khai báo hiệu trang đó. Dòng khai báo xác định loại phiên bản (X)HTML mà trang đó sử dụng. Các phần tử được đặt giữa thẻ <html> mở và thẻ </html> đóng, đồng thời cũng được gọi là phần tử gốc.</p> + +<p>{{HTMLRefTable("HTML Root Element")}}</p> + +<h2 id="Document_metadata" style="line-height: 30px; font-size: 2.14285714285714rem;">Document metadata</h2> + +<p>Metadata contains information about the page. This includes information about styles, scripts and data to help software (Search engines, {{Glossary("Browser","browsers")}}, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that has the information. </p> + +<p>{{HTMLRefTable("HTML document metadata")}}</p> + +<h2 id="Phân_chia_nội_dung" style="line-height: 30px; font-size: 2.14285714285714rem;">Phân chia nội dung</h2> + +<p>Các phần tử chia thành các mục giúp bạn trình bày nội dung tài liệu một cách loogic. Sử dụng các phần tử phân chia nội dung để tạo ra hình thể rộng cho nội dung trang, bao gồm tiêu đề và chân trang, và phần tử tiêu đề để đánh dấu phần nội dung.</p> + +<p>{{HTMLRefTable("HTML sections")}}</p> + +<h2 id="Text_content" style="line-height: 30px; font-size: 2.14285714285714rem;">Text content</h2> + +<p>Use HTML text content elements to organize blocks or sections of content placed between the opening <body> and closing </body> tags. Important for {{Glossary("accessibility")}} and {{Glossary("SEO")}}, these elements identify the purpose or structure of that content. </p> + +<p>{{HTMLRefTable("HTML grouping content")}}</p> + +<h2 id="Inline_text_semantics" style="line-height: 30px; font-size: 2.14285714285714rem;">Inline text semantics</h2> + +<p>Sử dụng ngữ nghĩa văn bản bên trong HTML để xác định ý nghĩa, cấu trúc hoặc kiểu của từ, dòng hoặc bất kỳ phần văn bản tùy ý nào</p> + +<p>{{HTMLRefTable("HTML text-level semantics")}}</p> + +<h2 id="Image_multimedia" style="line-height: 30px; font-size: 2.14285714285714rem;">Image & multimedia</h2> + +<p>HTML allows to use various multimedia ressources such as images, audio and video.</p> + +<p>{{HTMLRefTable("multimedia")}}</p> + +<h2 id="embedded_content" style="line-height: 30px; font-size: 2.14285714285714rem;">embedded content</h2> + +<p>Beyond multimedia contents HTML can include many other stuff, even if it's not always easy to interact with.</p> + +<p>{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}</p> + +<h2 id="Scripting" style="line-height: 30px; font-size: 2.14285714285714rem;">Scripting</h2> + +<p>{{HTMLRefTable("HTML scripting")}}</p> + +<h2 id="Edits" style="line-height: 30px; font-size: 2.14285714285714rem;">Edits</h2> + +<p>{{HTMLRefTable("HTML edits")}}</p> + +<h2 id="Table_content" style="line-height: 30px; font-size: 2.14285714285714rem;">Table content</h2> + +<p>Those set of elements is specificaly made to handle tabular data</p> + +<p>{{HTMLRefTable("HTML tabular data")}}</p> + +<h2 id="Forms" style="line-height: 30px; font-size: 2.14285714285714rem;">Forms</h2> + +<p>{{HTMLRefTable("HTML forms")}}</p> + +<h2 id="Interactive_elements" style="line-height: 30px; font-size: 2.14285714285714rem;">Interactive elements</h2> + +<p>{{HTMLRefTable("HTML interactive elements")}}</p> + +<h2 id="Web_Components" style="line-height: 30px; font-size: 2.14285714285714rem;">Web Components</h2> + +<div class="note"><strong>Those </strong>elements are defined in the {{Glossary("W3C","World Wide Web Consortium")}} (W3C) <a href="http://www.w3.org/TR/components-intro/" title="http://www.w3.org/TR/components-intro/">Web Components collection of specifications</a> rather than the HTML specification.</div> + +<p>{{HTMLRefTable({"include":["Web Components"],"elements":["decorator","shadow"]})}}</p> + +<h2 id="Obsolete_and_deprecated_elements" style="line-height: 30px; font-size: 2.14285714285714rem;">Obsolete and deprecated elements</h2> + +<div class="warning" style="font-size: 14px;"> +<p>Some old HTML elements were deprecated and their usage is strongly discouraged. <strong>You should never use them for new project, and replace them in old projects.</strong> There are listed here for information only.</p> +</div> + +<p>{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}</p> diff --git a/files/vi/web/html/element/meta/index.html b/files/vi/web/html/element/meta/index.html new file mode 100644 index 0000000000..861a343c66 --- /dev/null +++ b/files/vi/web/html/element/meta/index.html @@ -0,0 +1,441 @@ +--- +title: '<meta>: The Document-level Metadata element' +slug: Web/HTML/Element/meta +translation_of: Web/HTML/Element/meta +--- +<div>{{HTMLRef}}</div> + +<p>The <strong>HTML <code><meta></code> element</strong> represents {{Glossary("Metadata","metadata")}} that cannot be represented by other HTML meta-related elements, like {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} or {{HTMLElement("title")}}.</p> + +<table class="properties"> + <tbody> + <tr> + <th><a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a></th> + <td>Metadata content. If the {{htmlattrxref("itemprop", "meta")}} attribute is present: <a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">flow content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>.</td> + </tr> + <tr> + <th>Permitted content</th> + <td>None, it is an {{Glossary("empty element")}}.</td> + </tr> + <tr> + <th>Tag omission</th> + <td>As it is a void element, the start tag must be present and the end tag must not be present.</td> + </tr> + <tr> + <th>Permitted parents</th> + <td><code><meta charset></code>, <code><meta http-equiv></code>: a {{HTMLElement("head")}} element. If the {{htmlattrxref("http-equiv", "meta")}} is not an encoding declaration, it can also be inside a {{HTMLElement("noscript")}} element, itself inside a {{HTMLElement("head")}} element.</td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td>None</td> + </tr> + <tr> + <th>DOM interface</th> + <td>{{domxref("HTMLMetaElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Attributes">Attributes</h2> + +<p>This element includes the <a href="/en-US/docs/Web/HTML/Global_attributes">global attributes</a>.</p> + +<div class="note"> +<p><strong>Note:</strong> the global attribute {{htmlattrxref("name", "meta")}} has a specific meaning for the {{HTMLElement("meta")}} element, and the {{htmlattrxref("itemprop", "meta")}} attribute must not be set on the same <code><meta></code> element that has any existing {{htmlattrxref("name", "meta")}}, {{htmlattrxref("http-equiv", "meta")}} or {{htmlattrxref("charset", "meta")}} attributes.</p> +</div> + +<dl> + <dt>{{htmlattrdef("charset")}}</dt> + <dd>This attribute declares the page's character encoding. It must contain a <a class="external" href="https://www.iana.org/assignments/character-sets">standard IANA MIME name for character encodings</a>. Although the standard doesn't request a specific encoding, it suggests: + <ul> + <li>Authors are encouraged to use <a href="/en-US/docs/Glossary/UTF-8"><code>UTF-8</code></a>.</li> + <li>Authors should not use ASCII-incompatible encodings to avoid security risk: browsers not supporting them may interpret harmful content as HTML. This happens with the <code>JIS_C6226-1983</code>, <code>JIS_X0212-1990</code>, <code>HZ-GB-2312</code>, <code>JOHAB</code>, the ISO-2022 family and the EBCDIC family.</li> + </ul> + + <div class="note"> + <p><strong>Note: </strong>ASCII-incompatible encodings are those that don't map the 8-bit code points <code>0x20</code> to <code>0x7E</code> to the <code>0x0020</code> to <code>0x007E</code> Unicode code points)</p> + </div> + + <div class="warning"> + <ul> + <li>Authors <strong>must not</strong> use <code>CESU-8</code>, <code>UTF-7</code>, <code>BOCU-1</code> and/or <code>SCSU</code> as <a href="/en-US/docs/Glossary/Cross-site_scripting">cross-site scripting</a> attacks with these encodings have been demonstrated.</li> + <li>Authors should not use <code>UTF-32</code> because not all HTML5 encoding algorithms can distinguish it from <code>UTF-16</code>.</li> + </ul> + </div> + + <div class="note"><strong>Notes:</strong> + + <ul> + <li>The declared character encoding must match the one the page was saved with to avoid garbled characters and security holes.</li> + <li>The {{HTMLElement("meta")}} element declaring the encoding must be inside the {{HTMLElement("head")}} element and <strong>within the first 1024 bytes</strong> of the HTML as some browsers only look at those bytes before choosing an encoding.</li> + <li>This {{HTMLElement("meta")}} element is only one part of the <a href="https://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#encoding-sniffing-algorithm" title="Algorithm charset page">algorithm to determine a page's character set</a>. The <a href="/en-US/docs/Web/HTTP/Headers/Content-Type"><code>Content-Type</code> header</a> and any {{Glossary("Byte-Order Mark","Byte-Order Marks")}} override this element.</li> + <li>It is strongly recommended to define the character encoding. If a page's encoding is undefined, cross-scripting techniques are possible, such as the <a class="external" href="https://code.google.com/p/doctype-mirror/wiki/ArticleUtf7"><code>UTF-7</code> fallback cross-scripting technique</a>.</li> + <li>The {{HTMLElement("meta")}} element with a <code>charset</code> attribute is a synonym for the pre-HTML5 <code><meta http-equiv="Content-Type" content="text/html; charset=<em>IANAcharset</em>"></code>, where <em><code>IANAcharset</code></em> contains the value of the equivalent {{htmlattrxref("charset", "meta")}} attribute. This syntax is still allowed, although no longer recommended.</li> + </ul> + </div> + </dd> + <dt>{{htmlattrdef("content")}}</dt> + <dd>This attribute contains the value for the {{htmlattrxref("http-equiv", "meta")}} or {{htmlattrxref("name", "meta")}} attribute, depending on which is used.</dd> + <dt>{{htmlattrdef("http-equiv")}}</dt> + <dd>Defines a pragma directive. The attribute is named <code><strong>http-equiv</strong>(alent)</code> because all the allowed values are names of particular HTTP headers: + <ul> + <li><code>"content-language"</code> {{obsolete_inline}}<br> + Defines the default language of the page. It can be overridden by the <a href="/en-US/docs/Web/HTML/Global_attributes/lang">lang</a> attribute on any element. + <div class="warning"> + <p><strong>Warning: </strong>Do not use this value, as it is obsolete. Prefer the <code>lang</code> attribute on the {{HTMLElement("html")}} element.</p> + </div> + </li> + <li><code>"content-security-policy"</code><br> + Allows page authors to define a <a href="/en-US/docs/Web/Security/CSP/CSP_policy_directives">content policy</a> for the current page. Content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks.</li> + <li><code>"content-type"</code> {{obsolete_inline}}<br> + Defines the <a href="/en-US/docs/Glossary/MIME_type">MIME type</a> of the document, followed by its character encoding. It follows the same syntax as the HTTP <code>content-type</code> entity-header field, but as it is inside a HTML page, most values other than <code>text/html</code> are impossible. Therefore the valid syntax for its <code>content</code> is the string '<code>text/html</code>' followed by a character set with the following syntax: '<code>; charset=<em>IANAcharset</em></code>', where <code>IANAcharset</code> is the <em>preferred MIME name</em> for a character set as <a class="external" href="https://www.iana.org/assignments/character-sets">defined by the IANA.</a> + <div class="warning"> + <p><strong>Warning: </strong>Do not use this value, as it is obsolete. Use the {{htmlattrxref("charset", "meta")}} attribute on the {{HTMLElement("meta")}} element.</p> + </div> + + <div class="note"> + <p><strong>Note: </strong>As {{HTMLElement("meta")}} can't change documents' types in XHTML or HTML5's XHTML serialization, never set the MIME type to an XHTML MIME type with <code><meta></code>.</p> + </div> + </li> + <li><code>"refresh"</code><br> + This instruction specifies: + <ul> + <li>The number of seconds until the page should be reloaded - only if the {{htmlattrxref("content", "meta")}} attribute contains a positive integer.</li> + <li>The number of seconds until the page should redirect to another - only if the {{htmlattrxref("content", "meta")}} attribute contains a positive integer followed by the string '<code>;url=</code>', and a valid URL.</li> + </ul> + </li> + <li><code>"set-cookie"</code> {{obsolete_inline}}<br> + Defines a <a href="/en-US/docs/cookie">cookie</a> for the page. Its content must follow the syntax defined in the <a class="external" href="https://tools.ietf.org/html/draft-ietf-httpstate-cookie-14">IETF HTTP Cookie Specification</a>. + <div class="warning"> + <p><strong>Warning:</strong> Do not use this instruction, as it is obsolete. Use the HTTP header <a href="/en-US/docs/Web/HTTP/Headers/Set-Cookie"><code>Set-Cookie</code></a> instead.</p> + </div> + </li> + </ul> + </dd> + <dt>{{htmlattrdef("name")}}</dt> + <dd> + <p>This attribute defines the name of a piece of document-level metadata. It should not be set if one of the attributes {{htmlattrxref("itemprop", "meta")}}, {{htmlattrxref("http-equiv", "meta")}} or {{htmlattrxref("charset", "meta")}} is also set.</p> + + <p>This metadata name is associated with the value contained by the {{htmlattrxref("content", "meta")}} attribute. The possible values for the name attribute are:</p> + + <ul> + <li><code>application-name</code> which defines the name of the application running in the web page. + + <div class="note"><strong>Note:</strong> + + <ul> + <li>Browsers may use this to identify the application. It is different from the {{HTMLElement("title")}} element, which usually contain the application name, but may also contain information like the document name or a status.</li> + <li>Simple web pages shouldn't define an application-name.</li> + </ul> + </div> + </li> + <li><code>author</code> which defines the name of the document's author.</li> + <li><code>description</code> which contains a short and accurate summary of the content of the page. Several browsers, like Firefox and Opera, use this as the default description of bookmarked pages.</li> + <li><code>generator</code> which contains the identifier of the software that generated the page.</li> + <li><code>keywords</code> which contains words relevant to the page's content separated by commas.</li> + <li><code>referrer</code> which controls the <a href="/en-US/docs/Web/HTTP/Headers/Referer"><code>Referer</code> HTTP header</a> attached to requests sent from the document: + <table class="standard-table"> + <caption>Values for the <code>content</code> attribute of <code><meta name="referrer"></code></caption> + <tbody> + <tr> + <td><code>no-referrer</code></td> + <td>Do not send a HTTP <code>Referrer</code> header.</td> + </tr> + <tr> + <td><code>origin</code></td> + <td>Send the <a href="/en-US/docs/Glossary/Origin">origin</a> of the document.</td> + </tr> + <tr> + <td><code>no-referrer-when-downgrade</code></td> + <td>Send the <a href="/en-US/docs/Glossary/Origin">origin</a> as a referrer to URLs as secure as the current page, (https→https), but does not send a referrer to less secure URLs (https→http). This is the default behaviour.</td> + </tr> + <tr> + <td><code>origin-when-cross-origin</code></td> + <td>Send the full URL (stripped of parameters) for same-origin requests, but only send the <a href="/en-US/docs/Glossary/Origin">origin</a> for other cases.</td> + </tr> + <tr> + <td><code>same-origin</code></td> + <td>A referrer will be sent for <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">same-site origins</a>, but cross-origin requests will contain no referrer information.</td> + </tr> + <tr> + <td><code>strict-origin</code></td> + <td>Only send the origin of the document as the referrer to a-priori as-much-secure destination (HTTPS->HTTPS), but don't send it to a less secure destination (HTTPS->HTTP).</td> + </tr> + <tr> + <td><code>strict-origin-when-cross-origin</code></td> + <td>Send a full URL when performing a same-origin request, only send the origin of the document to a-priori as-much-secure destination (HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP).</td> + </tr> + <tr> + <td><code>unsafe-URL</code></td> + <td>Send the full URL (stripped of parameters) for same-origin or cross-origin requests.</td> + </tr> + </tbody> + </table> + + <div class="note"> + <p><strong>Notes:</strong></p> + + <ul> + <li>Some browsers support the deprecated values of <code>always</code>, <code>default</code>, and <code>never</code> for referrer.</li> + <li>Dynamically inserting <code><meta name="referrer"></code> (with <a href="/en-US/docs/Web/API/Document/write"><code>document.write</code></a> or <a href="/en-US/docs/Web/API/Node/appendChild"><code>appendChild</code></a>) makes the referrer behaviour unpredictable.</li> + <li>When several conflicting policies are defined, the no-referrer policy is applied.</li> + </ul> + </div> + </li> + </ul> + + <p>This attribute may also have a value taken from the extended list defined on <a class="external" href="https://wiki.whatwg.org/wiki/MetaExtensions">WHATWG Wiki MetaExtensions page</a>. Although none have been formally accepted yet, a few commonly used names are:</p> + + <ul> + <li><code>creator</code> which defines the name of the creator of the document, such as an organization or institution. If there are more than one, several {{HTMLElement("meta")}} elements should be used.</li> + <li><code>googlebot</code>, a synonym of <code>robots</code>, is only followed by Googlebot (the indexing crawler for Google).</li> + <li><code>publisher</code> which defines the name of the document's publisher.</li> + <li><code>robots</code> which defines the behaviour that cooperative crawlers, or "robots", should use with the page. It is a comma-separated list of the values below: + <table class="standard-table"> + <caption>Values for the content of <code><meta name="robots"></code></caption> + <thead> + <tr> + <th scope="col">Value</th> + <th scope="col">Description</th> + <th scope="col">Used by</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>index</code></td> + <td>Allows the robot to index the page (default).</td> + <td>All</td> + </tr> + <tr> + <td><code>noindex</code></td> + <td>Requests the robot to not index the page.</td> + <td>All</td> + </tr> + <tr> + <td><code>follow</code></td> + <td>Allows the robot to follow the links on the page (default).</td> + <td>All</td> + </tr> + <tr> + <td><code>nofollow</code></td> + <td>Requests the robot to not follow the links on the page.</td> + <td>All</td> + </tr> + <tr> + <td><code>none</code></td> + <td>Equivalent to <code>noindex, nofollow</code></td> + <td><a class="external" href="https://support.google.com/webmasters/answer/79812">Google</a></td> + </tr> + <tr> + <td><code>noodp</code></td> + <td>Prevents using the <a class="external" href="https://www.dmoz.org/">Open Directory Project</a> description, if any, as the page description in search engine results.</td> + <td> + <p><a class="external" href="https://support.google.com/webmasters/answer/35624#nodmoz">Google</a>, <a class="external" href="https://help.yahoo.com/kb/search-for-desktop/meta-tags-robotstxt-yahoo-search-sln2213.html#cont5">Yahoo</a>, <a class="external" href="https://www.bing.com/webmaster/help/which-robots-metatags-does-bing-support-5198d240">Bing</a></p> + </td> + </tr> + <tr> + <td><code>noarchive</code></td> + <td>Requests the search engine not to cache the page content.</td> + <td><a class="external" href="https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag#valid-indexing--serving-directives">Google</a>, <a class="external" href="https://help.yahoo.com/kb/search-for-desktop/SLN2213.html">Yahoo</a>, <a class="external" href="https://www.bing.com/webmaster/help/which-robots-metatags-does-bing-support-5198d240">Bing</a></td> + </tr> + <tr> + <td><code>nosnippet</code></td> + <td>Prevents displaying any description of the page in search engine results.</td> + <td><a class="external" href="https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag#valid-indexing--serving-directives">Google</a>, <a class="external" href="https://www.bing.com/webmaster/help/which-robots-metatags-does-bing-support-5198d240">Bing</a></td> + </tr> + <tr> + <td><code>noimageindex</code></td> + <td>Requests this page not to appear as the referring page of an indexed image.</td> + <td><a class="external" href="https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag#valid-indexing--serving-directives">Google</a></td> + </tr> + <tr> + <td><code>nocache</code></td> + <td>Synonym of <code>noarchive</code>.</td> + <td><a class="external" href="https://www.bing.com/webmaster/help/which-robots-metatags-does-bing-support-5198d240">Bing</a></td> + </tr> + </tbody> + </table> + + <div class="note"><strong>Notes:</strong> + + <ul> + <li>Only cooperative robots follow these rules. Do not expect to prevent e-mail harvesters with them.</li> + <li>The robot still needs to access the page in order to read these rules. To prevent bandwidth consumption, use a <em><a href="/en-US/docs/Robot_Exclusion_Protocol" title="Robot Exclusion Protocol">robots.txt</a></em> file.</li> + <li>If you want to remove a page, <code>noindex</code> will work, but only after the robot visits the page again. Ensure that the <code>robots.txt</code> file is not preventing revisits.</li> + <li>Some values are mutually exclusive, like <code>index</code> and <code>noindex</code>, or <code>follow</code> and <code>nofollow</code>. In these cases the robot's behaviour is undefined and may vary between them.</li> + <li>Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header <code>X-Robots-Tag</code>; this allows non-HTML documents like images to use these rules.</li> + </ul> + </div> + </li> + <li><code>slurp</code>, is a synonym of <code>robots</code>, but only for Slurp - the crawler for Yahoo Search.</li> + <li><code>viewport</code>, which gives hints about the size of the initial size of the {{glossary("viewport")}}. Used by mobile devices only. + <table class="fullwidth-table"> + <caption>Values for the content of <code><meta name="viewport"></code></caption> + <thead> + <tr> + <th scope="col">Value</th> + <th scope="col">Possible subvalues</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>width</code></td> + <td>A positive integer number, or the text <code>device-width</code></td> + <td>Defines the pixel width of the viewport that you want the web site to be rendered at.</td> + </tr> + <tr> + <td><code>height</code></td> + <td>A positive integer, or the text <code>device-height</code></td> + <td>Defines the height of the viewport. Not used by any browser.</td> + </tr> + <tr> + <td><code>initial-scale</code></td> + <td>A positive number between <code>0.0</code> and <code>10.0</code></td> + <td>Defines the ratio between the device width (<code>device-width</code> in portrait mode or <code>device-height</code> in landscape mode) and the viewport size.</td> + </tr> + <tr> + <td><code>maximum-scale</code></td> + <td>A positive number between <code>0.0</code> and <code>10.0</code></td> + <td>Defines the maximum amount to zoom in. It must be greater or equal to the <code>minimum-scale</code> or the behaviour is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default.</td> + </tr> + <tr> + <td><code>minimum-scale</code></td> + <td>A positive number between <code>0.0</code> and <code>10.0</code></td> + <td>Defines the minimum zoom level. It must be smaller or equal to the <code>maximum-scale</code> or the behaviour is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default.</td> + </tr> + <tr> + <td><code>user-scalable</code></td> + <td><code>yes</code> or <code>no</code></td> + <td>If set to <code>no</code>, the user is not able to zoom in the webpage. The default is <code>yes</code>. Browser settings can ignore this rule, and iOS10+ ignores it by default.</td> + </tr> + </tbody> + </table> + + <table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Device', '#viewport-meta', '<meta name="viewport">')}}</td> + <td>{{Spec2('CSS3 Device')}}</td> + <td>Non-normatively describes the Viewport META element</td> + </tr> + </tbody> + </table> + + <div>See also: {{cssxref("@viewport")}}</div> + + <div class="note"><strong>Notes:</strong> + + <ul> + <li>Though unstandardized, this declaration is respected by most mobile browsers due to de-facto dominance.</li> + <li>The default values may vary between devices and browsers.</li> + <li>To learn about this declaration in Firefox for Mobile, see <a href="/en-US/docs/Mobile/Viewport_meta_tag" title="Mobile/Viewport meta tag">this article</a>.</li> + </ul> + </div> + </li> + </ul> + </dd> + <dt>{{htmlattrdef("scheme")}} {{obsolete_inline}}</dt> + <dd>This attribute defines the scheme in which metadata is described. A scheme is a context leading to the correct interpretations of the {{htmlattrxref("content", "meta")}} value, like a format. + <div class="warning"> + <p><strong>Warning:</strong> Do not use this value, as it is obsolete. There is no replacement as there was no real usage for it.</p> + </div> + </dd> +</dl> + +<h2 id="Notes">Notes</h2> + +<p>Depending on the attributes set, the kind of metadata can be one of the following:</p> + +<ul> + <li>If {{htmlattrxref("name", "meta")}} is set, it is <em>document-level</em> <em>metadata</em>, applying to the whole page.</li> + <li>If {{htmlattrxref("http-equiv", "meta")}} is set, it is a <em>pragma directive</em> — information normally given by the web server about how the web page is served.</li> + <li>If {{htmlattrxref("charset", "meta")}} is set, it is a <em>charset declaration</em> — the character encoding used by the webpage.</li> + <li>If {{htmlattrxref("itemprop", "meta")}} is set, it is <em>user-defined metadata</em> — transparent for the user-agent as the semantics of the metadata is user-specific. {{experimental_inline}}</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: html"><meta charset="utf-8"> + +<!-- Redirect page after 3 seconds --> +<meta http-equiv="refresh" content="3;url=https://www.mozilla.org"> +</pre> + +<h2 id="Accessibility_concerns">Accessibility concerns</h2> + +<h3 id="Refreshing_content">Refreshing content</h3> + +<p>Pages set with a <code>refresh</code> value run the risk of having the time interval being too short. People navigating with the aid of assistive technology such as a screen reader may be unable to read through and understand the page's content before being automatically redirected. The abrupt, unannounced updating of the page content may also be disorienting for people experiencing low vision conditions. </p> + +<ul> + <li><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#Guideline_2.2_—_Enough_Time_Provide_users_enough_time_to_read_and_use_content">MDN Understanding WCAG, Guideline 2.1 explanations</a></li> + <li><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#Guideline_3.2_—_Predictable_Make_Web_pages_appear_and_operate_in_predictable_ways">MDN Understanding WCAG, Guideline 3.1 explanations</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-required-behaviors.html">Understanding Success Criterion 2.2.1 | W3C Understanding WCAG 2.0</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-postponed.html">Understanding Success Criterion 2.2.4 | W3C Understanding WCAG 2.0</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/consistent-behavior-no-extreme-changes-context.html">Understanding Success Criterion 3.2.5 | W3C Understanding WCAG 2.0</a></li> +</ul> + +<h3 id="Viewport_scaling">Viewport scaling</h3> + +<p>Disabling zooming capabilities by setting <code>user-scalable</code> to a value of <code>no</code> prevents people experiencing low vision conditions from being able to read and understand page content.</p> + +<ul> + <li><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#Guideline_1.4_Make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background">MDN Understanding WCAG, Guideline 1.4 explanations</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-scale.html">Understanding Success Criterion 1.4.4 | W3C Understanding WCAG 2.0</a></li> +</ul> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Referrer Policy', '#referrer-policy-delivery-meta', '<meta name="referrer">')}}</td> + <td>{{Spec2('Referrer Policy')}}</td> + <td>Defines values and semantics of <code><meta name="referrer"></code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'semantics.html#the-meta-element', '<meta>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Added <code>itemprop</code> attribute</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'document-metadata.html#the-meta-element', '<meta>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Added <code>charset</code> attribute</td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'struct/global.html#h-7.4.4.2', '<meta>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>The information shown below has been pulled from MDN's Github (<a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>).</p> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("html.elements.meta")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The other elements containing metadata: {{HTMLElement("base")}}, {{HTMLElement("head")}}, {{HTMLElement("link")}}, {{HTMLElement("style")}},{{HTMLElement("title")}}.</li> +</ul> diff --git a/files/vi/web/html/element/span/index.html b/files/vi/web/html/element/span/index.html new file mode 100644 index 0000000000..4f45bf613b --- /dev/null +++ b/files/vi/web/html/element/span/index.html @@ -0,0 +1,122 @@ +--- +title: <span> +slug: Web/HTML/Element/span +translation_of: Web/HTML/Element/span +--- +<div>{{HTMLRef}}</div> + +<p><span class="seoSummary">Phần tử <span> HTML là một bộ chứa nội tuyến chung cho nội dung cụm từ, vốn không đại diện cho bất cứ điều gì. Nó có thể được sử dụng để nhóm các thành phần cho mục đích tạo kiểu (sử dụng các thuộc tính {{htmlattrxref ("class")}} hoặc {{htmlattrxref ("id")}}) hoặc vì chúng chia sẻ các giá trị thuộc tính, như {{htmlattrxref ( "lang")}}. Nó chỉ được sử dụng khi không có yếu tố ngữ nghĩa nào khác phù hợp. <span> rất giống với phần tử {{HTMLE bổ sung ("div")}}, nhưng {{HTMLEuity ("div")}} là phần tử cấp khối trong khi <span> là phần tử nội tuyến.</span></p> + +<div>{{EmbedInteractiveExample("pages/tabbed/span.html", "tabbed-shorter")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a></th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">Flow content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>.</td> + </tr> + <tr> + <th scope="row">Permitted content</th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">Phrasing content</a>.</td> + </tr> + <tr> + <th scope="row">Tag omission</th> + <td>{{no_tag_omission}}</td> + </tr> + <tr> + <th scope="row">Permitted parents</th> + <td>Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>, or any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">flow content</a>.</td> + </tr> + <tr> + <th scope="row">Implicit ARIA role</th> + <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role">No corresponding role</a></td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td>Any</td> + </tr> + <tr> + <th scope="row">DOM interface</th> + <td>{{domxref("HTMLSpanElement")}} (before {{glossary("HTML5")}}, the interface was {{domxref("HTMLElement")}})</td> + </tr> + </tbody> +</table> + +<h2 id="Attributes">Attributes</h2> + +<p>This element only includes the <a href="/en-US/docs/Web/HTML/Global_attributes">global attributes</a>.</p> + +<h2 id="Example">Example</h2> + +<h3 id="Example_1">Example 1</h3> + +<h4 id="HTML">HTML</h4> + +<pre class="brush:html gutter:false notranslate"><p><span>Some text</span></p></pre> + +<h4 id="Result">Result</h4> + +<p>{{EmbedLiveSample('Example_1')}}</p> + +<h3 id="Example_2">Example 2</h3> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush:html gutter:false notranslate"><li><span> + <a href="portfolio.html" target="_blank">See my portfolio</a> +</span></li> +</pre> + +<h4 id="CSS">CSS</h4> + +<pre class="brush: css notranslate">li span { + background: gold; + } +</pre> + +<h4 id="Result_2">Result</h4> + +<p>{{EmbedLiveSample('Example_2')}}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'text-level-semantics.html#the-span-element', '<span>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'textlevel-semantics.html#the-span-element', '<span>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>The {{glossary("DOM")}} interface is now {{domxref("HTMLSpanElement")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'struct/global.html#edef-SPAN', '<span>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("html.elements.span")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>HTML {{HTMLElement("div")}} element</li> +</ul> diff --git a/files/vi/web/html/index.html b/files/vi/web/html/index.html new file mode 100644 index 0000000000..8dd468916b --- /dev/null +++ b/files/vi/web/html/index.html @@ -0,0 +1,77 @@ +--- +title: HTML +slug: Web/HTML +tags: + - HTML +translation_of: Web/HTML +--- +<div class="callout-box"> +<div style="font: normal 20px 'Bebas Neue','League Gothic',Haettenschweiler,Impact,'Arial Narrow',sans-serif; text-transform: uppercase;">HTML5 Demos</div> + +<p><a href="/en-US/demos/tag/tech:html5" title="https://developer.mozilla.org/en-US/demos/tag/tech:css3/">Bộ sưu tập demo</a> cho thấy những công nghệ HTML mới nhất trong thực tiễn.</p> + +<p><a href="/en-US/docs/HTML/HTML5" title="html5"><img alt="HTML5_Logo" class="default internal" src="/@api/deki/files/6020/=HTML5_Logo_128.png"></a></p> +</div> + +<p><strong>Ngôn ngữ đánh dấu siêu văn bản (HyperText Markup Language - HTML)</strong> được sử dụng trong việc tạo trang web và các loại tài liệu khác có thể xem được bằng trình duyệt. HTML là một tiêu chuẩn quốc tế, được duy trì bởi <a class="external" href="http://www.w3.org/">World Wide Web Consortium</a> - Liên hợp Web toàn cầu. Trên phương diện kỹ thuật, <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/" title="http://www.whatwg.org/specs/web-apps/current-work/">HTML5</a> vẫn đang trong quá trình phát triển. Tuy nhiên nó được xem là "tiêu chuẩn sống" và là phiên bản nâng cấp được cập nhật của HTML.</p> + +<table class="topicpage-table"> + <tbody> + <tr> + <td style="width: 60%; padding-right: 75px;"> + <h2 class="Documentation" id="Documentation" name="Documentation"> Tài liệu HTML</h2> + + <dl> + <dt><strong><a href="/en-US/docs/HTML/Introduction" title="Introduction to HTML">Giới thiệu về HTML</a></strong></dt> + <dd>Phần này đề cập đến các thông tin cơ bản về cú pháp và ngữ nghĩa của một trang (tài liệu) HTML. Đây là những thông tin cơ bản và cần thiết trong việc phát triển những tài liệu HTML</dd> + <dt><a class="internal" href="/en-US/docs/HTML/Element" title="en-US/docs/HTML/Element">Tham khảo về yếu tố của HTML</a></dt> + <dd>Đi vào chi tiết về từng phần tử được hỗ trợ bởi các trình duyệt khác nhau.</dd> + <dt><a class="internal" href="/en-US/docs/HTML/Attributes" title="en-US/docs/HTML/Attributes">Danh sách thuộc tính HTML</a></dt> + <dd>Tìm hiểu tất cả các thuộc tính và những phần tử liên quan.</dd> + <dt><a href="/en-US/docs/HTML/HTML5" title="en-US/docs/HTML/HTML5">HTML5</a></dt> + <dd>Khám phá về API mới trong HTML5 và các phần tử được hỗ trợ.</dd> + <dt><a href="/en-US/docs/Web_development/Historical_artifacts_to_avoid" title="en-US/docs/HTML/Bad_copy_pasting_habits">Thói quen xấu: copy-paste</a></dt> + <dd>Công nghệ web thường được học bằng cách xem nguồn từ những trang khác rồi copy-paste. Thói quen xấu này vẫn đang tiếp tục tồn tại.</dd> + <dt> <a href="/en-US/docs/HTML/Canvas/Drawing_Graphics_with_Canvas" title="en-US/docs/Drawing_Graphics_with_Canvas"> Vẽ đồ hoạ với Canvas</a></dt> + <dd>Một phần tử HTML mới : <code><canvas></code> có thể được dùng để tạo ra biểu đồ, các phần tử UI, và những yếu tố đồ hoạ tuỳ chỉnh khác từ phía máy khách - client.</dd> + <dt><a href="/en-US/docs/HTML/Tips_for_authoring_fast-loading_HTML_pages" title="en-US/docs/HTML/Tips for authoring fast-loading HTML pages">Các mẹo tạo trang HTML với tốc độ tải nhanh</a></dt> + <dd>Web được tối ưu không đơn thuần chỉ là trang web có tương tác cao với khách truy cập, mà còn được kỳ vọng là có khả năng giảm tải lên máy chủ và kết nối internet.</dd> + </dl> + + <p><span class="alllinks"><a href="/en-US/docs/tag/HTML" title="Article tagged: HTML">Xem tất cả...</a></span></p> + </td> + <td style="width: 40%; vertical-align: top;"> + <h2 class="Community" id="Community" name="Community">Nhận trợ giúp từ cộng đồng</h2> + + <p>Bạn cần trợ giúp về một vấn đề liên quan đến HTML mà không thể tìm thấy giải pháp trong phần tài liệu?</p> + + <ul> + <li>Tham gia thảo luận tại diễn đàn dành riêng cho Mozilla : {{ DiscussionList("dev-tech-html", "mozilla.dev.tech.html") }}</li> + <li>Đặt câu hỏi với <a class="external" href="http://groups.yahoo.com/group/canvas-developers/">Nhóm Yahoo những nhà phát triển Canvas</a></li> + </ul> + + <p><span class="alllinks"><a class="external" href="http://www.catb.org/~esr/faqs/smart-questions.html" title="http://www.catb.org/~esr/faqs/smart-questions.html">Đừng quên giao tiếp một cách <em>netiquette</em>...</a></span></p> + + <h2 class="Tools" id="Tools" name="Tools">Công cụ hỗ trợ phát triển HTML</h2> + + <ul> + <li><a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/1843">Tiện ích mở rộng Firebug </a>của Firefox<span class="external">, rất phổ biến để chỉnh sửa CSS trên các trang web đã xem. Hữu dụng để kiểm tra thay những thay đổi</span>.</li> + <li><a class="external" href="http://validator.w3.org/">Trình xác thực HTML </a></li> + <li><a class="link-https" href="https://addons.mozilla.org/extensions/moreinfo.php?id=60&application=firefox">Tiện ích mở rộng dành cho nhà phát triển Web</a></li> + <li><a class="external" href="http://tidy.sourceforge.net/">HTML gọn gàng</a></li> + <li><a class="external" href="http://prettydiff.com/?html">Sự khác biệt</a></li> + </ul> + + <p><span class="alllinks"><a href="/Special:Tags?tag=HTML:Tools&language=en" title="Special:Tags?tag=HTML:Tools&language=en">Xem tất cả...</a></span></p> + + <h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Chủ đề liên quan</h2> + + <ul> + <li><a href="/en-US/docs/CSS" title="en-US/docs/CSS">Cascading Style Sheets (CSS)</a> dùng để tạo kiểu cho HTML.</li> + <li><a href="/en-US/docs/Document_Object_Model_(DOM)" title="Document Object Model (DOM)">Document Object Model (DOM)</a> là đại biểu cho một tài liệu HTML dạng cây.</li> + <li><a href="/en-US/docs/XHTML" title="XHTML">XHTML</a> là <a href="/en-US/docs/XML" title="XML">XML</a> phiên bản ngôn ngữ.</li> + </ul> + </td> + </tr> + </tbody> +</table> diff --git a/files/vi/web/html_vi/index.html b/files/vi/web/html_vi/index.html new file mode 100644 index 0000000000..0b57e8194c --- /dev/null +++ b/files/vi/web/html_vi/index.html @@ -0,0 +1,102 @@ +--- +title: HTML +slug: Web/HTML_vi +translation_of: Web/HTML +--- +<div>{{HTMLSidebar}}</div> + +<p class="summary"><span class="seoSummary"><strong>HTML</strong> (Viết tắt của cụm từ: HyperText Markup Language - Ngôn ngữ đánh dấu siêu văn bản) được xem như là khung xương của một trang web. Mọi việc "mô tả", "định nghĩa" bố cục, <em>nội dung</em> trang web đều do HTML thực hiện. Bên cạnh đó là sự xuất hiện của việc trang trí/trình bày do <a href="/en-US/docs/Web/CSS">CSS</a> đảm nhiệm và các chức năng/hành động của <a href="/en-US/docs/Web/JavaScript">JavaScript</a>.</span></p> + +<p>"HyperText" (Siêu văn bản) biểu diễn sự liên kết các trang web với nhau, trên một trang web sẽ có thể sẽ chứa nhiều trang khác nhau và mỗi trang như thế lại được quy ra là một tệp HTML. Liên kết là một khái niệm cơ bản của Web.</p> + +<p>Bằng cách tải nội dung lên mạng, liên kết nó với các trang do người khác tạo ra, và bạn đã trở thành một thành viên "tích cực" của World Wide Web. Tada!!!</p> + +<p>HTML sử dụng "markup" (chú thích) để chú thích văn bản, hình ảnh và những nội dung khác để hiển thị trên trình duyệt web. HTML markup chứa các "elements" (phần tử) đặc biệt như {{HTMLElement("head")}}, {{HTMLElement("title")}}, {{HTMLElement("body")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("p")}}, {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("img")}}, và (n + 1) thứ khác nữa.</p> + +<p>Tags (các thẻ) trong HTML chả phân biệt chữ hoa hay thường đâu. Bạn thích viết kiểu gì cũng được. Ví dụ nhé: thẻ <strong><title> </strong>có thể viết thành <Title>,<TiTlE> hay <tItLe> và rất rất nhiều cách khác. Đương nhiên là đủ và đúng chữ cái, chứ không phải t33nc0d3 đâu nha.</p> + +<p>Những bài viết dưới đây sẽ giúp đạo hữu hiểu rõ hơn về HTML.</p> + +<section class="cleared" id="sect1"> +<ul class="card-grid"> + <li><span>Khai thông HTML</span> + + <p>Nếu đạo hữu là người mới vào ngành lập trình web, hãy chắc rằng đã đọc qua bài <a href="/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics">HTML Khai Quyển</a> để hiểu HTML là gì và dùng như nào.</p> + </li> + <li><span>HTML Hướng dẫn</span> + <p>Những bài viết về cách sử dụng HTML, có hướng dẫn và đầy đủ ví dụ, mời đạo hữu xem qua <a href="/en-US/docs/Learn/HTML">HTML Học Vực</a>.</p> + </li> + <li><span>HTML Kỳ thư</span> + <p>Trong phần <a href="/en-US/docs/Web/HTML/Reference">Tham khảo HTML mở rộng</a>, đạo hữu sẽ trên thông thiên văn, dưới tường địa lý, hiểu rõ tất tần tật về phần tử và thuộc tính trong HTML.</p> + </li> +</ul> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Tools" id="Nhập_môn_quyển">Nhập môn quyển</h2> + +<p><a href="/en-US/docs/Learn/HTML">HTML Học Vực</a> của bần đạo có những mô-đun HTML chạy ngay từ đầu — đạo hữu không cần kiến thức trước đó vẫn sẽ được khai thông.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Khai quyển HTML</a></dt> + <dd>Khai quyển sẽ thiết lập những kiến thức nền tảng cho đạo hữu, giúp đạo hữu hiểu các khái niệm và sử dụng các cú pháp quan trọng. Như việc cho HTML vào văn bản, làm sao để tạo liên kết, cách sử dụng HTML để xây dựng một trang web.</dd> + <dt><a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding">Nhúng và Đa phương tiện</a></dt> + <dd>Phần này sẽ khai mở kiến thức sử dụng HTML để nhét đa phương tiện vào website của đạo hữu, kể cả 1 vạn phương pháp nhét ảnh vào website, và làm sao để nhúng video, âm thanh và kể cả website của người khác.</dd> + <dt><a href="/en-US/docs/Learn/HTML/Tables">Bảng trong HTML</a></dt> + <dd>Việc trình bày bảng trên một website theo một cách dễ hiểu và dễ tiếp cận có thể là thiên kiếp đối với nhiều người tu hành HTML Kỳ kinh. Phần này có phương pháp từ cơ bản đến phức tạp hơn, chẳng hạn như phụ đề và tóm tắt.</dd> + <dt><a href="/en-US/docs/Learn/HTML/Forms">Biểu mẫu HTML</a></dt> + <dd>Biểu mẫu là thần hồn của website — nó cung cấp cho đạo hữu một thiên hà chức năng mà đạo hữu cần để tương tác với trang web. Ví dụ như Ký danh - Đăng nhập, gửi phản hồi, báo quan, mua bán dao dịch sản phẩm, và nhiều hơn thế nữa. Phần này sẽ chỉ dẫn đạo hữu tạo ra biểu mẫu từ client-side (tạm dịch: phía máy khách) / front-end (tạm dịch: phần giao diện).</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto">Dùng HTML để giải quyết vấn đề thường gặp</a></dt> + <dd>Cung cấp liên kết tới các nội dung để giải thích làm sao để sử dụng HTML để giải quyết vấn đề thường mắc phải khi tạo lập một trang web: liên quan tới các tiêu đề, chèn hình ảnh hoặc video, nhấn mạnh nội dung, tạo lập biểu mẫu cơ bản, vân vân.</dd> +</dl> + +<h2 id="Cao_cấp_chủ_đề">Cao cấp chủ đề</h2> + +<dl> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/CORS_enabled_image">CORS để kích hoạt hình ảnh</a></dt> + <dd class="landingPageList">Thuộc tính <code><a href="/en-US/docs/Web/HTML/Element/img#attr-crossorigin">crossorigin</a></code>, kết hợp với <a class="glossaryLink" href="/en-US/docs/Glossary/CORS">một CORS</a>, cho phép hình ảnh được định nghĩa vởi phần tử {{HTMLElement("img")}} để có thể nạp từ bên ngoài và sử dụng bên trong phần tử {{HTMLElement("canvas")}} như thể nó đang được nạp từ nơi này.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/CORS_settings_attributes">Cài đặt thuộc tính CORS</a></dt> + <dd class="landingPageList">Một số phần tử HTML cung cấp sự hỗ trợ cho <a href="/en-US/docs/HTTP/Access_control_CORS">CORS</a>, ví dụ như {{HTMLElement("img")}} hay {{HTMLElement("video")}}, có một thuộc tính <code>crossorigin</code> (đặc tính <code>crossOrigin</code>),<span id="result_box" lang="vi"><span> cho phép định hình các yêu cầu CORS cho dữ liệu đã nạp của phần tử</span></span> .</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Focus_management_in_HTML">Quản lý tập trung trong HTML</a></dt> + <dd class="landingPageList">Thuộc tính <code><a href="/en-US/docs/Web/API/Document/activeElement">activeElement</a></code> DOM và phương thức <code><a href="/en-US/docs/Web/API/Document/hasFocus">hasFocus()</a></code> DOM giúp bạn<span id="result_box" lang="vi"><span> theo dõi và kiểm soát sự tương tác của người dùng với các phần tử trên một trang web.</span></span></dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Using_the_application_cache">Sử dụng bộ nhớ đệm (cache) của ứng dụng</a></dt> + <dd class="landingPageList">Ứng dụng bộ nhớ đệm cho phép các ứng dụng dựa trên nền tảng web chạy offline. Bạn có thể sử dụng giao diện <strong>Application Cache</strong> (<em>AppCache</em>) <span id="result_box" lang="vi"><span>để cung cấp các tài nguyên mà trình duyệt lưu trữ và cung cấp cho người dùng ngoại tuyến</span></span>. <span id="result_box" lang="vi"><span>Các ứng dụng được lưu trữ trong bộ nhớ cache và hoạt động chính xác ngay cả khi người dùng Refresh lại khi đang ngoại tuyến.</span></span></dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content">Tải trước nội dung cùng với rel="preload"</a></dt> + <dd class="landingPageList">Giá trị <code>preload</code> trong thuộc tính {{htmlattrxref("rel", "link")}} của phần ử {{htmlelement("link")}} cho phép bạn viết yêu cầu tìm kiếm khai báo trong thẻ HTML {{htmlelement("head")}} của bạn, xác định các nguồn tài nguyên mà trang bạn sẽ cần tới trước khi tải trang, thứ bạn muốn tải trước trong cái vòng tròn tải trang, trước cả khi trình duyệt chính thức hoàn lại nội dung vào đó. <span id="result_box" lang="vi"><span>Điều này đảm bảo rằng chúng được tạo sẵn, sớm hơn và ít có khả năng chặn render đầu tiên của trang, làm cải thiện hiệu suất</span></span>. Tóm lại bài này sẽ cho bạn hiểu cơ bản làm cách nào mà cái <code>preload</code> làm việc.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Documentation" id="Đại_kỳ_thư">Đại kỳ thư</h2> + +<dl> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Reference">HTML kỳ kinh</a></dt> + <dd class="landingPageList">Tất tần tật cá <strong>phần tử </strong>HTML, mỗi thứ có thể được sửa đổi bởi một số<strong> thuộc tính.</strong> Tài liệu HTML đã được kết nối với nhau bằng <a href="/en-US/docs/Web/HTML/Link_types">cái liên kết này</a>.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Element">Phần tử HTML kỳ kinh</a></dt> + <dd class="landingPageList">Bách khoa toàn thư về <a class="glossaryLink" href="/en-US/docs/Glossary/HTML">Phần tử HTML</a>.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Attributes">Thuộc tính HTML kỳ kinh</a></dt> + <dd class="landingPageList">Phần tử trong HTML có <strong>thuộc tính</strong>. Đó là việc bổ xung giá trị để định hình các phần tử hay điều chỉnh hành động của chúng nhiều cách khác nhau.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Global_attributes">Thuộc tính toàn cầu</a></dt> + <dd class="landingPageList">Thuộc tính toàn cầu có thể áp đặt lên toàn bộ <a href="/en-US/docs/Web/HTML/Element">phần tử HTML</a>, <em>kể cả khi nó chả có trong tiêu chuẩn</em>. Có nghĩa là bất cứ pần tử không theo tiêu chuẩn nào vẫn phải bị áp đặt bởi mấy cái thuộc tính này, kể cả việc này không phù hợp với tài liệu HTML-5.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Inline_elements">Phần tử hướng nội</a> and <a href="/en-US/docs/Web/HTML/Block-level_elements">Phần tử phân khối</a></dt> + <dd class="landingPageList">Phần tử HTML luôn luôn "inline" (hướng nội) hoặc "block-level" (phân khối). Phần tử inline chỉ chiếm không gian giới hạn bởi các thẻ định nghĩa nó. Phần tử block-level chiếm cả vùng không gian của phần tử cha mẹ (container - vùng chứa), và rồi tạo thành một "khối".</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Link_types">Phân loại liên kết</a></dt> + <dd class="landingPageList">Trong HTML, các liên kết khác nhau có thể dùng để thiết lập mối quan hệ giữa hai tài liệu. Phần tử liên kết có thể được phân ra các loại <a href="/en-US/docs/Web/HTML/Element/a"><code><a></code></a>, <a href="/en-US/docs/Web/HTML/Element/area"><code><area></code></a>, và <a href="/en-US/docs/Web/HTML/Element/link"><code><link></code></a>.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Supported_media_formats">Định dạng đa phương tiện được hỗ trợ bởi phần tử audio và video</a></dt> + <dd class="landingPageList">Phần tử <a href="/en-US/docs/Web/HTML/Element/audio"><code><audio></code></a> và <a href="/en-US/docs/Web/HTML/Element/video"><code><video></code></a> cho phép ta phát âm thanh và video. Mấy cái phần tử này cung cấp một trình phát của chính trình duyệt thay cho việc sử dụng Flash Player hay một vài phần mở rộng khác.</dd> + <dt class="landingPageList"></dt> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Kinds_of_HTML_content">Các thể loại nội dung HTML</a></dt> + <dd class="landingPageList">HTML bao gồm nhiều loại nội dung, mỗi trong số đó cho phép sử dụng trong một ngữ cảnh nhất định và không được phép ở chỗ khác. Tương tự, mỗi ths có một mục nội dung khác mà chúng có thể chứa và các phàn tử có thể hoặc không thể sử dụng ở bên trong chúng. Đây là hướng dẫn cho các loại này.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode">Chế độ không minh bạch và chế độ tiêu chuẩn</a></dt> + <dd class="landingPageList">Biên niên sử về chế độ quirks (không minh bạch) và chế độ standards (tiêu chuẩn).</dd> +</dl> + +<h2 class="landingPageList" id="Chủ_đề_liên_quan">Chủ đề liên quan</h2> + +<dl> + <dt><a href="/en-US/docs/Web/HTML/Applying_color">Áp dụng màu sắc vào HTML sử dụng CSS</a></dt> + <dd>Bài này sẽ bao gồm nhiều cách sử dụng CSS để thêm màu vào nội dung HTML, liệt kê các phàn của tệp HTML có thể đổ màu và dùng thuộc tính CSS gì khi làm như vậy. Bao cả ví dụ, liên kết tới công cụ xây dựng bảng màu và nhiều hơn thế nữa.</dd> +</dl> +</div> +</div> +<span class="alllinks"><a href="/en-US/docs/tag/HTML">Xem tất...</a></span></section> diff --git a/files/vi/web/http/headers/content-security-policy/index.html b/files/vi/web/http/headers/content-security-policy/index.html new file mode 100644 index 0000000000..94ee94b509 --- /dev/null +++ b/files/vi/web/http/headers/content-security-policy/index.html @@ -0,0 +1,258 @@ +--- +title: Content-Security-Policy +slug: Web/HTTP/Headers/Content-Security-Policy +tags: + - CSP + - Content Security Policy + - HTTP + - NeedsTranslation + - Reference + - Security + - TopicStub + - header +translation_of: Web/HTTP/Headers/Content-Security-Policy +--- +<div>{{HTTPSidebar}}</div> + +<p>The HTTP <strong><code>Content-Security-Policy</code></strong> response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks ({{Glossary("XSS")}}).</p> + +<p>For more information, see the introductory article on <a href="/en-US/docs/Web/HTTP/CSP">Content Security Policy (CSP)</a>.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Header type</th> + <td>{{Glossary("Response header")}}</td> + </tr> + <tr> + <th scope="row">{{Glossary("Forbidden header name")}}</th> + <td>no</td> + </tr> + </tbody> +</table> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">Content-Security-Policy: <policy-directive>; <policy-directive> +</pre> + +<p>where <code><policy-directive></code> consists of: <code><directive> <value></code> with no internal punctuation.</p> + +<h2 id="Directives">Directives</h2> + +<h3 id="Fetch_directives" name="Fetch_directives">Fetch directives</h3> + +<p>Fetch directives control the locations from which certain resource types may be loaded.</p> + +<dl> + <dt>{{CSP("child-src")}}</dt> + <dd> + <p>Defines the valid sources for <a href="/en-US/docs/Web/API/Web_Workers_API">web workers</a> and nested browsing contexts loaded using elements such as {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.</p> + + <div class="warning"> + <p>Instead of <strong><code>child-src</code></strong>, if you want to regulate nested browsing contexts and workers, you should use the {{CSP("frame-src")}} and {{CSP("worker-src")}} directives, respectively.</p> + </div> + </dd> + <dt>{{CSP("connect-src")}}</dt> + <dd>Restricts the URLs which can be loaded using script interfaces</dd> + <dt>{{CSP("default-src")}}</dt> + <dd>Serves as a fallback for the other {{Glossary("Fetch directive", "fetch directives")}}.</dd> + <dt>{{CSP("font-src")}}</dt> + <dd>Specifies valid sources for fonts loaded using {{cssxref("@font-face")}}.</dd> + <dt>{{CSP("frame-src")}}</dt> + <dd>Specifies valid sources for nested browsing contexts loading using elements such as {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.</dd> + <dt>{{CSP("img-src")}}</dt> + <dd>Specifies valid sources of images and favicons.</dd> + <dt>{{CSP("manifest-src")}}</dt> + <dd>Specifies valid sources of application manifest files.</dd> + <dt>{{CSP("media-src")}}</dt> + <dd>Specifies valid sources for loading media using the {{HTMLElement("audio")}} , {{HTMLElement("video")}} and {{HTMLElement("track")}} elements.</dd> + <dt>{{CSP("object-src")}}</dt> + <dd>Specifies valid sources for the {{HTMLElement("object")}}, {{HTMLElement("embed")}}, and {{HTMLElement("applet")}} elements.</dd> + <dd class="note">Elements controlled by <code>object-src</code> are perhaps coincidentally considered legacy HTML elements and are not receiving new standardized features (such as the security attributes <code>sandbox</code> or <code>allow</code> for <code><iframe></code>). Therefore it is <strong>recommended</strong> to restrict this fetch-directive (e.g., explicitly set <code>object-src 'none'</code> if possible).</dd> + <dt>{{CSP("prefetch-src")}}{{experimental_inline}}</dt> + <dd>Specifies valid sources to be prefetched or prerendered.</dd> + <dt>{{CSP("script-src")}}</dt> + <dd>Specifies valid sources for JavaScript.</dd> + <dt>{{CSP("script-src-elem")}}{{experimental_inline}}</dt> + <dd>Specifies valid sources for JavaScript {{HTMLElement("script")}} elements.</dd> + <dt>{{CSP("script-src-attr")}}{{experimental_inline}}</dt> + <dd>Specifies valid sources for JavaScript inline event handlers.</dd> +</dl> + +<dl> + <dt>{{CSP("style-src")}}</dt> + <dd>Specifies valid sources for stylesheets.</dd> + <dt>{{CSP("style-src-elem")}}{{experimental_inline}}</dt> + <dd>Specifies valid sources for stylesheets {{HTMLElement("style")}} elements and {{HTMLElement("link")}} elements with <code>rel="stylesheet"</code>.</dd> + <dt>{{CSP("style-src-attr")}}{{experimental_inline}}</dt> + <dd>Specifies valid sources for inline styles applied to individual DOM elements.</dd> + <dt>{{CSP("worker-src")}}{{experimental_inline}}</dt> + <dd>Specifies valid sources for {{domxref("Worker")}}, {{domxref("SharedWorker")}}, or {{domxref("ServiceWorker")}} scripts.</dd> +</dl> + +<h3 id="Document_directives" name="Document_directives">Document directives</h3> + +<p>Document directives govern the properties of a document or <a href="/en-US/docs/Web/API/Web_Workers_API">worker</a> environment to which a policy applies.</p> + +<dl> + <dt>{{CSP("base-uri")}}</dt> + <dd>Restricts the URLs which can be used in a document's {{HTMLElement("base")}} element.</dd> + <dt>{{CSP("plugin-types")}}</dt> + <dd>Restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded.</dd> + <dt>{{CSP("sandbox")}}</dt> + <dd>Enables a sandbox for the requested resource similar to the {{HTMLElement("iframe")}} {{htmlattrxref("sandbox", "iframe")}} attribute.</dd> +</dl> + +<h3 id="Navigation_directives" name="Navigation_directives">Navigation directives</h3> + +<p>Navigation directives govern to which locations a user can navigate or submit a form, for example.</p> + +<dl> + <dt>{{CSP("form-action")}}</dt> + <dd>Restricts the URLs which can be used as the target of a form submissions from a given context.</dd> + <dt>{{CSP("frame-ancestors")}}</dt> + <dd>Specifies valid parents that may embed a page using {{HTMLElement("frame")}}, {{HTMLElement("iframe")}}, {{HTMLElement("object")}}, {{HTMLElement("embed")}}, or {{HTMLElement("applet")}}.</dd> + <dt>{{CSP("navigate-to")}}{{experimental_inline}}</dt> + <dd>Restricts the URLs to which a document can initiate navigation by any means, including {{HTMLElement("form")}} (if {{CSP("form-action")}} is not specified), {{HTMLElement("a")}}, {{DOMxRef("window.location")}}, {{DOMxRef("window.open")}}, etc.</dd> +</dl> + +<h3 id="Reporting_directives" name="Reporting_directives">Reporting directives</h3> + +<p>Reporting directives control the reporting process of CSP violations. See also the {{HTTPHeader("Content-Security-Policy-Report-Only")}} header.</p> + +<dl> + <dt>{{CSP("report-uri")}}{{deprecated_inline}}</dt> + <dd>Instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of {{Glossary("JSON")}} documents sent via an HTTP <code>POST</code> request to the specified URI. + <div class="warning"> + <p>Though the {{CSP("report-to")}} directive is intended to replace the deprecated <code><strong>report-uri</strong></code> directive, {{CSP("report-to")}} is not supported in most browsers yet. So for compatibility with current browsers while also adding forward compatibility when browsers get {{CSP("report-to")}} support, you can specify both <code><strong>report-uri</strong></code> and {{CSP("report-to")}}:</p> + + <pre class="syntaxbox notranslate">Content-Security-Policy: ...; report-uri https://endpoint.example.com; report-to groupname</pre> + + <p>In browsers that support {{CSP("report-to")}}, the <code><strong>report-uri</strong></code> directive will be ignored.</p> + </div> + </dd> + <dt>{{CSP("report-to")}}{{experimental_inline}}</dt> + <dd>Fires a <code>SecurityPolicyViolationEvent</code>.</dd> +</dl> + +<h3 id="Other_directives">Other directives</h3> + +<dl> + <dt>{{CSP("block-all-mixed-content")}}</dt> + <dd>Prevents loading any assets using HTTP when the page is loaded using HTTPS.</dd> + <dt>{{CSP("referrer")}}{{deprecated_inline}}{{non-standard_inline}}</dt> + <dd>Used to specify information in the <a href="/en-US/docs/Web/HTTP/Headers/Referer">Referer</a> (sic) header for links away from a page. Use the {{HTTPHeader("Referrer-Policy")}} header instead.</dd> + <dt>{{CSP("require-sri-for")}}{{experimental_inline}}</dt> + <dd>Requires the use of {{Glossary("SRI")}} for scripts or styles on the page.</dd> + <dt>{{CSP("require-trusted-types-for")}}{{experimental_inline}}</dt> + <dd>Enforces <a href="https://w3c.github.io/webappsec-trusted-types/dist/spec/">Trusted Types</a> at the DOM XSS injection sinks.</dd> +</dl> + +<dl> + <dt>{{CSP("trusted-types")}}{{experimental_inline}}</dt> + <dd>Used to specify an allow-list of <a href="https://w3c.github.io/webappsec-trusted-types/dist/spec/">Trusted Types</a> policies. Trusted Types allows applications to lock down DOM XSS injection sinks to only accept non-spoofable, typed values in place of strings.</dd> +</dl> + +<dl> + <dt>{{CSP("upgrade-insecure-requests")}}</dt> + <dd>Instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.</dd> +</dl> + +<h2 id="CSP_in_workers">CSP in workers</h2> + +<p><a href="/en-US/docs/Web/API/Worker">Workers</a> are in general <em>not</em> governed by the content security policy of the document (or parent worker) that created them. To specify a content security policy for the worker, set a <code>Content-Security-Policy</code> response header for the request which requested the worker script itself.</p> + +<p>The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the content security policy of the document or worker that created it.</p> + +<h2 id="Multiple_content_security_policies">Multiple content security policies</h2> + +<p>The CSP mechanism allows multiple policies being specified for a resource, including via the <code>Content-Security-Policy</code> header, the {{HTTPHeader("Content-Security-Policy-Report-Only")}} header and a {{HTMLElement("meta")}} element.</p> + +<p>You can use the <code>Content-Security-Policy</code> header more than once, as in the example below. Pay special attention to the {{CSP("connect-src")}} directive here. Even though the second policy would allow the connection, the first policy contains <code>connect-src 'none'</code>. Adding additional policies <em>can only further restrict</em> the capabilities of the protected resource, which means that there will be no connection allowed and, as the strictest policy, <code>connect-src 'none'</code> is enforced.</p> + +<pre class="notranslate">Content-Security-Policy: default-src 'self' http://example.com; + connect-src 'none'; +Content-Security-Policy: connect-src http://example.com/; + script-src http://example.com/</pre> + +<h2 id="Examples">Examples</h2> + +<p>Example: Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) over https:</p> + +<pre class="notranslate">// header +Content-Security-Policy: default-src https: + +// meta tag +<meta http-equiv="Content-Security-Policy" content="default-src https:"> +</pre> + +<p>Example: Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over HTTPS and to disable plugins:</p> + +<pre class="notranslate">Content-Security-Policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'</pre> + +<p>Example: Do not implement the above policy yet; instead just report violations that would have occurred:</p> + +<pre class="notranslate">Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/</pre> + +<p>See <a href="https://infosec.mozilla.org/guidelines/web_security#Examples_5">Mozilla Web Security Guidelines</a> for more examples.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{specName("CSP 3.0")}}</td> + <td>{{Spec2("CSP 3.0")}}</td> + <td>Adds <code>manifest-src</code>, <code>navigate-to</code>, <code>report-to</code>, <code>strict-dynamic</code>, <code>worker-src</code>. Undeprecates <code>frame-src</code>. Deprecates <code>report-uri</code> in favor if <code>report-to</code>.</td> + </tr> + <tr> + <td>{{specName("Mixed Content")}}</td> + <td>{{Spec2("Mixed Content")}}</td> + <td>Adds <code>block-all-mixed-content</code>.</td> + </tr> + <tr> + <td>{{specName("Subresource Integrity")}}</td> + <td>{{Spec2("Subresource Integrity")}}</td> + <td>Adds <code>require-sri-for</code>.</td> + </tr> + <tr> + <td>{{specName("Upgrade Insecure Requests")}}</td> + <td>{{Spec2("Upgrade Insecure Requests")}}</td> + <td>Adds <code>upgrade-insecure-requests</code>.</td> + </tr> + <tr> + <td>{{specName("CSP 1.1")}}</td> + <td>{{Spec2("CSP 1.1")}}</td> + <td>Adds <code>base-uri</code>, <code>child-src</code>, <code>form-action</code>, <code>frame-ancestors</code>, <code>plugin-types</code>, <code>referrer</code>, and <code>report-uri</code>. Deprecates <code>frame-src</code>.</td> + </tr> + <tr> + <td>{{specName("CSP 1.0")}}</td> + <td>{{Spec2("CSP 1.0")}}</td> + <td>Defines <code>connect-src</code>, <code>default-src</code>, <code>font-src</code>, <code>frame-src</code>, <code>img-src</code>, <code>media-src</code>, <code>object-src</code>, report-uri, <code>sandbox</code>, <code>script-src,</code> and <code>style-src</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("http.headers.csp.Content-Security-Policy")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{HTTPHeader("Content-Security-Policy-Report-Only")}}</li> + <li><a href="/en-US/docs/Web/HTTP/CSP">Learn about: Content Security Policy</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">Content Security in WebExtensions</a></li> + <li><a href="https://csp.withgoogle.com/docs/strict-csp.html">Adopting a strict policy</a></li> + <li><a href="https://github.com/google/csp-evaluator">CSP Evaluator</a> - Evaluate your Content Security Policy</li> +</ul> diff --git a/files/vi/web/http/headers/content-security-policy/style-src/index.html b/files/vi/web/http/headers/content-security-policy/style-src/index.html new file mode 100644 index 0000000000..d4d81d3cce --- /dev/null +++ b/files/vi/web/http/headers/content-security-policy/style-src/index.html @@ -0,0 +1,167 @@ +--- +title: 'CSP: style-src' +slug: Web/HTTP/Headers/Content-Security-Policy/style-src +translation_of: Web/HTTP/Headers/Content-Security-Policy/style-src +--- +<div>{{HTTPSidebar}}</div> + +<p>The HTTP {{HTTPHeader("Content-Security-Policy")}} (CSP) <code><strong>style</strong></code><strong><code>-src</code></strong> directive specifies valid sources for stylesheets.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">CSP version</th> + <td>1</td> + </tr> + <tr> + <th scope="row">Directive type</th> + <td>{{Glossary("Fetch directive")}}</td> + </tr> + <tr> + <th scope="row">{{CSP("default-src")}} fallback</th> + <td>Yes. If this directive is absent, the user agent will look for the <code>default-src</code> directive.</td> + </tr> + </tbody> +</table> + +<h2 id="Syntax">Syntax</h2> + +<p>One or more sources can be allowed for the <code>style-src</code> policy:</p> + +<pre class="syntaxbox notranslate">Content-Security-Policy: style-src <source>; +Content-Security-Policy: style-src <source> <source>; +</pre> + +<h3 id="Sources">Sources</h3> + +<p>{{page("Web/HTTP/Headers/Content-Security-Policy/connect-src", "Sources")}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Violation_cases">Violation cases</h3> + +<p>Với tiêu đề CSP này:</p> + +<pre class="brush: bash notranslate">Content-Security-Policy: style-src https://example.com/</pre> + +<p>các bảng định kiểu sau bị chặn và không tải:</p> + +<pre class="brush: html notranslate"><link href="https://not-example.com/styles/main.css" rel="stylesheet" type="text/css" /> + +<style> +#inline-style { background: red; } +</style> + +<style> + @import url("https://not-example.com/styles/print.css") print; +</style></pre> + +<p>as well as styles loaded using the {{HTTPHeader("Link")}} header:</p> + +<pre class="brush: bash notranslate">Link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet +</pre> + +<p>Inline style attributes are also blocked:</p> + +<pre class="brush: html notranslate"><div style="display:none">Foo</div></pre> + +<p class="brush: js">As well as styles that are applied in Javascript by setting the <code>style</code> attribute directly, or by setting {{domxref("CSSStyleDeclaration.cssText", "cssText")}}:</p> + +<pre class="brush: js notranslate">document.querySelector('div').setAttribute('style', 'display:none;'); +document.querySelector('div').style.cssText = 'display:none;';</pre> + +<p>However, styles properties that are set directly on the element's {{domxref("HTMLElement.style", "style")}} property will not be blocked, allowing users to safely manipulate styles via Javascript:</p> + +<pre class="brush: js notranslate">document.querySelector('div').style.display = 'none';</pre> + +<p>These types of manipulations can be prevented by disallowing Javascript via the {{CSP("script-src")}} CSP directive.</p> + +<h3 id="Unsafe_inline_styles">Unsafe inline styles</h3> + +<div class="note"> +<p><strong>Note:</strong> Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. However, if you absolutely have to use it, there are a few mechanisms that will allow them.</p> +</div> + +<p>To allow inline styles, <code>'unsafe-inline'</code>, a nonce-source or a hash-source that matches the inline block can be specified.</p> + +<pre class="brush: bash notranslate">Content-Security-Policy: style-src 'unsafe-inline'; +</pre> + +<p>The above Content Security Policy will allow inline styles like the {{HTMLElement("style")}} element, and the <code>style</code> attribute on any element:</p> + +<pre class="brush: html notranslate"><style> +#inline-style { background: red; } +</style> + +<div style="display:none">Foo</div> +</pre> + +<p>You can use a nonce-source to only allow specific inline style blocks:</p> + +<pre class="brush: bash notranslate">Content-Security-Policy: style-src 'nonce-2726c7f26c'</pre> + +<p>You will have to set the same nonce on the {{HTMLElement("style")}} element:</p> + +<pre class="brush: html notranslate"><style nonce="2726c7f26c"> +#inline-style { background: red; } +</style></pre> + +<p>Alternatively, you can create hashes from your inline styles. CSP supports sha256, sha384 and sha512.</p> + +<pre class="brush: bash notranslate">Content-Security-Policy: style-src 'sha256-a330698cbe9dc4ef1fb12e2ee9fc06d5d14300262fa4dc5878103ab7347e158f'</pre> + +<p>When generating the hash, don't include the {{HTMLElement("style")}} tags and note that capitalization and whitespace matter, including leading or trailing whitespace.</p> + +<pre class="brush: html notranslate"><style>#inline-style { background: red; }</style></pre> + +<h3 id="Unsafe_style_expressions">Unsafe style expressions</h3> + +<p>The <code>'unsafe-eval'</code> source expression controls several style methods that create style declarations from strings. If <code>'unsafe-eval'</code> isn't specified with the <code>style-src</code> directive, the following methods are blocked and won't have any effect:</p> + +<ul> + <li>{{domxref("CSSStyleSheet.insertRule()")}}</li> + <li>{{domxref("CSSGroupingRule.insertRule()")}}</li> + <li>{{domxref("CSSStyleDeclaration.cssText")}}</li> +</ul> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{specName("CSP 3.0", "#directive-style-src", "style-src")}}</td> + <td>{{Spec2('CSP 3.0')}}</td> + <td>No changes.</td> + </tr> + <tr> + <td>{{specName("CSP 1.1", "#directive-style-src", "style-src")}}</td> + <td>{{Spec2('CSP 1.1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("http.headers.csp.Content-Security-Policy.style-src")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{HTTPHeader("Content-Security-Policy")}}</li> + <li>{{CSP("style-src-elem")}}</li> + <li>{{CSP("style-src-attr")}}</li> + <li>{{HTTPHeader("Link")}} header</li> + <li>{{HTMLElement("style")}}, {{HTMLElement("link")}}</li> + <li>{{cssxref("@import")}}</li> + <li>{{domxref("CSSStyleSheet.insertRule()")}}</li> + <li>{{domxref("CSSGroupingRule.insertRule()")}}</li> + <li>{{domxref("CSSStyleDeclaration.cssText")}}</li> +</ul> diff --git a/files/vi/web/http/headers/index.html b/files/vi/web/http/headers/index.html new file mode 100644 index 0000000000..23d020b770 --- /dev/null +++ b/files/vi/web/http/headers/index.html @@ -0,0 +1,362 @@ +--- +title: HTTP headers +slug: Web/HTTP/Headers +tags: + - HTTP + - Headers + - NeedsTranslation + - Networking + - Reference + - TopicStub +translation_of: Web/HTTP/Headers +--- +<div>{{HTTPSidebar}}</div> + +<p>HTTP headers allow the client and the server to pass additional information with the request or the response. A request header consists of its case-insensitive name followed by a colon '<code>:</code>', then by its value (without line breaks). Leading white space before the value is ignored.</p> + +<p>Custom proprietary headers can be added using the 'X-' prefix, but this convention was deprecated in June 2012, because of the inconveniences it caused when non-standard fields became standard in <a href="https://tools.ietf.org/html/rfc6648">RFC 6648</a>; others are listed in an <a class="external" href="http://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a>, whose original content was defined in <a class="external" href="http://tools.ietf.org/html/rfc4229">RFC 4229</a>. IANA also maintains a <a class="external" href="http://www.iana.org/assignments/message-headers/prov-headers.html">registry of proposed new HTTP message headers</a>.</p> + +<p>Headers can be grouped according to their contexts:</p> + +<ul> + <li>{{Glossary("General header")}}: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body.</li> + <li>{{Glossary("Request header")}}: Headers containing more information about the resource to be fetched or about the client itself.</li> + <li>{{Glossary("Response header")}}: Headers with additional information about the response, like its location or about the server itself (name and version etc.).</li> + <li>{{Glossary("Entity header")}}: Headers containing more information about the body of the entity, like its content length or its MIME-type.</li> +</ul> + +<p>Headers can also be grouped according to how proxies handle them:</p> + +<dl> + <dt><a id="e2e" name="e2e"></a>End-to-end headers</dt> + <dd>These headers must be transmitted to the final recipient of the message; that is, the server for a request or the client for a response. Intermediate proxies must retransmit end-to-end headers unmodified and caches must store them.</dd> + <dt><a id="hbh" name="hbh"></a>Hop-by-hop headers</dt> + <dd>These headers are meaningful only for a single transport-level connection and must not be retransmitted by proxies or cached. Such headers are: {{ httpheader("Connection") }}, {{ httpheader("Keep-Alive") }}, {{ httpheader("Proxy-Authenticate") }}, {{ httpheader("Proxy-Authorization") }}, {{ httpheader("TE") }}, {{ httpheader("Trailer") }}, {{ httpheader("Transfer-Encoding") }} and {{ httpheader("Upgrade") }}. Note that only hop-by-hop headers may be set using the {{ httpheader("Connection") }} general header.</dd> +</dl> + +<p>The following list summaries HTTP headers by their usage category. For an alphabetical list, see the navigation on the left side.</p> + +<h2 id="Authentication">Authentication</h2> + +<dl> + <dt>{{HTTPHeader("WWW-Authenticate")}}</dt> + <dd>Defines the authentication method that should be used to gain access to a resource.</dd> + <dt>{{HTTPHeader("Authorization")}}</dt> + <dd>Contains the credentials to authenticate a user agent with a server.</dd> + <dt>{{HTTPHeader("Proxy-Authenticate")}}</dt> + <dd>Defines the authentication method that should be used to gain access to a resource behind a Proxy server.</dd> + <dt>{{HTTPHeader("Proxy-Authorization")}}</dt> + <dd>Contains the credentials to authenticate a user agent with a proxy server.</dd> +</dl> + +<h2 id="Caching">Caching</h2> + +<dl> + <dt>{{HTTPHeader("Age")}}</dt> + <dd>The time in seconds the object has been in a proxy cache.</dd> + <dt>{{HTTPHeader("Cache-Control")}}</dt> + <dd>Specifies directives for caching mechanisms in both, requests and responses.</dd> + <dt>{{HTTPHeader("Expires")}}</dt> + <dd>The date/time after which the response is considered stale.</dd> + <dt>{{HTTPHeader("Pragma")}}</dt> + <dd>Implementation-specific header that may have various effects anywhere along the request-response chain. Used for backwards compatibility with HTTP/1.0 caches where the <code>Cache-Control</code> header is not yet present.</dd> + <dt>{{HTTPHeader("Warning")}}</dt> + <dd>A general warning field containing information about possible problems.</dd> +</dl> + +<h2 id="Client_hints">Client hints</h2> + +<dl> + <dt>{{HTTPHeader("Accept-CH")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Content-DPR")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("DPR")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Downlink")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Save-Data")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Viewport-Width")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Width")}}</dt> + <dd>...</dd> +</dl> + +<dl> + <dt> + <h2 id="Conditionals">Conditionals</h2> + </dt> + <dt>{{HTTPHeader("Last-Modified")}}</dt> + <dd>It is a validator, the last modification date of the resource, used to compare several versions of the same resource. It is less accurate than {{HTTPHeader("ETag")}}, but easier to calculate in some environments. Conditional requests using {{HTTPHeader("If-Modified-Since")}} and {{HTTPHeader("If-Unmodified-Since")}} use this value to change the behavior of the request.</dd> + <dt>{{HTTPHeader("ETag")}}</dt> + <dd>It is a validator, a unique string identifying the version of the resource. Conditional requests using {{HTTPHeader("If-Match")}} and {{HTTPHeader("If-None-Match")}} use this value to change the behavior of the request.</dd> + <dt>{{HTTPHeader("If-Match")}}</dt> + <dd>Makes the request conditional and applies the method only if the stored resource matches one of the given ETags.</dd> + <dt>{{HTTPHeader("If-None-Match")}}</dt> + <dd>Makes the request conditional and applies the method only if the stored resource doesn't match any of the given ETags. This is used to update caches (for safe requests), or to prevent to upload a new resource when one is already existing.</dd> + <dt>{{HTTPHeader("If-Modified-Since")}}</dt> + <dd>Makes the request conditional and expects the entity to be transmitted only if it has been modified after the given date. This is used to transmit data only when the cache is out of date.</dd> + <dt>{{HTTPHeader("If-Unmodified-Since")}}</dt> + <dd>Makes the request conditional and expects the entity to be transmitted only if it has not been modified after the given date. This is used to ensure the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents.</dd> +</dl> + +<h2 id="Connection_management">Connection management</h2> + +<dl> + <dt>{{HTTPHeader("Connection")}}</dt> + <dd>Controls whether the network connection stays open after the current transaction finishes.</dd> + <dt>{{HTTPHeader("Keep-Alive")}}</dt> + <dd>Controls how long a persistent connection should stay open.</dd> +</dl> + +<h2 id="Content_negotiation">Content negotiation</h2> + +<dl> + <dt>{{HTTPHeader("Accept")}}</dt> + <dd>Informs the server about the types of data that can be sent back. It is MIME-type.</dd> + <dt>{{HTTPHeader("Accept-Charset")}}</dt> + <dd>Informs the server about which character set the client is able to understand.</dd> + <dt>{{HTTPHeader("Accept-Encoding")}}</dt> + <dd>Informs the server about the encoding algorithm, usually a compression algorithm, that can be used on the resource sent back.</dd> + <dt>{{HTTPHeader("Accept-Language")}}</dt> + <dd>Informs the server about the language the server is expected to send back. This is a hint and is not necessarily under the full control of the user: the server should always pay attention not to override an explicit user choice (like selecting a language in a drop down list).</dd> +</dl> + +<dl> +</dl> + +<h2 id="Controls">Controls</h2> + +<dl> + <dt>{{HTTPHeader("Expect")}}</dt> + <dd>Indicates expectations that need to be fulfilled by the server in order to properly handle the request.</dd> + <dt>{{HTTPHeader("Max-Forwards")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="Cookies">Cookies</h2> + +<dl> + <dt>{{HTTPHeader("Cookie")}}</dt> + <dd>Contains stored <a href="/en-US/docs/Web/HTTP/Cookies">HTTP cookies</a> previously sent by the server with the {{HTTPHeader("Set-Cookie")}} header.</dd> + <dt>{{HTTPHeader("Set-Cookie")}}</dt> + <dd>Send cookies from the server to the user agent.</dd> + <dt>{{HTTPHeader("Cookie2")}} {{obsolete_inline}}</dt> + <dd>Used to contain an HTTP cookie, previously sent by the server with the {{HTTPHeader("Set-Cookie2")}} header, but has been obsoleted by the specification. Use {{HTTPHeader("Cookie")}} instead.</dd> + <dt>{{HTTPHeader("Set-Cookie2")}} {{obsolete_inline}}</dt> + <dd>Used to send cookies from the server to the user agent, but has been obsoleted by the specification. Use {{HTTPHeader("Set-Cookie")}} instead.</dd> + <dt> + <h2 id="CORS">CORS</h2> + </dt> + <dt>{{HTTPHeader("Access-Control-Allow-Origin")}}</dt> + <dd>Indicates whether the response can be shared.</dd> + <dt>{{HTTPHeader("Access-Control-Allow-Credentials")}}</dt> + <dd>Indicates whether the response to the request can be exposed when the credentials flag is true.</dd> + <dt>{{HTTPHeader("Access-Control-Allow-Headers")}}</dt> + <dd>Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.</dd> + <dt>{{HTTPHeader("Access-Control-Allow-Methods")}}</dt> + <dd>Specifies the method or methods allowed when accessing the resource in response to a preflight request.</dd> + <dt>{{HTTPHeader("Access-Control-Expose-Headers")}}</dt> + <dd>Indicates which headers can be exposed as part of the response by listing their names.</dd> + <dt>{{HTTPHeader("Access-Control-Max-Age")}}</dt> + <dd>Indicates how long the results of a preflight request can be cached.</dd> + <dt>{{HTTPHeader("Access-Control-Request-Headers")}}</dt> + <dd>Used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.</dd> + <dt>{{HTTPHeader("Access-Control-Request-Method")}}</dt> + <dd>Used when issuing a preflight request to let the server know which <a href="/en-US/docs/Web/HTTP/Methods">HTTP method</a> will be used when the actual request is made.</dd> + <dt>{{HTTPHeader("Origin")}}</dt> + <dd>Indicates where a fetch originates from.</dd> +</dl> + +<h2 id="Do_Not_Track">Do Not Track</h2> + +<dl> + <dt>{{HTTPHeader("DNT")}}</dt> + <dd>Used for expressing the user's tracking preference.</dd> + <dt>{{HTTPHeader("Tk")}}</dt> + <dd>Indicates the tracking status that applied to the corresponding request.</dd> +</dl> + +<h2 id="Downloads">Downloads</h2> + +<dl> + <dt>{{HTTPHeader("Content-Disposition")}}</dt> + <dd>Is a response header if the resource transmitted should be displayed inline (default behavior when the header is not present), or it should be handled like a download and the browser should present a 'Save As' window.</dd> +</dl> + +<h2 id="Message_body_information">Message body information</h2> + +<dl> + <dt>{{HTTPHeader("Content-Length")}}</dt> + <dd>indicates the size of the entity-body, in decimal number of octets, sent to the recipient.</dd> + <dt>{{HTTPHeader("Content-Type")}}</dt> + <dd>Indicates the media type of the resource.</dd> + <dt>{{HTTPHeader("Content-Encoding")}}</dt> + <dd>Used to specify the compression algorithm.</dd> + <dt>{{HTTPHeader("Content-Language")}}</dt> + <dd>Describes the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language.</dd> + <dt>{{HTTPHeader("Content-Location")}}</dt> + <dd>Indicates an alternate location for the returned data.</dd> + <dt> + <h2 id="Proxies">Proxies</h2> + </dt> +</dl> + +<dl> + <dt>{{HTTPHeader("Forwarded")}}</dt> + <dd>Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.</dd> + <dt>{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}</dt> + <dd>Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.</dd> + <dt>{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}</dt> + <dd>Identifies the original host requested that a client used to connect to your proxy or load balancer.</dd> + <dt>{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}</dt> + <dd>identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.</dd> + <dt>{{HTTPHeader("Via")}}</dt> + <dd>Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.</dd> +</dl> + +<h2 id="Redirects">Redirects</h2> + +<dl> + <dt>{{HTTPHeader("Location")}}</dt> + <dd>Indicates the URL to redirect a page to.</dd> +</dl> + +<h2 id="Request_context">Request context</h2> + +<dl> + <dt>{{HTTPHeader("From")}}</dt> + <dd>Contains an Internet email address for a human user who controls the requesting user agent.</dd> + <dt>{{HTTPHeader("Host")}}</dt> + <dd>Specifies the domain name of the server (for virtual hosting), and (optionally) the TCP port number on which the server is listening.</dd> + <dt>{{HTTPHeader("Referer")}}</dt> + <dd>The address of the previous web page from which a link to the currently requested page was followed.</dd> + <dt>{{HTTPHeader("Referrer-Policy")}}</dt> + <dd>Governs which referrer information sent in the {{HTTPHeader("Referer")}} header should be included with requests made.</dd> + <dt>{{HTTPHeader("User-Agent")}}</dt> + <dd>Contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. See also the <a href="/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox">Firefox user agent string reference</a>.</dd> +</dl> + +<h2 id="Response_context">Response context</h2> + +<dl> + <dt>{{HTTPHeader("Allow")}}</dt> + <dd>Lists the set of HTTP request methods support by a resource.</dd> + <dt>{{HTTPHeader("Server")}}</dt> + <dd>Contains information about the software used by the origin server to handle the request.</dd> +</dl> + +<h2 id="Range_requests">Range requests</h2> + +<dl> + <dt>{{HTTPHeader("Accept-Ranges")}}</dt> + <dd>Indicates if the server supports range requests and if so, in which unit the range can be expressed.</dd> + <dt>{{HTTPHeader("Range")}}</dt> + <dd>Indicates the part of a document that the server should return.</dd> + <dt>{{HTTPHeader("If-Range")}}</dt> + <dd>Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource.</dd> + <dt>{{HTTPHeader("Content-Range")}}</dt> + <dd>Indicates where in a full body message a partial message belongs.</dd> +</dl> + +<h2 id="Security">Security</h2> + +<dl> + <dt>{{HTTPHeader("Content-Security-Policy")}} ({{Glossary("CSP")}})</dt> + <dd>Controls resources the user agent is allowed to load for a given page.</dd> + <dt>{{HTTPHeader("Content-Security-Policy-Report-Only")}}</dt> + <dd>Allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of {{Glossary("JSON")}} documents sent via an HTTP <code>POST</code> request to the specified URI.</dd> + <dt>{{HTTPHeader("Public-Key-Pins")}} ({{Glossary("HPKP")}})</dt> + <dd>Associates a specific cryptographic public key with a certain web server to decrease the risk of {{Glossary("MITM")}} attacks with forged certificates.</dd> + <dt>{{HTTPHeader("Public-Key-Pins-Report-Only")}}</dt> + <dd>Sends reports to the report-uri specified in the header and does still allow clients to connect to the server even if the pinning is violated.</dd> +</dl> + +<dl> + <dt>{{HTTPHeader("Strict-Transport-Security")}} ({{Glossary("HSTS")}})</dt> + <dd>Force communication using HTTPS instead of HTTP.</dd> + <dt>{{HTTPHeader("Upgrade-Insecure-Requests")}}</dt> + <dd>Sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the {{CSP("upgrade-insecure-requests")}} directive.</dd> +</dl> + +<dl> + <dt>{{HTTPHeader("X-Content-Type-Options")}}</dt> + <dd>Disables MIME sniffing and forces browser to use the type given in {{HTTPHeader("Content-Type")}}.</dd> +</dl> + +<dl> + <dt>{{HTTPHeader("X-Frame-Options")}} (XFO)</dt> + <dd>Indicates whether a browser should be allowed to render a page in a {{HTMLElement("frame")}}, {{HTMLElement("iframe")}} or {{HTMLElement("object")}}</dd> + <dt>{{HTTPHeader("X-XSS-Protection")}}</dt> + <dd>Enables cross-site scripting filtering.</dd> +</dl> + +<h2 id="Server-sent_events">Server-sent events</h2> + +<dl> + <dt>{{HTTPHeader("Ping-From")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Ping-To")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Last-Event-ID")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="Transfer_coding">Transfer coding</h2> + +<dl> + <dt>{{HTTPHeader("Transfer-Encoding")}}</dt> + <dd>Specifies the the form of encoding used to safely transfer the entity to the user.</dd> + <dt>{{HTTPHeader("TE")}}</dt> + <dd>Specifies the transfer encodings the user agent is willing to accept.</dd> + <dt>{{HTTPHeader("Trailer")}}</dt> + <dd>Allows the sender to include additional fields at the end of chunked message.</dd> +</dl> + +<h2 id="WebSockets">WebSockets</h2> + +<dl> + <dt>{{HTTPHeader("Sec-WebSocket-Key")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Extensions")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Accept")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Protocol")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Version")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="Other">Other</h2> + +<dl> + <dt>{{HTTPHeader("Date")}}</dt> + <dd>Contains the date and time at which the message was originated.</dd> + <dt>{{HTTPHeader("Large-Allocation")}}</dt> + <dd>Tells the browser that the page being loaded is going to want to perform a large allocation.</dd> + <dt>{{HTTPHeader("Link")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Retry-After")}}</dt> + <dd>Indicates how long the user agent should wait before making a follow-up request.</dd> + <dt>{{HTTPHeader("SourceMap")}}</dt> + <dd>Links generated code to a <a href="/en-US/docs/Tools/Debugger/How_to/Use_a_source_map">source map</a>.</dd> + <dt>{{HTTPHeader("Upgrade")}}</dt> + <dd>This is a Proposed Internet Standard. To view a comprehensive list of all Official and Proposed Internet Standards with detailed information about each, <a href="https://www.rfc-editor.org/standards">visit this Internet Standards reference</a>, which is updated daily. The relevant RFC document for the <a href="https://tools.ietf.org/html/rfc7230#section-6.7">Upgrade header field standard is RFC 7230, section 6.7</a>. The standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection. For example, this header standard allows a client to change from HTTP 1.1 to HTTP 2.0, assuming the server decides to acknowledge and implement the Upgrade header field. Niether party is required to accept the terms specified in the Upgrade header field. It can be used in both client and server headers. If the Upgrade header field is specified, then the sender MUST also send the Connection header field with the upgrade option specified. For details on the Connection header field <a href="https://tools.ietf.org/html/rfc7230#section-6.1">please see section 6.1 of the aforementioned RFC</a>.</dd> + <dt>{{HTTPHeader("Vary")}}</dt> + <dd>Determines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server.</dd> + <dt>{{HTTPHeader("X-DNS-Prefetch-Control")}}</dt> + <dd>Controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth.</dd> + <dt>{{HTTPHeader("X-Requested-With")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("X-UA-Compatible")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields">Wikipedia page on List of HTTP headers</a></li> + <li><a href="https://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a></li> +</ul> diff --git a/files/vi/web/http/index.html b/files/vi/web/http/index.html new file mode 100644 index 0000000000..8e05d11ec0 --- /dev/null +++ b/files/vi/web/http/index.html @@ -0,0 +1,84 @@ +--- +title: HTTP +slug: Web/HTTP +tags: + - HTTP + - NeedsTranslation + - Reference + - TopicStub + - Web + - 'l10n:priority' +translation_of: Web/HTTP +--- +<div>{{HTTPSidebar}}</div> + +<p class="summary"><strong><dfn>Hypertext Transfer Protocol (HTTP)</dfn></strong> là một giao thức thuộc <a href="https://vi.wikipedia.org/wiki/T%E1%BA%A7ng_%E1%BB%A9ng_d%E1%BB%A5ng">tầng ứng dụng</a> được dùng để truyền tải các tài liệu đa phương tiện, ví dụ như HTML. Giao thức này được thiết kế để truyền thông giữa các trình duyệt web và máy chủ web, tuy nhiên nó cũng được dùng cho nhiều mục đích khác. HTTP tuân theo một <a href="https://vi.wikipedia.org/wiki/Client-server">mô hình client-server</a> truyền thống, với một client mở một kết nối (connection) để tạo ra một yêu cầu (request), sau đó chờ đợi cho đến khi nó nhận được phản một phản hồi (response). HTTP là một giao thức không lưu lại trạng thái (<a href="https://en.wikipedia.org/wiki/Stateless_protocol">stateless protocol</a>), có nghĩa là máy chủ không lưu giữ bất cữ dữ liệu (state) gì giữa các yêu cầu. Bởi thường được dựa trên một lớp TCP/IP, nó có thể được sử dụng trên bất cứ <a href="https://vi.wikipedia.org/wiki/T%E1%BA%A7ng_giao_v%E1%BA%ADn">tầng giao vận</a> đáng tin cậy nào (reliable transport layer) - những giao thức không bị mất dữ liệu, như là UDP.</p> + +<div class="column-container"> +<div class="column-half"> +<h2 id="Hướng_dẫn">Hướng dẫn</h2> + +<p>Learn how to use HTTP with guides and tutorials.</p> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Overview">Tổng quan về HTTP</a></dt> + <dd>Các chức năng cơ bản của giao thức client-server: nó có thể làm gì và mục đích sử dụng của nó.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Caching">HTTP Cache</a></dt> + <dd>Caching rất quan trọng với tốc độ của các trang web. Bài viết này mô tả các cách thức cache khác nhau cũng như cách sử dụng HTTP Headers để điều khiển chúng.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Cookies">HTTP Cookies</a></dt> + <dd>Cookies hoạt động như thế nào được định nghĩa trong <a class="external" href="http://tools.ietf.org/html/rfc6265">RFC 6265</a>. Khi phục vụ một yêu cầu HTTP (HTTP request), một máy chủ (server) có thể gửi một <code>Set-Cookie</code> HTTP header đính kèm trong phản hồi (response). Máy khách (client) sau đó sẽ gửi trả giá trị của cookie trong mỗi yêu cầu đến máy chủ (server) đó trong Cookie header của yêu cầu (request). Cookie cũng có thể được quy định ngày hết hạn hoặc hạn chế với một tên miền và đường dẫn.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP Access Control (CORS)</a></dt> + <dd><strong>Cross-site HTTP requests</strong> are HTTP requests for resources from a <strong>different domain</strong> than the domain of the resource making the request. For instance, an HTML page from Domain A (<code>http://domaina.example/</code>) makes a request for an image on Domain B (<code>http://domainb.foo/image.jpg</code>) via the <code>img</code> element. Web pages today very commonly load cross-site resources, including CSS stylesheets, images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests.</dd> +</dl> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP">Evolution of HTTP</a></dt> + <dd>A brief description of the changes between the early versions of HTTP, to the modern HTTP/2 and beyond.</dd> + <dt><a href="https://wiki.mozilla.org/Security/Guidelines/Web_Security">Mozilla web security guidelines</a></dt> + <dd>A collection of tips to help operational teams with creating secure web applications.</dd> +</dl> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Messages">HTTP Messages</a></dt> + <dd>Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Session">A typical HTTP session</a></dt> + <dd>Shows and explains the flow of a usual HTTP session.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x">Connection management in HTTP/1.x</a></dt> + <dd>Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses.</dd> +</dl> +</div> + +<div class="column-half"> +<h2 id="Reference">Reference</h2> + +<p>Browse through detailed HTTP reference documentation.</p> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Headers">HTTP Headers</a></dt> + <dd>HTTP message headers are used to describe a resource, or the behavior of the server or the client. Custom proprietary headers can be added using the <code>X-</code> prefix; others in an <a class="external" href="http://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a>, whose original content was defined in <a class="external" href="http://tools.ietf.org/html/rfc4229">RFC 4229</a>. IANA also maintains a <a class="external" href="http://www.iana.org/assignments/message-headers/prov-headers.html">registry of proposed new HTTP message headers</a>.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Methods">HTTP Request Methods</a></dt> + <dd>The different operations that can be done with HTTP: {{HTTPMethod("GET")}}, {{HTTPMethod("POST")}}, and also less common requests like {{HTTPMethod("OPTIONS")}}, {{HTTPMethod("DELETE")}}, or {{HTTPMethod("TRACE")}}.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Response_codes">HTTP Status Response Codes</a></dt> + <dd>HTTP response codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">CSP directives</a></dt> + <dd>The {{HTTPHeader("Content-Security-Policy")}} response header fields allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints.</dd> +</dl> + +<h2 id="Tools_resources">Tools & resources</h2> + +<p>Helpful tools and resources for understanding and debugging HTTP.</p> + +<dl> + <dt><a href="/en-US/docs/Tools">Firefox Developer Tools</a></dt> + <dd><a href="/en-US/docs/Tools/Network_Monitor">Network monitor</a></dd> + <dt><a href="https://observatory.mozilla.org/">Mozilla Observatory</a></dt> + <dd> + <p>A project designed to help developers, system administrators, and security professionals configure their sites safely and securely.</p> + </dd> + <dt><a class="external" href="https://redbot.org/">RedBot</a></dt> + <dd>Tools to check your cache-related headers</dd> + <dt><a href="http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/">How Browsers Work</a></dt> + <dd>A very comprehensive article on browser internals and request flow through HTTP protocol. A MUST-READ for any web developer.</dd> +</dl> +</div> +</div> diff --git a/files/vi/web/index.html b/files/vi/web/index.html new file mode 100644 index 0000000000..8f6b0ea4ab --- /dev/null +++ b/files/vi/web/index.html @@ -0,0 +1,100 @@ +--- +title: Công nghệ lập trình Web +slug: Web +tags: + - Landing + - Web +translation_of: Web +--- +<p class="summary"><span lang="vi"><span class="hps">Sự phát triển rộng rãi của World Wide Web đã tạo ra cơ hội cho các lập trình viên sáng tạo các trang web cũng như ứng dụng online bổ ích</span><span>.</span> <span class="hps">Để tận dụng</span> <span class="hps">đầy đủ</span> <span class="hps">các công nghệ này</span><span>,</span> <span class="hps">bạn cần phải</span> <span class="hps">biết làm thế nào</span> <span class="hps">để sử dụng chúng.</span> <span class="hps">Dưới đây bạn</span> <span class="hps">sẽ tìm thấy</span> <span class="hps">các liên kết</span> <span class="hps">đến các tài liệu</span> <span class="hps">MDN</span> <span class="hps">của các</span> <span class="hps">công nghệ</span> lập trình <span class="hps">Web</span><span>.</span></span></p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Các_công_nghệ_lập_trình_Web">Các công nghệ lập trình Web</h2> + +<h3 class="Documentation" id="Cơ_bản">Cơ bản</h3> + +<dl> + <dt><a href="/vi/docs/Web/HTML">HTML</a></dt> + <dd><strong>HyperText Markup Language (HTML)</strong> là ngôn ngữ được sử dụng để định hình cấu trúc và nội dung của trang Web.</dd> + <dt><a href="/vi/docs/Web/CSS">CSS</a></dt> + <dd><strong>Cascading Style Sheets (CSS)</strong> được sử dụng để biểu thị cách mà một nội dung được hiển thị như thế nào trên Web.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP">HTTP</a></dt> + <dd><strong><dfn>Hypertext Transfer Protocol (HTTP) </dfn></strong><dfn>là g</dfn>iao thức truyền tải siêu văn bản, được sử dụng để truyền tải các nội dung HTML cũng như các nội dung media trên mạng.</dd> +</dl> + +<h3 id="Scripting">Scripting</h3> + +<dl> + <dt><a href="/vi/docs/Web/JavaScript">JavaScript</a></dt> + <dd> + <p>JavaScipt là mội ngôn ngữ lập trình chạy trên các trình duyệt, được sử dụng để xây dựng các trang Web có tính tương tác cao với người sử dụng hoặc tạo ra các ứng dụng Web.</p> + </dd> + <dt><a href="/vi/docs/Web/Reference/API">Web APIs</a></dt> + <dd><strong>Web Application Programming Interfaces (Web APIs) </strong>là giao diện lập trình ứng dụng Web được dùng để vận hành các tính năng đa dạng như điều khiển DOM, phát nhạc và video, hoặc tạo ra đồ họa 3D. + <ul> + <li><a href="/vi/docs/Web/API" title="/en-US/docs/Web/API">Web API interface reference</a> - danh sách các objects bạn có thể dùng khi phát triển web.</li> + <li><a href="https://developer.mozilla.org/en-US/docs/WebAPI">WebAPI page</a> - danh sách các thiết bị kết nối, phần cứng và các API hữu ích khác cho một ứng dụng.</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Events">Event reference</a> - danh sách các sự kiện có thể giúp bạn kiểm soát và phản ứng kịp thời với những gì xảy ra trên trang web của bạn.</li> + </ul> + </dd> +</dl> + +<h3 id="Đồ_họa">Đồ họa</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/HTML/Canvas">Canvas</a></dt> + <dd>The {{HTMLElement("canvas")}} cung cấp API hỗ trợ vẽ 2D bằng Javascript.</dd> +</dl> + +<dl> + <dt><a href="/vi/docs/SVG">SVG</a></dt> + <dd>Scalable Vector Graphics cho phép bạn biểu thị một hình ảnh bằng cách vẽ ra các vector với các hình dạng khác nhau để cho phép hình ảnh đó có thể phóng to thu nhỏ một cách trơn tru với bất kì một kích thước nào.</dd> + <dt><a href="/vi/docs/Web/WebGL" title="/en-US/docs/Web/WebGL">WebGL</a></dt> + <dd>WebGL là một API cho Javascript mang lại đồ họa 3D cho Web bằng cách sử dụng HTML5: {{HTMLElement("canvas")}}.</dd> + <dt> + <h3 id="Âm_Thanh_Video_và_Truyền_Thông_Đa_Phương_Tiện">Âm Thanh, Video, và Truyền Thông Đa Phương Tiện</h3> + </dt> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Media">Công Nghệ Truyền Thông Web</a></dt> + <dd>Danh sách các API có liên quan tới truyền thông và những tài liệu cần thiết.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Media/Overview">Tổng Quan Công Nghệ Truyền Thông trên Web</a></dt> + <dd>Tổng quan về công nghệ web mở và các giao diện lập trình ứng dụng (APIs) hỗ trợ phát sóng âm thành, hình ảnh cũng như điều khiển và ghi hình. Nếu bạn muốn biết bạn nên sử dụng API nào, bạn nên tham khảo tại đây.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API">API hỗ trợ ghi hình và phát sóng truyền thông</a></dt> + <dd>Tài liệu tham khảo các API dùng để ghi hình và phát sóng trong mạng nội bộ cũng như mạng kết nối, bao gồm nhiều phương thức như sử dụng máy ghi hình cũng như máy thu âm để quay video, thu âm, và chụp ảnh tĩnh.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video">Ứng Dụng Âm Thanh và Video trong HTML5</a></dt> + <dd>Nhúng âm thanh hoặc video vào trang web và tích hợp trình điều chỉnh</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/WebRTC">WebRTC</a></dt> + <dd>RTC trong WebRTC là viết tắt của Real-Time Communications, công nghệ cho phép phát sóng trực tiếp âm thanh hình ảnh và truyền dữ liệu giữa các trình duyệt của những người dùng.</dd> +</dl> + +<h3 id="Công_nghệ_khác">Công nghệ khác</h3> + +<dl> + <dt><a href="/vi/docs/Web/MathML">MathML</a></dt> + <dd><strong>Mathematical Markup Language (MathML)</strong> giúp trang web có thể hiển thị các phương trình toán học phức tạp cũng như các cú pháp toán học liên quan.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Documentation" id="Góc_Hướng_Dẫn">Góc Hướng Dẫn</h2> + +<dl> + <dt> </dt> + <dt><a href="https://developer.mozilla.org/en-US/docs/Learn">Hướng Dẫn Lập Trình Web</a></dt> + <dd>Tập hợp các bài viết cho người mới bắt đầu lập trình trang web đơn giản.</dd> +</dl> + +<h2 id="Các_chủ_đề_khác">Các chủ đề khác</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Apps">Developing Web applications - Phát triển ứng dụng Web</a></dt> + <dd>Tài liệu cho các lập trình viên ứng dụng Web cho di động (mobile), máy tính bàn / laptop (desktop), và Firefox.</dd> + <dt><a href="/en-US/docs/Web/Accessibility">Accessibility - khả năng tiếp cận</a></dt> + <dd>Khả năng tiếp cập trong lập trình Web nghĩa là cho cho càng nhiều người sử dụng trang Web của bạn càng tốt, ngay cả khi khả năng của người đó có khiếm khuyết về thị lực hoặc thính giác. Trong phần này chúng tôi cung cấp thông tin về cách phát triển trang Web có tính tiếp cận cao.</dd> + <dt><a href="/en-US/docs/Web/Security">Security - bảo mật </a></dt> + <dd>Chắc chắn rằng việc bảo mật trang Web hoặc ứng dụng Web của bạn là một điều thật sự đáng quan tâm. Tập hợp bài viết ở mục này sẽ giúp cho web của bạn an toàn và bảo mât.</dd> +</dl> +</div> +</div> + +<p><span class="alllinks"><a href="/vi-VN/docs/tag/Web">Xem thêm ...</a></span></p> diff --git a/files/vi/web/javascript/a_re-introduction_to_javascript/index.html b/files/vi/web/javascript/a_re-introduction_to_javascript/index.html new file mode 100644 index 0000000000..531fb96fc0 --- /dev/null +++ b/files/vi/web/javascript/a_re-introduction_to_javascript/index.html @@ -0,0 +1,950 @@ +--- +title: A re-introduction to JavaScript (JS tutorial) +slug: Web/JavaScript/A_re-introduction_to_JavaScript +translation_of: Web/JavaScript/A_re-introduction_to_JavaScript +--- +<div>{{jsSidebar}}</div> + +<p>Tại sao lại là giới thiệu lại? Đó là vì <a href="/en-US/docs/Glossary/JavaScript">JavaScript</a> được coi là một trong những ngôn ngữ hay bị hiểu lầm nhất thế giới. Nó thường chỉ được coi như một món đồ chơi, nhưng bên dưới sự đơn giản đó lại ẩn chứa rất nhiều sức mạnh. JavaScript hiện được dùng bởi rất rất nhiều ứng dụng mạnh mẽ, và một sự hiểu biết sâu sắc về công nghệ này giờ là một trong những kỹ năng quan trọng của bất kỳ lập trình viên web hay ứng dụng di động nào.</p> + +<p>Biết một chút về lịch sử của ngôn ngữ này là rất hữu dụng. JavaScript được tạo ra năm 1995 bởi Brendan Eich khi ông đang là một kỹ sư tại Netscape. JavaScript lần đầu được phát hàng cùng với Netscape 2 đầu năm 1996. Ban đầu nó dự định được gọi là LiveScript, nhưng sau đó đổi lại trong một quyết định marketing sai lầm khi cố gắng nhấn mạnh sự phổ biến của Java, ngôn ngữ lập trình được phát triển bởi Sun Microsystems - dù rằng chúng có rất ít điểm chung. Đây chính là cội rễ của mọi sự hiểu lầm kể từ đó.</p> + +<p>Vài tháng sau đó, Microsoft đã phát hành JScript cùng với Internet Explorer 3. Đó cũng là một trong những bản tương thích JavaScript nhiều nhất. Vài tháng sau đó, Netscape gửi JavaScript lên cho <a class="external" href="http://www.ecma-international.org/">Ecma International</a>, một tổ chức tiêu chuẩn của châu Âu, và kết quả là năm đó phiên bản đầu tiên của chuẩn <a href="/en-US/docs/Glossary/ECMAScript">ECMAScript</a> được đưa ra. Chuẩn này sau đó tiếp tục được cập nhật đáng kể với phiên bản <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript edition 3</a> vào năm 1999, và giữ ổn định kể từ đó. Phiên bản thứ 4 bị hủy bỏ do một số khác biệt về chính sách liên quan đến sự phức tạp của ngôn ngữ. Nhiều phần của phiên bản 4 sau đó trở thành nền tảng cho ECMAScript edition 5, được phát hành vào tháng 12 năm 2009, và cho phiên bản 6 của chuẩn này, phát hành năm 2015.</p> + +<div class="note"> +<p>Trong tài liệu này chúng ta sẽ nói về ECMAScript với tên "JavaScript".</p> +</div> + +<p>Không như hầu hết các ngôn ngữ lập trình, JavaScript không có khái niệm đầu vào hay đầu ra (input/output). Nó được thiết kế để chạy như một ngôn ngữ kịch bản và thực thi trong một môi trường được quản lý (host environment), JavaScript phụ thuộc vào môi trường đang chạy để cung cấp các kỹ thuật khác nhau cho việc giao tiếp với thế giới bên ngoài. Môi trường thực thi phổ biến nhất là trình duyệt, nhưng trình thông dịch JavaScript còn có thể được tìm thấy từ một danh sách khổng lồ khác: Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, các môi trường thực thi phía server như <a href="http://nodejs.org/">Node.js</a>, các cơ sở dữ liệu NoSQL như phần mềm mã nguồn mở <a href="http://couchdb.apache.org/">Apache CouchDB</a>, các máy tính nhúng, các môi trường desktop như <a href="http://www.gnome.org/">GNOME</a> (một trong những giao diện phổ biến nhất cho GNU/Linux operating systems), và nhiều nơi khác.</p> + +<h2 id="Overview">Overview</h2> + +<p>JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes (see more about <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain" title="prototypical inheritance">prototypical inheritance</a> and ES2015 <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classes</a>). JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.</p> + +<p>Let's start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript's types are:</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Symbol")}} (new in ES2015)</li> +</ul> + +<p>... oh, and {{jsxref("undefined")}} and {{jsxref("null")}}, which are ... slightly odd. And {{jsxref("Array")}}, which is a special kind of object. And {{jsxref("Date")}} and {{jsxref("RegExp")}}, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type diagram looks more like this:</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}} (new in ES2015)</li> + <li>{{jsxref("Object")}} + <ul> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Date")}}</li> + <li>{{jsxref("RegExp")}}</li> + </ul> + </li> + <li>{{jsxref("null")}}</li> + <li>{{jsxref("undefined")}}</li> +</ul> + +<p>And there are some built-in {{jsxref("Error")}} types as well. Things are a lot easier if we stick with the first diagram, however, so we'll discuss the types listed there for now.</p> + +<h2 id="Numbers">Numbers</h2> + +<p>Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec. This has some interesting consequences. There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java.</p> + +<p>Also, watch out for stuff like:</p> + +<pre class="brush: js notranslate">0.1 + 0.2 == 0.30000000000000004; +</pre> + +<p>In practice, integer values are treated as 32-bit ints, and some implementations even store it that way until they are asked to perform an instruction that's valid on a Number but not on a 32-bit integer. This can be important for bit-wise operations.</p> + +<p>The standard <a href="/en-US/docs/Web/JavaScript/Reference/Operators#Arithmetic_operators">arithmetic operators</a> are supported, including addition, subtraction, modulus (or remainder) arithmetic, and so forth. There's also a built-in object that we did not mention earlier called {{jsxref("Math")}} that provides advanced mathematical functions and constants:</p> + +<pre class="brush: js notranslate">Math.sin(3.5); +var circumference = 2 * Math.PI * r; +</pre> + +<p>You can convert a string to an integer using the built-in {{jsxref("Global_Objects/parseInt", "parseInt()")}} function. This takes the base for the conversion as an optional second argument, which you should always provide:</p> + +<pre class="brush: js notranslate">parseInt('123', 10); // 123 +parseInt('010', 10); // 10 +</pre> + +<p>In older browsers, strings beginning with a "0" are assumed to be in octal (radix 8), but this hasn't been the case since 2013 or so. Unless you're certain of your string format, you can get surprising results on those older browsers:</p> + +<pre class="brush: js notranslate">parseInt('010'); // 8 +parseInt('0x10'); // 16 +</pre> + +<p>Here, we see the {{jsxref("Global_Objects/parseInt", "parseInt()")}} function treat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading "0x". The <em>hexadecimal notation is still in place</em>; only octal has been removed.</p> + +<p>If you want to convert a binary number to an integer, just change the base:</p> + +<pre class="brush: js notranslate">parseInt('11', 2); // 3 +</pre> + +<p>Similarly, you can parse floating point numbers using the built-in {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} function. Unlike its {{jsxref("Global_Objects/parseInt", "parseInt()")}} cousin, <code>parseFloat()</code> always uses base 10.</p> + +<p>You can also use the unary <code>+</code> operator to convert values to numbers:</p> + +<pre class="brush: js notranslate">+ '42'; // 42 ++ '010'; // 10 ++ '0x10'; // 16 +</pre> + +<p>A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:</p> + +<pre class="brush: js notranslate">parseInt('hello', 10); // NaN +</pre> + +<p><code>NaN</code> is toxic: if you provide it as an operand to any mathematical operation, the result will also be <code>NaN</code>:</p> + +<pre class="brush: js notranslate">NaN + 5; // NaN +</pre> + +<p>You can test for <code>NaN</code> using the built-in {{jsxref("Global_Objects/isNaN", "isNaN()")}} function:</p> + +<pre class="brush: js notranslate">isNaN(NaN); // true +</pre> + +<p>JavaScript also has the special values {{jsxref("Infinity")}} and <code>-Infinity</code>:</p> + +<pre class="brush: js notranslate"> 1 / 0; // Infinity +-1 / 0; // -Infinity +</pre> + +<p>You can test for <code>Infinity</code>, <code>-Infinity</code> and <code>NaN</code> values using the built-in {{jsxref("Global_Objects/isFinite", "isFinite()")}} function:</p> + +<pre class="brush: js notranslate">isFinite(1 / 0); // false +isFinite(-Infinity); // false +isFinite(NaN); // false +</pre> + +<div class="note">The {{jsxref("Global_Objects/parseInt", "parseInt()")}} and {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to <code>NaN</code> if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.</div> + +<h2 id="Strings">Strings</h2> + +<p>Strings in JavaScript are sequences of <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">Unicode characters</a>. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are sequences of UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character is represented by either 1 or 2 code units.</p> + +<p>If you want to represent a single character, you just use a string consisting of that single character.</p> + +<p>To find the length of a string (in code units), access its <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length">length</a></code> property:</p> + +<pre class="brush: js notranslate">'hello'.length; // 5 +</pre> + +<p>There's our first brush with JavaScript objects! Did we mention that you can use strings like {{jsxref("Object", "objects", "", 1)}} too? They have {{jsxref("String", "methods", "#Methods", 1)}} as well that allow you to manipulate the string and access information about the string:</p> + +<pre class="brush: js notranslate">'hello'.charAt(0); // "h" +'hello, world'.replace('world', 'mars'); // "hello, mars" +'hello'.toUpperCase(); // "HELLO" +</pre> + +<h2 id="Other_types">Other types</h2> + +<p>JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the <code>null</code> keyword), and {{jsxref("undefined")}}, which is a value of type <code>undefined</code> that indicates an uninitialized variable — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is <code>undefined</code>. <code>undefined</code> is actually a constant.</p> + +<p>JavaScript has a boolean type, with possible values <code>true</code> and <code>false</code> (both of which are keywords.) Any value can be converted to a boolean according to the following rules:</p> + +<ol> + <li><code>false</code>, <code>0</code>, empty strings (<code>""</code>), <code>NaN</code>, <code>null</code>, and <code>undefined</code> all become <code>false.</code></li> + <li>All other values become <code>true.</code></li> +</ol> + +<p>You can perform this conversion explicitly using the <code>Boolean()</code> function:</p> + +<pre class="brush: js notranslate">Boolean(''); // false +Boolean(234); // true +</pre> + +<p>However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an <code>if</code> statement (see below). For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become <code>true</code> and <code>false</code>, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.</p> + +<p>Boolean operations such as <code>&&</code> (logical <em>and</em>), <code>||</code> (logical <em>or</em>), and <code>!</code> (logical <em>not</em>) are supported; see below.</p> + +<h2 id="Variables">Variables</h2> + +<p>New variables in JavaScript are declared using one of three keywords: <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code>, or <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var" title="/en/JavaScript/Reference/Statements/var">var</a></code>.<br> + <br> + <strong><code>let</code> </strong>allows you to declare block-level variables. The declared variable is available from the <em>block</em> it is enclosed in.</p> + +<pre class="brush: js notranslate">let a; +let name = 'Simon'; +</pre> + +<p>The following is an example of scope with a variable declared with <code><strong>let</strong></code>:</p> + +<pre class="brush: js notranslate">// myLetVariable is *not* visible out here + +for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) { + // myLetVariable is only visible in here +} + +// myLetVariable is *not* visible out here + +</pre> + +<p><code><strong>const</strong></code> allows you to declare variables whose values are never intended to change. The variable is available from the <em>block</em> it is declared in.</p> + +<pre class="brush: js notranslate">const Pi = 3.14; // variable Pi is set +Pi = 1; // will throw an error because you cannot change a constant variable.</pre> + +<p><br> + <code><strong>var</strong></code> is the most common declarative keyword. It does not have the restrictions that the other two keywords have. This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the <strong><code>var</code> </strong>keyword is available from the <em>function</em> it is declared in.</p> + +<pre class="brush: js notranslate">var a; +var name = 'Simon';</pre> + +<p>An example of scope with a variable declared with <strong><code>var</code>:</strong></p> + +<pre class="brush: js notranslate">// myVarVariable *is* visible out here + +for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) { + // myVarVariable is visible to the whole function +} + +// myVarVariable *is* visible out here +</pre> + +<p>If you declare a variable without assigning any value to it, its type is <code>undefined</code>.</p> + +<p>An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have a scope. So if a variable is defined using <code>var</code> in a compound statement (for example inside an <code>if</code> control structure), it will be visible to the entire function. However, starting with ECMAScript 2015, <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code> declarations allow you to create block-scoped variables.</p> + +<h2 id="Operators">Operators</h2> + +<p>JavaScript's numeric operators are <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> and <code>%</code> which is the remainder operator (<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_%28%29">which is the same as modulo</a>.) Values are assigned using <code>=</code>, and there are also compound assignment statements such as <code>+=</code> and <code>-=</code>. These extend out to <code>x = x <em>operator</em> y</code>.</p> + +<pre class="brush: js notranslate">x += 5; +x = x + 5; +</pre> + +<p>You can use <code>++</code> and <code>--</code> to increment and decrement respectively. These can be used as a prefix or postfix operators.</p> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition" title="/en/JavaScript/Reference/Operators/String_Operators"><code>+</code> operator</a> also does string concatenation:</p> + +<pre class="brush: js notranslate">'hello' + ' world'; // "hello world" +</pre> + +<p>If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:</p> + +<pre class="brush: js notranslate">'3' + 4 + 5; // "345" + 3 + 4 + '5'; // "75" +</pre> + +<p>Adding an empty string to something is a useful way of converting it to a string itself.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators" title="/en/JavaScript/Reference/Operators/Comparison_Operators">Comparisons</a> in JavaScript can be made using <code><</code>, <code>></code>, <code><=</code> and <code>>=</code>. These work for both strings and numbers. Equality is a little less straightforward. The double-equals operator performs type coercion if you give it different types, with sometimes interesting results:</p> + +<pre class="brush: js notranslate">123 == '123'; // true +1 == true; // true +</pre> + +<p>To avoid type coercion, use the triple-equals operator:</p> + +<pre class="brush: js notranslate">123 === '123'; // false +1 === true; // false +</pre> + +<p>There are also <code>!=</code> and <code>!==</code> operators.</p> + +<p>JavaScript also has <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators" title="/en/JavaScript/Reference/Operators/Bitwise_Operators">bitwise operations</a>. If you want to use them, they're there.</p> + +<h2 id="Control_structures">Control structures</h2> + +<p>JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by <code>if</code> and <code>else</code>; you can chain them together if you like:</p> + +<pre class="brush: js notranslate">var name = 'kittens'; +if (name == 'puppies') { + name += ' woof'; +} else if (name == 'kittens') { + name += ' meow'; +} else { + name += '!'; +} +name == 'kittens meow'; +</pre> + +<p>JavaScript has <code>while</code> loops and <code>do-while</code> loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:</p> + +<pre class="brush: js notranslate">while (true) { + // an infinite loop! +} + +var input; +do { + input = get_input(); +} while (inputIsNotValid(input)); +</pre> + +<p>JavaScript's <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for"><code>for</code> loop</a> is the same as that in C and Java: it lets you provide the control information for your loop on a single line.</p> + +<pre class="brush: js notranslate">for (var i = 0; i < 5; i++) { + // Will execute 5 times +} +</pre> + +<p>JavaScript also contains two other prominent for loops: <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for</code>...<code>of</code></a></p> + +<pre class="brush: js notranslate">for (let value of array) { + // do something with value +} +</pre> + +<p>and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for</code>...<code>in</code></a>:</p> + +<pre class="brush: js notranslate">for (let property in object) { + // do something with object property +} +</pre> + +<p>The <code>&&</code> and <code>||</code> operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:</p> + +<pre class="brush: js notranslate">var name = o && o.getName(); +</pre> + +<p>Or for caching values (when falsy values are invalid):</p> + +<pre class="brush: js notranslate">var name = cachedName || (cachedName = getName()); +</pre> + +<p>JavaScript has a ternary operator for conditional expressions:</p> + +<pre class="brush: js notranslate">var allowed = (age > 18) ? 'yes' : 'no'; +</pre> + +<p>The <code>switch</code> statement can be used for multiple branches based on a number or string:</p> + +<pre class="brush: js notranslate">switch (action) { + case 'draw': + drawIt(); + break; + case 'eat': + eatIt(); + break; + default: + doNothing(); +} +</pre> + +<p>If you don't add a <code>break</code> statement, execution will "fall through" to the next level. This is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging:</p> + +<pre class="brush: js notranslate">switch (a) { + case 1: // fallthrough + case 2: + eatIt(); + break; + default: + doNothing(); +} +</pre> + +<p>The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the <code>===</code> operator:</p> + +<pre class="brush: js notranslate">switch (1 + 3) { + case 2 + 2: + yay(); + break; + default: + neverhappens(); +} +</pre> + +<h2 id="Objects">Objects</h2> + +<p>JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to:</p> + +<ul> + <li>Dictionaries in Python.</li> + <li>Hashes in Perl and Ruby.</li> + <li>Hash tables in C and C++.</li> + <li>HashMaps in Java.</li> + <li>Associative arrays in PHP.</li> +</ul> + +<p>The fact that this data structure is so widely used is a testament to its versatility. Since everything (bare core types) in JavaScript is an object, any JavaScript program naturally involves a great deal of hash table lookups. It's a good thing they're so fast!</p> + +<p>The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objects. This allows you to build data structures of arbitrary complexity.</p> + +<p>There are two basic ways to create an empty object:</p> + +<pre class="brush: js notranslate">var obj = new Object(); +</pre> + +<p>And:</p> + +<pre class="brush: js notranslate">var obj = {}; +</pre> + +<p>These are semantically equivalent; the second is called object literal syntax and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.</p> + +<p>Object literal syntax can be used to initialize an object in its entirety:</p> + +<pre class="brush: js notranslate">var obj = { + name: 'Carrot', + for: 'Max', // 'for' is a reserved word, use '_for' instead. + details: { + color: 'orange', + size: 12 + } +}; +</pre> + +<p>Attribute access can be chained together:</p> + +<pre class="brush: js notranslate">obj.details.color; // orange +obj['details']['size']; // 12 +</pre> + +<p>The following example creates an object prototype(<code>Person</code>) and an instance of that prototype(<code>you</code>).</p> + +<pre class="brush: js notranslate">function Person(name, age) { + this.name = name; + this.age = age; +} + +// Define an object +var you = new Person('You', 24); +// We are creating a new person named "You" aged 24. + +</pre> + +<p><strong>Once created</strong>, an object's properties can again be accessed in one of two ways:</p> + +<pre class="brush: js notranslate">// dot notation +obj.name = 'Simon'; +var name = obj.name; +</pre> + +<p>And...</p> + +<pre class="brush: js notranslate">// bracket notation +obj['name'] = 'Simon'; +var name = obj['name']; +// can use a variable to define a key +var user = prompt('what is your key?') +obj[user] = prompt('what is its value?') +</pre> + +<p>These are also semantically equivalent. The second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. However, using this method prevents some JavaScript engine and minifier optimizations being applied. It can also be used to set and get properties with names that are <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords" title="/en/JavaScript/Reference/Reserved_Words">reserved words</a>:</p> + +<pre class="brush: js notranslate">obj.for = 'Simon'; // Syntax error, because 'for' is a reserved word +obj['for'] = 'Simon'; // works fine +</pre> + +<div class="note"> +<p>Starting in ECMAScript 5, reserved words may be used as object property names "in the buff". This means that they don't need to be "clothed" in quotes when defining object literals. See the ES5 <a href="http://es5.github.io/#x7.6.1">Spec</a>.</p> +</div> + +<p>For more on objects and prototypes see <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype">Object.prototype</a>. For an explanation of object prototypes and the object prototype chains see <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a>.</p> + +<div class="note"> +<p>Starting in ECMAScript 2015, object keys can be defined by the variable using bracket notation upon being created. <code>{[phoneType]: 12345}</code> is possible instead of just <code>var userPhone = {}; userPhone[phoneType] = 12345</code>.</p> +</div> + +<h2 id="Arrays">Arrays</h2> + +<p>Arrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can naturally be accessed only using <code>[]</code> syntax) but they have one magic property called '<code>length</code>'. This is always one more than the highest index in the array.</p> + +<p>One way of creating arrays is as follows:</p> + +<pre class="brush: js notranslate">var a = new Array(); +a[0] = 'dog'; +a[1] = 'cat'; +a[2] = 'hen'; +a.length; // 3 +</pre> + +<p>A more convenient notation is to use an array literal:</p> + +<pre class="brush: js notranslate">var a = ['dog', 'cat', 'hen']; +a.length; // 3 +</pre> + +<p>Note that <code>array.length</code> isn't necessarily the number of items in the array. Consider the following:</p> + +<pre class="brush: js notranslate">var a = ['dog', 'cat', 'hen']; +a[100] = 'fox'; +a.length; // 101 +</pre> + +<p>Remember — the length of the array is one more than the highest index.</p> + +<p>If you query a non-existent array index, you'll get a value of <code>undefined</code> in return:</p> + +<pre class="brush: js notranslate">typeof a[90]; // undefined +</pre> + +<p>If you take the above about <code>[]</code> and <code>length</code> into account, you can iterate over an array using the following <code>for</code> loop:</p> + +<pre class="brush: js notranslate">for (var i = 0; i < a.length; i++) { + // Do something with a[i] +} +</pre> + +<p>ES2015 introduced the more concise <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for</code>...<code>of</code></a> loop for iterable objects such as arrays:</p> + +<pre class="brush:js notranslate">for (const currentValue of a) { + // Do something with currentValue +}</pre> + +<p>You could also iterate over an array using a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in" title="/en/JavaScript/Reference/Statements/for...in"><code>for</code>...<code>in</code></a> loop, however this does not iterate over the array elements, but the array indices. Furthermore, if someone added new properties to <code>Array.prototype</code>, they would also be iterated over by such a loop. Therefore this loop type is not recommended for arrays.</p> + +<p>Another way of iterating over an array that was added with ECMAScript 5 is <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach()</a></code>:</p> + +<pre class="brush: js notranslate">['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) { + // Do something with currentValue or array[index] +}); +</pre> + +<p>If you want to append an item to an array simply do it like this:</p> + +<pre class="brush: js notranslate">a.push(item);</pre> + +<p>Arrays come with a number of methods. See also the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">full documentation for array methods</a>.</p> + +<table> + <thead> + <tr> + <th scope="col">Method name</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>a.toString()</code></td> + <td>Returns a string with the <code>toString()</code> of each element separated by commas.</td> + </tr> + <tr> + <td><code>a.toLocaleString()</code></td> + <td>Returns a string with the <code>toLocaleString()</code> of each element separated by commas.</td> + </tr> + <tr> + <td><code>a.concat(item1[, item2[, ...[, itemN]]])</code></td> + <td>Returns a new array with the items added on to it.</td> + </tr> + <tr> + <td><code>a.join(sep)</code></td> + <td>Converts the array to a string — with values delimited by the <code>sep</code> param</td> + </tr> + <tr> + <td><code>a.pop()</code></td> + <td>Removes and returns the last item.</td> + </tr> + <tr> + <td><code>a.push(item1, ..., itemN)</code></td> + <td>Appends items to the end of the array.</td> + </tr> + <tr> + <td><code>a.reverse()</code></td> + <td>Reverses the array.</td> + </tr> + <tr> + <td><code>a.shift()</code></td> + <td>Removes and returns the first item.</td> + </tr> + <tr> + <td><code>a.slice(start[, end])</code></td> + <td>Returns a sub-array.</td> + </tr> + <tr> + <td><code>a.sort([cmpfn])</code></td> + <td>Takes an optional comparison function.</td> + </tr> + <tr> + <td><code>a.splice(start, delcount[, item1[, ...[, itemN]]])</code></td> + <td>Lets you modify an array by deleting a section and replacing it with more items.</td> + </tr> + <tr> + <td><code>a.unshift(item1[, item2[, ...[, itemN]]])</code></td> + <td>Prepends items to the start of the array.</td> + </tr> + </tbody> +</table> + +<h2 id="Functions">Functions</h2> + +<p>Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:</p> + +<pre class="brush: js notranslate">function add(x, y) { + var total = x + y; + return total; +} +</pre> + +<p>This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like and can declare its own variables which are local to that function. The <code>return</code> statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns <code>undefined</code>.</p> + +<p>The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to <code>undefined</code>.</p> + +<pre class="brush: js notranslate">add(); // NaN +// You can't perform addition on undefined +</pre> + +<p>You can also pass in more arguments than the function is expecting:</p> + +<pre class="brush: js notranslate">add(2, 3, 4); // 5 +// added the first two; 4 was ignored +</pre> + +<p>That may seem a little silly, but functions have access to an additional variable inside their body called <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments" title="/en/JavaScript/Reference/Functions_and_function_scope/arguments"><code>arguments</code></a>, which is an array-like object holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:</p> + +<pre class="brush: js notranslate">function add() { + var sum = 0; + for (var i = 0, j = arguments.length; i < j; i++) { + sum += arguments[i]; + } + return sum; +} + +add(2, 3, 4, 5); // 14 +</pre> + +<p>That's really not any more useful than writing <code>2 + 3 + 4 + 5</code> though. Let's create an averaging function:</p> + +<pre class="brush: js notranslate">function avg() { + var sum = 0; + for (var i = 0, j = arguments.length; i < j; i++) { + sum += arguments[i]; + } + return sum / arguments.length; +} + +avg(2, 3, 4, 5); // 3.5 +</pre> + +<p>This is pretty useful, but it does seem a little verbose. To reduce this code a bit more we can look at substituting the use of the arguments array through <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameter syntax</a>. In this way, we can pass in any number of arguments into the function while keeping our code minimal. The <strong>rest parameter operator</strong> is used in function parameter lists with the format: <strong>...variable</strong> and it will include within that variable the entire list of uncaptured arguments that the function was called with. We will also replace the <strong>for</strong> loop with a <strong>for...of</strong> loop to return the values within our variable.</p> + +<pre class="brush: js notranslate">function avg(...args) { + var sum = 0; + for (let value of args) { + sum += value; + } + return sum / args.length; +} + +avg(2, 3, 4, 5); // 3.5 +</pre> + +<div class="note">In the above code, the variable <strong>args</strong> holds all the values that were passed into the function.<br> +<br> +It is important to note that wherever the rest parameter operator is placed in a function declaration it will store all arguments <em>after</em> its declaration, but not before. <em>i.e. function</em> <em>avg(</em><strong>firstValue, </strong><em>...args)</em><strong> </strong>will store the first value passed into the function in the <strong>firstValue </strong>variable and the remaining arguments in <strong>args</strong>. That's another useful language feature but it does lead us to a new problem. The <code>avg()</code> function takes a comma-separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:</div> + +<pre class="brush: js notranslate">function avgArray(arr) { + var sum = 0; + for (var i = 0, j = arr.length; i < j; i++) { + sum += arr[i]; + } + return sum / arr.length; +} + +avgArray([2, 3, 4, 5]); // 3.5 +</pre> + +<p>But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function object.</p> + +<pre class="brush: js notranslate">avg.apply(null, [2, 3, 4, 5]); // 3.5 +</pre> + +<p>The second argument to <code>apply()</code> is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objects too.</p> + +<div class="note"> +<p>You can achieve the same result using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> in the function call.</p> + +<p>For instance: <code>avg(...numbers)</code></p> +</div> + +<p>JavaScript lets you create anonymous functions.</p> + +<pre class="brush: js notranslate">var avg = function() { + var sum = 0; + for (var i = 0, j = arguments.length; i < j; i++) { + sum += arguments[i]; + } + return sum / arguments.length; +}; +</pre> + +<p>This is semantically equivalent to the <code>function avg()</code> form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:</p> + +<pre class="brush: js notranslate">var a = 1; +var b = 2; + +(function() { + var b = 3; + a += b; +})(); + +a; // 4 +b; // 2 +</pre> + +<p>JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.</p> + +<pre class="brush: js notranslate">function countChars(elm) { + if (elm.nodeType == 3) { // TEXT_NODE + return elm.nodeValue.length; + } + var count = 0; + for (var i = 0, child; child = elm.childNodes[i]; i++) { + count += countChars(child); + } + return count; +} +</pre> + +<p>This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named <a href="/en-US/docs/Glossary/IIFE">IIFEs (Immediately Invoked Function Expressions)</a> as shown below:</p> + +<pre class="brush: js notranslate">var charsInBody = (function counter(elm) { + if (elm.nodeType == 3) { // TEXT_NODE + return elm.nodeValue.length; + } + var count = 0; + for (var i = 0, child; child = elm.childNodes[i]; i++) { + count += counter(child); + } + return count; +})(document.body); +</pre> + +<p>The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.</p> + +<p>Note that JavaScript functions are themselves objects — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the Objects section.</p> + +<h2 id="Custom_objects">Custom objects</h2> + +<div class="note">For a more detailed discussion of object-oriented programming in JavaScript, see <a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a>.</div> + +<p>In classic Object Oriented Programming, objects are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement). Instead, JavaScript uses functions as classes. Let's consider a person object with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objects that we've discussed previously, we could display the data like this:</p> + +<pre class="brush: js notranslate">function makePerson(first, last) { + return { + first: first, + last: last + }; +} +function personFullName(person) { + return person.first + ' ' + person.last; +} +function personFullNameReversed(person) { + return person.last + ', ' + person.first; +} + +var s = makePerson('Simon', 'Willison'); +personFullName(s); // "Simon Willison" +personFullNameReversed(s); // "Willison, Simon" +</pre> + +<p>This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an object. Since functions are objects, this is easy:</p> + +<pre class="brush: js notranslate">function makePerson(first, last) { + return { + first: first, + last: last, + fullName: function() { + return this.first + ' ' + this.last; + }, + fullNameReversed: function() { + return this.last + ', ' + this.first; + } + }; +} + +var s = makePerson('Simon', 'Willison'); +s.fullName(); // "Simon Willison" +s.fullNameReversed(); // "Willison, Simon" +</pre> + +<p>Note on the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this" title="/en/JavaScript/Reference/Operators/this">this</a></code> keyword. Used inside a function, <code>this</code> refers to the current object. What that actually means is specified by the way in which you called that function. If you called it using <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Accessing_properties" title="/en/JavaScript/Reference/Operators/Member_Operators">dot notation or bracket notation</a> on an object, that object becomes <code>this</code>. If dot notation wasn't used for the call, <code>this</code> refers to the global object.</p> + +<p>Note that <code>this</code> is a frequent cause of mistakes. For example:</p> + +<pre class="brush: js notranslate">var s = makePerson('Simon', 'Willison'); +var fullName = s.fullName; +fullName(); // undefined undefined +</pre> + +<p>When we call <code>fullName()</code> alone, without using <code>s.fullName()</code>, <code>this</code> is bound to the global object. Since there are no global variables called <code>first</code> or <code>last</code> we get <code>undefined</code> for each one.</p> + +<p>We can take advantage of the <code>this</code> keyword to improve our <code>makePerson</code> function:</p> + +<pre class="brush: js notranslate">function Person(first, last) { + this.first = first; + this.last = last; + this.fullName = function() { + return this.first + ' ' + this.last; + }; + this.fullNameReversed = function() { + return this.last + ', ' + this.first; + }; +} +var s = new Person('Simon', 'Willison'); +</pre> + +<p>We have introduced another keyword: <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new" title="/en/JavaScript/Reference/Operators/new">new</a></code>. <code>new</code> is strongly related to <code>this</code>. It creates a brand new empty object, and then calls the function specified, with <code>this</code> set to that new object. Notice though that the function specified with <code>this</code> does not return a value but merely modifies the <code>this</code> object. It's <code>new</code> that returns the <code>this</code> object to the calling site. Functions that are designed to be called by <code>new</code> are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with <code>new</code>.</p> + +<p>The improved function still has the same pitfall with calling <code>fullName()</code> alone.</p> + +<p>Our person objects are getting better, but there are still some ugly edges to them. Every time we create a person object we are creating two brand new function objects within it — wouldn't it be better if this code was shared?</p> + +<pre class="brush: js notranslate">function personFullName() { + return this.first + ' ' + this.last; +} +function personFullNameReversed() { + return this.last + ', ' + this.first; +} +function Person(first, last) { + this.first = first; + this.last = last; + this.fullName = personFullName; + this.fullNameReversed = personFullNameReversed; +} +</pre> + +<p>That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:</p> + +<pre class="brush: js notranslate">function Person(first, last) { + this.first = first; + this.last = last; +} +Person.prototype.fullName = function() { + return this.first + ' ' + this.last; +}; +Person.prototype.fullNameReversed = function() { + return this.last + ', ' + this.first; +}; +</pre> + +<p><code>Person.prototype</code> is an object shared by all instances of <code>Person</code>. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of <code>Person</code> that isn't set, JavaScript will check <code>Person.prototype</code> to see if that property exists there instead. As a result, anything assigned to <code>Person.prototype</code> becomes available to all instances of that constructor via the <code>this</code> object.</p> + +<p>This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objects at runtime:</p> + +<pre class="brush: js notranslate">var s = new Person('Simon', 'Willison'); +s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function + +Person.prototype.firstNameCaps = function() { + return this.first.toUpperCase(); +}; +s.firstNameCaps(); // "SIMON" +</pre> + +<p>Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let's add a method to <code>String</code> that returns that string in reverse:</p> + +<pre class="brush: js notranslate">var s = 'Simon'; +s.reversed(); // TypeError on line 1: s.reversed is not a function + +String.prototype.reversed = function() { + var r = ''; + for (var i = this.length - 1; i >= 0; i--) { + r += this[i]; + } + return r; +}; + +s.reversed(); // nomiS +</pre> + +<p>Our new method even works on string literals!</p> + +<pre class="brush: js notranslate">'This can now be reversed'.reversed(); // desrever eb won nac sihT +</pre> + +<p>As mentioned before, the prototype forms part of a chain. The root of that chain is <code>Object.prototype</code>, whose methods include <code>toString()</code> — it is this method that is called when you try to represent an object as a string. This is useful for debugging our <code>Person</code> objects:</p> + +<pre class="brush: js notranslate">var s = new Person('Simon', 'Willison'); +s.toString(); // [object Object] + +Person.prototype.toString = function() { + return '<Person: ' + this.fullName() + '>'; +} + +s.toString(); // "<Person: Simon Willison>" +</pre> + +<p>Remember how <code>avg.apply()</code> had a null first argument? We can revisit that now. The first argument to <code>apply()</code> is the object that should be treated as '<code>this</code>'. For example, here's a trivial implementation of <code>new</code>:</p> + +<pre class="brush: js notranslate">function trivialNew(constructor, ...args) { + var o = {}; // Create an object + constructor.apply(o, args); + return o; +} +</pre> + +<p>This isn't an exact replica of <code>new</code> as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, <code>...args</code> (including the ellipsis) is called the "<a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest arguments</a>" — as the name implies, this contains the rest of the arguments.</p> + +<p>Calling</p> + +<pre class="brush: js notranslate">var bill = trivialNew(Person, 'William', 'Orange');</pre> + +<p>is therefore almost equivalent to</p> + +<pre class="brush: js notranslate">var bill = new Person('William', 'Orange');</pre> + +<p><code>apply()</code> has a sister function named <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="/en/JavaScript/Reference/Global_Objects/Function/call"><code>call</code></a>, which again lets you set <code>this</code> but takes an expanded argument list as opposed to an array.</p> + +<pre class="brush: js notranslate">function lastNameCaps() { + return this.last.toUpperCase(); +} +var s = new Person('Simon', 'Willison'); +lastNameCaps.call(s); +// Is the same as: +s.lastNameCaps = lastNameCaps; +s.lastNameCaps(); // WILLISON +</pre> + +<h3 id="Inner_functions">Inner functions</h3> + +<p>JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier <code>makePerson()</code> function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:</p> + +<pre class="brush: js notranslate">function parentFunc() { + var a = 1; + + function nestedFunc() { + var b = 4; // parentFunc can't use this + return a + b; + } + return nestedFunc(); // 5 +} +</pre> + +<p>This provides a great deal of utility in writing more maintainable code. If a called function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside it. This keeps the number of functions that are in the global scope down, which is always a good thing.</p> + +<p>This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.</p> + +<h2 id="Closures">Closures</h2> + +<p>This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?</p> + +<pre class="brush: js notranslate">function makeAdder(a) { + return function(b) { + return a + b; + }; +} +var add5 = makeAdder(5); +var add20 = makeAdder(20); +add5(6); // ? +add20(7); // ? +</pre> + +<p>The name of the <code>makeAdder()</code> function should give it away: it creates new 'adder' functions, each of which, when called with one argument, adds it to the argument that it was created with.</p> + +<p>What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they <em>do</em> still exist — otherwise, the adder functions would be unable to work. What's more, there are two different "copies" of <code>makeAdder()</code>'s local variables — one in which <code>a</code> is 5 and the other one where <code>a</code> is 20. So the result of that function calls is as follows:</p> + +<pre class="brush: js notranslate">add5(6); // returns 11 +add20(7); // returns 27 +</pre> + +<p>Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global object that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope object is created every time a function starts executing, and secondly, unlike the global object (which is accessible as <code>this</code> and in browsers as <code>window</code>) these scope objects cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope object, for example.</p> + +<p>So when <code>makeAdder()</code> is called, a scope object is created with one property: <code>a</code>, which is the argument passed to the <code>makeAdder()</code> function. <code>makeAdder()</code> then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope object created for <code>makeAdder()</code> at this point, but the returned function maintains a reference back to that scope object. As a result, the scope object will not be garbage-collected until there are no more references to the function object that <code>makeAdder()</code> returned.</p> + +<p>Scope objects form a chain called the scope chain, similar to the prototype chain used by JavaScript's object system.</p> + +<p>A <strong>closure</strong> is the combination of a function and the scope object in which it was created. Closures let you save state — as such, they can often be used in place of objects. You can find <a href="http://stackoverflow.com/questions/111102/how-do-javascript-closures-work">several excellent introductions to closures</a>.</p> + +<div id="gtx-trans" style="position: absolute; left: 72px; top: 4643px;"> +<div class="gtx-trans-icon"></div> +</div> diff --git a/files/vi/web/javascript/closures/index.html b/files/vi/web/javascript/closures/index.html new file mode 100644 index 0000000000..c2168a9593 --- /dev/null +++ b/files/vi/web/javascript/closures/index.html @@ -0,0 +1,452 @@ +--- +title: Closures +slug: Web/JavaScript/Closures +translation_of: Web/JavaScript/Closures +--- +<div>{{jsSidebar("Intermediate")}}</div> + +<p class="summary"><em>Closure</em> là một hàm được viết lồng vào bên trong một hàm khác (hàm cha) nó có thể sử dụng biến toàn cục, biến cục bộ của hàm cha và biến cục bộ của chính nó (lexical scoping)</p> + +<h2 id="Lexical_scoping">Lexical scoping</h2> + +<p>Xem xét ví dụ sau</p> + +<div> +<pre class="brush: js">function init() { + var name = 'Mozilla'; // name là biến cục bộ của hàm init + function displayName() { // displayName() là hàm closure + alert(name); // sử dụng biến của hàm cha + } + displayName(); +} +init();</pre> +</div> + +<p><code>init()</code> tạo một biến cục bộ <code>name</code> và một hàm <code>displayName()</code>. Hàm <code>displayName()</code> được khai báo bên trong hàm <code>init()</code> và chỉ tồn tại bên trong hàm <code>init()</code> . Hàm <code>displayName()</code> không có biến cục bộ nào của chính nó. Tuy nhiên, hàm <code>displayName()</code> truy cập đến biến <code>name</code> vốn được định nghĩa ở hàm cha, <code>init()</code>. Nếu bên trong hàm <code>displayName()</code> có khai báo biến cục bộ của chính nó, biến đó sẽ được sử dụng.</p> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/78dg25ax/", "js,result", 250)}}</p> + +<p><a href="http://jsfiddle.net/xAFs9/3/" title="http://jsfiddle.net/xAFs9/">Thực thi</a> đoạn code trên sẽ nhận được kết quả từ <code>alert()</code> bên trong hàm <code>displayName()</code> , giá trị biến <code>name</code> . Đây là một ví dụ của <strong><em>lexical</em> <em>scoping</em></strong>, cách các biến được truy cập như thế nào khi hàm được lồng nhau. Hàm lồng bên trong có thể truy suất đến biến được khai bào từ hàm bên ngoài.</p> + +<h2 id="Closure">Closure</h2> + +<p>Giờ xem xét đến ví dụ sau:</p> + +<pre class="brush: js">function makeFunc() { + var name = 'Mozilla'; + function displayName() { + alert(name); + } + return displayName; +} + +var myFunc = makeFunc(); +myFunc(); +</pre> + +<p>Chạy đoạn code trên sẽ nhận kết quả tương tự như ví dụ hàm <code>init()</code> ở trên; sự khác nhau ở đây là gì? khi gọi hàm makeFunc<code>()</code> sẽ return về hàm <code>displayName()</code> , và chưa hề chạy qua đoạn code trong hàm <code>displayName()</code>.</p> + +<p>Thoạt nhìn, đoạn code này sẽ không dễ nhận ra đoạn code này vẫn chạy bình thường. Trong một số ngôn ngữ lập trình khác, biến cục bộ bên trong một hàm chỉ tồn tại trong quá trình hàm thực thi. Một khi <code>makeFunc()</code> chạy xong, chúng ta sẽ nghĩ rằng biến <code>name</code> sẽ không còn thể truy cập được. Tuy nhiên, đoạn code trên sẽ vẫn cho ra kết quả không khác gì ví dụ ở trên cùng, rõ ràng đây là một tính chất đặc biệt của Javascript.</p> + +<p>Trong trường hợp này, <code>myFunc</code> đang tham chiếu đến một instance <code>displayName</code> được tạo ra khi chạy <code>makeFunc</code>. Instance của <code>displayName</code> sẽ duy trì lexical environment, biến <code>name</code> sẽ vẫn tồn tại. Với lý do này, khi gọi hàm <code>myFunc</code> , giá trị biến <code>name</code> vẫn có và chuỗi "Mozilla" sẽ được đưa vào hàm <code>alert</code>.</p> + +<p>Một ví dụ thú vị khác — hàm <code>makeAdder</code>:</p> + +<pre class="brush: js">function makeAdder(x) { + return function(y) { + return x + y; + }; +} + +var add5 = makeAdder(5); +var add10 = makeAdder(10); + +console.log(add5(2)); // 7 +console.log(add10(2)); // 12 +</pre> + +<p>Trong ví dụ này, chúng ta định nghĩa hàm <code>makeAdder(x)</code>, nhận vào 1 argument, <code>x</code>, và trả về một hàm khác. Hàm trả về nhận vào 1 argument, <code>y</code>, và trả về kết của của <code>x</code> + <code>y</code>.</p> + +<p>Bản chất, <code>makeAdder</code> là một hàm factory — nó tạo ra một hàm khác nhận một argument. Ví dụ trên chúng ta sử dụng hàm factory để tạo ra 2 functions — cái thứ nhất thêm argument là 5, cái thứ 2 thêm 10.</p> + +<p><code>add5</code> và <code>add10</code> đều là closures. Cùng một xử lý bên trong, nhưng được lưu ở lexical environments khác nhau. Trong lexical environment của <code>add5</code> , <code>x</code> = 5, trong khi lexical environment của <code>add10</code>, <code>x</code> = 10.</p> + +<h2 id="Ứng_dụng_closures">Ứng dụng closures</h2> + +<p>Closures hữu dụng vì nó cho phép chúng ta gắn một vài dữ liệu (bên trong lexical environment) với một function sẽ tương tác với dữ liệu. Tương tự như trong object-oriented programming, các object cho phép chúng ta gắn một vài dữ liệu với một hoặc nhiều phương thức bên trong</p> + +<p>Trên nền web, hầu hết code được viết bằng JavaScript là event-based — chúng ta định nghĩa một xử lý, sau đó gắn nó vào event sẽ được gọi bởi user (ví dụ như click hay keypress). Đoạn code của chúng ta sẽ là callback: 1 function chạy khi có một sự kiện xảy ra.</p> + +<p>Ví dụ, giả sử chúng ta muốn thêm một cái button để thay đổi kích thước chữ. Một trong những cách làm là set font-size cho thẻ <code>body</code> bằng giá trị pixels, sau đó set kích thước của những phần từ khác (như header) sử dụng đơn vị <code>em</code> :</p> + +<pre class="brush: css">body { + font-family: Helvetica, Arial, sans-serif; + font-size: 12px; +} + +h1 { + font-size: 1.5em; +} + +h2 { + font-size: 1.2em; +} +</pre> + +<p>Khi thay đổi <code>font-size</code> của thẻ <code>body</code> , kích thước font của h1, h2 sẽ tự động được điều chỉnh.</p> + +<p>Trong JavaScript:</p> + +<pre class="brush: js">function makeSizer(size) { + return function() { + document.body.style.fontSize = size + 'px'; + }; +} + +var size12 = makeSizer(12); +var size14 = makeSizer(14); +var size16 = makeSizer(16); +</pre> + +<p><code>size12</code>, <code>size14</code>, và <code>size16</code> là những hàm sẽ thay đổi kích thước font chữ của body qua 12, 14, và 16 pixels. Gắn cho các button tương ứng:</p> + +<pre class="brush: js">document.getElementById('size-12').onclick = size12; +document.getElementById('size-14').onclick = size14; +document.getElementById('size-16').onclick = size16; +</pre> + +<pre class="brush: html"><a href="#" id="size-12">12</a> +<a href="#" id="size-14">14</a> +<a href="#" id="size-16">16</a> +</pre> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/vnkuZ/7726/","","200")}}</p> + +<h2 id="Giả_lập_phương_thức_private_với_closures">Giả lập phương thức private với closures</h2> + +<p>Những ngôn ngữ như Java chúng ta có cách để khai báo các phương thức private, nghĩa là phương thức chỉ được gọi bởi các phương thức khác nằm cùng class.</p> + +<p>JavaScript không hỗ trợ cách làm chính quy cho việc này, tuy nhiên có thể giả lập việc này bằng closures. Phương thức Private không chỉ hữu dụng trong việc giới hạn việc truy cập: nó còn là một cách rất tốt để quản lý global namespace, giữ các phương thức không cần thiết có thể làm xáo trộn những phương thức public.</p> + +<p>Đoạn code bên dưới diễn giải cách sử dụng closures để khai báo một phương thức public có thể truy cập phương thức private và biến. Sử dụng closures như thế này gọi là <a class="external" href="http://www.google.com/search?q=javascript+module+pattern" title="http://www.google.com/search?q=javascript+module+pattern">module pattern</a>:</p> + +<pre class="brush: js">var counter = (function() { + var privateCounter = 0; + function changeBy(val) { + privateCounter += val; + } + return { + increment: function() { + changeBy(1); + }, + decrement: function() { + changeBy(-1); + }, + value: function() { + return privateCounter; + } + }; +})(); + +console.log(counter.value()); // logs 0 +counter.increment(); +counter.increment(); +console.log(counter.value()); // logs 2 +counter.decrement(); +console.log(counter.value()); // logs 1 +</pre> + +<p>Mỗi closure có một lexical environment. Ở đây, chúng ta tạo 1 lexical environment cho cả 3 function: <code>counter.increment</code>, <code>counter.decrement</code>, and <code>counter.value</code>.</p> + +<p>Lexical environment được tạo bên trong một hàm không tên function, sẽ được tạo ra ngay khi được gán cho một khai báo. Lexical environment chứa 2 private: biến <code>privateCounter</code> và hàm <code>changeBy</code>. Cả 2 đối tượng private đều không thể được truy cập trực tiếp từ bên ngoài. Thay vào đó, nó chỉ có thể tương tác thông qua 3 phương thức public.</p> + +<p>Cả 3 phương thức public đều là closures chia sẽ cùng 1 Lexical environment. Cả 3 đều có thể truy cập đến <code>privateCounter</code> và <code>changeBy</code></p> + +<div class="note"> +<p>Chúng ta khai báo một hàm không tên tạo counter, và gọi nó ngay lập tức rồi gắn vào biến <code>counter</code> . Chúng ta lưu hàm này vào một biến khác <code>makeCounter</code> và sử dụng nó để tạo ra nhiều counter khác</p> +</div> + +<pre class="brush: js">var makeCounter = function() { + var privateCounter = 0; + function changeBy(val) { + privateCounter += val; + } + return { + increment: function() { + changeBy(1); + }, + decrement: function() { + changeBy(-1); + }, + value: function() { + return privateCounter; + } + } +}; + +var counter1 = makeCounter(); +var counter2 = makeCounter(); +alert(counter1.value()); /* Alerts 0 */ +counter1.increment(); +counter1.increment(); +alert(counter1.value()); /* Alerts 2 */ +counter1.decrement(); +alert(counter1.value()); /* Alerts 1 */ +alert(counter2.value()); /* Alerts 0 */ +</pre> + +<p>Để ý cách 2 counters, <code>counter1</code> và <code>counter2</code>, hoàn toàn độc lập với nhau. Mỗi closure tham chiếu đến các instance khác nhau của <code>privateCounter</code> .</p> + +<div class="note"> +<p>Sử dụng closures bằng cách này cho ta rất nhiều ưu điểm như trong object-oriented programming -- cụ thể, dữ liệu được ẩn đi và đóng gói.</p> +</div> + +<h2 id="Closure_Scope_Chain">Closure Scope Chain</h2> + +<p>Mỗi closure chúng ta có 3 scopes:-</p> + +<ul> + <li>Scope cục bộ</li> + <li>Scope của function chứa closure</li> + <li>Scope global</li> +</ul> + +<p>Chúng ta có thể truy cập đến cả 3 scope này trong closure tuy nhiên sẽ ra sau nếu chúng lồng nhiều closure với nhau. Như ví dụ sau:</p> + +<pre class="brush: js">// global scope +var e = 10; +function sum(a){ + return function(b){ + return function(c){ + // outer functions scope + return function(d){ + // local scope + return a + b + c + d + e; + } + } + } +} + +console.log(sum(1)(2)(3)(4)); // log 20 + +// chúng ta có thể không dùng hàm không tên: + +// global scope +var e = 10; +function sum(a){ + return function sum2(b){ + return function sum3(c){ + // outer functions scope + return function sum4(d){ + // local scope + return a + b + c + d + e; + } + } + } +} + +var s = sum(1); +var s1 = s(2); +var s2 = s1(3); +var s3 = s2(4); +console.log(s3) //log 20 +</pre> + +<p>Với ví dụ trên, chúng ta có thể nói toàn bộ closure sẽ có cùng scope với function cha.</p> + +<h2 id="Tạo_closures_trong_vòng_lặp_lỗi_thường_thấy">Tạo closures trong vòng lặp: lỗi thường thấy</h2> + +<p>Trước khi có từ khóa <a href="/en-US/docs/Web/JavaScript/Reference/Statements/let" title="let"><code>let</code> keyword</a> được giới thiệu trong ECMAScript 2015, một lỗi thường gặp trong closure khi nó được tạo bên trong vòng lặp. Xem ví dụ sau:</p> + +<pre class="brush: html"><p id="help">Helpful notes will appear here</p> +<p>E-mail: <input type="text" id="email" name="email"></p> +<p>Name: <input type="text" id="name" name="name"></p> +<p>Age: <input type="text" id="age" name="age"></p> +</pre> + +<pre class="brush: js">function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + var item = helpText[i]; + document.getElementById(item.id).onfocus = function() { + showHelp(item.help); + } + } +} + +setupHelp(); +</pre> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/8164/", "", 200)}}</p> + +<p>Mảng <code>helpText</code> khai báo 3 string help, tương ứng cho mỗi ID của input. Vòng lặp chạy qua cả 3 khai báo này, chèn vào sự kiện <code>onfocus</code> để hiển thị đoạn string phù hợp với từng input.</p> + +<p>Nếu thử chạy đoạn code này, bạn sẽ thấy kết quả không giống như chúng ta nghĩ. Mặc cho chúng ta đang focus vào input nào, dòng message hiển thị sẽ luôn là "Your age (you must be over 16)".</p> + +<p>Lý do là hàm gắn cho sự kiện <code>onfocus</code> là closures; nó sẽ thống nhất các khai báo trong và đưa vào chung scope của hàm <code>setupHelp</code>. Cả 3 closures được tạo trong vòng lặp, nhưng cùng chung lexical environment, tức là dùng chung biến <code>item.help</code>. Giá trị <code>item.help</code> được xác định khi <code>onfocus</code> được gọi. Vì ở đây vòng lặp đã chạy đến giá trị cuối cùng của mảng, biến <code>item</code> sẽ trỏ đến giá trị cuối cùng trong mảng.</p> + +<p>Giải pháp trong tình huống này là dùng thêm một closures: như cách chúng ta viết function factory trước đó:</p> + +<pre class="brush: js">function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function makeHelpCallback(help) { + return function() { + showHelp(help); + }; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + var item = helpText[i]; + document.getElementById(item.id).onfocus = makeHelpCallback(item.help); + } +} + +setupHelp(); +</pre> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/9573/", "", 300)}}</p> + +<p>Hàm <code>makeHelpCallback</code> đã tạo ra một<em> lexical environment</em> riêng cho mỗi callback.</p> + +<p>Một cách khác là sử dụng closure không tên</p> + +<pre class="brush: js">function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + (function() { + var item = helpText[i]; + document.getElementById(item.id).onfocus = function() { + showHelp(item.help); + } + })(); // Immediate event listener attachment with the current value of item (preserved until iteration). + } +} + +setupHelp();</pre> + +<p>Nếu không muốn sử dụng nhiều closure, có thể dùng từ khóa <code><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let">let</a></code> được giới thiệu trong ES2015 :</p> + +<pre class="brush: js">function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + let item = helpText[i]; + document.getElementById(item.id).onfocus = function() { + showHelp(item.help); + } + } +} + +setupHelp();</pre> + +<p>Ví dụ này ta sử dụng <code>let</code> thay cho <code>var</code>, như thế mỗi closure được gán cho 1 biến block-scoped.</p> + +<p>Một cách khác nữa là dùng <code>forEach()</code> để lặp qua mảng <code>helpText</code> và gắn hàm xử lý {{htmlelement("div")}}, như bên dưới:</p> + +<pre class="brush: js">function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + helpText.forEach(function(text) { + document.getElementById(text.id).onfocus = function() { + showHelp(text.help); + } + }); +} + +setupHelp();</pre> + +<h2 id="Cân_nhắc_về_hiệu_năng">Cân nhắc về hiệu năng</h2> + +<p>Dùng closure trong những trường hợp thực sự không cần thiết thì không khôn ngoan vì nó có thể ảnh hưởng hiệu năng lúc chạy.</p> + +<p>Một ví dụ, khi tạo mới một object/class, phương thức thường nên gán vào object mà không nên khai báo bên trong hàm khởi tạo của object. Lý do là mỗi khi hàm constructor được gọi, phương thức sẽ được gán lại một lần nữa trên mỗi một object được tạo ra</p> + +<p>Ví dụ cho trường hợp sau:</p> + +<pre class="brush: js">function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); + this.getName = function() { + return this.name; + }; + + this.getMessage = function() { + return this.message; + }; +} +</pre> + +<p>Bởi vì đoạn code trên không thực sự cần những lợi ích có được từ closure trên mỗi instance, chúng ta có thể viết lại mà không sử dụng closure:</p> + +<pre class="brush: js">function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); +} +MyObject.prototype = { + getName: function() { + return this.name; + }, + getMessage: function() { + return this.message; + } +}; +</pre> + +<p>Tuy nhiên, khai báo lại prototype không được khuyến khích. Chúng ta mở rộng prototype bằng cách sau:</p> + +<pre class="brush: js">function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); +} +MyObject.prototype.getName = function() { + return this.name; +}; +MyObject.prototype.getMessage = function() { + return this.message; +}; +</pre> + +<p>Trong 2 ví dụ trên, tất cả object sẽ kế thừa cùng những prototype và khai báo phương thức trên mỗi object không bắt buộc. Xem <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">Details of the Object Model</a> để tìm hiểu thêm</p> diff --git a/files/vi/web/javascript/data_structures/index.html b/files/vi/web/javascript/data_structures/index.html new file mode 100644 index 0000000000..cbf63cdadf --- /dev/null +++ b/files/vi/web/javascript/data_structures/index.html @@ -0,0 +1,285 @@ +--- +title: Kiểu dữ liệu và cấu trúc dữ liệu trong Javascript +slug: Web/JavaScript/Data_structures +translation_of: Web/JavaScript/Data_structures +--- +<div>{{jsSidebar("More")}}</div> + +<p>Tất cả các ngôn ngữ lập trình đều có cấu trúc dữ liệu dựng sẵn, nhưng mỗi ngôn ngữ thường có những kiểu cấu trúc dữ liệu khác nhau. Bài viết này sẽ cố gắng liệt kê những kiểu dữ liệu dựng sẵn trong Javascript và những thuộc tính của chúng. Chúng có thể được dùng để xây dựng những kiểu cấu trúc dữ liệu khác. Khi có thể, rút ra so sánh với những ngôn ngữ khác.</p> + +<h2 id="Kiểu_động">Kiểu động</h2> + +<p>JavaScript là một ngôn ngữ <em>định kiểu yếu</em> hay <em>động</em>. Điều đó nghĩa là không cần phải khai báo kiểu của các biến trước khi dùng. Kiểu sẽ được xác định tự động trong khi chương trình được thực thi. Điều đó cũng có nghĩa là một biến có thể chứa giá trị của các kiểu dữ liệu khác nhau:</p> + +<pre class="brush: js notranslate">let foo = 42; // foo là một số +foo = 'bar'; // foo bây giờ là một chuỗi +foo = true; // foo bây giờ là một boolean +</pre> + +<h2 id="Các_kiểu_Dữ_liệu_và_kiểu_Cấu_trúc">Các kiểu Dữ liệu và kiểu Cấu trúc</h2> + +<p>Tiêu chuẩn ECMAScript mới nhất xác định chín kiểu:</p> + +<ul> + <li>Sáu kiểu Dữ liệu {{Glossary("Primitive", "sơ khai")}} (primitive), có thể kiểm tra với toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a>: + + <ul> + <li>{{Glossary("Undefined", "Kiểu undefined")}}: <code>typeof instance === "undefined"</code></li> + <li>{{Glossary("Boolean", "Kiểu Boolean")}}: <code>typeof instance === "boolean"</code></li> + <li>{{Glossary("Number", "Kiểu số")}}: <code>typeof instance === "number"</code></li> + <li>{{Glossary("String", "Kiểu chuỗi")}}: <code>typeof instance === "string"</code></li> + <li>{{Glossary("BigInt", "Kiểu số BigInt")}}: <code>typeof instance === "bigint"</code></li> + <li>{{Glossary("Symbol", "Kiểu Symbol")}}: <code>typeof instance === "symbol"</code></li> + </ul> + </li> + <li>{{Glossary("null", "Kiểu null")}}: <code>typeof instance === "object"</code>. Một kiểu {{Glossary("Primitive", "sơ khai")}} mà giá trị của nó có thêm một vai trò đặc biệt: nếu object không kế thừa từ đối tượng nào khác, <code>null</code> sẽ được hiển thị ở cuối <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">chuỗi Prototype</a></li> + <li>{{Glossary("Object", "Object")}}: <code>typeof instance === "object"</code>. Kiểu phi dữ liệu nhưng có cấu trúc cho các đối tượng <a href="/en-US/docs/Learn/JavaScript/Objects#The_Constructor">được khởi tạo</a> và được dùng như cấu trúc dữ liệu: new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>, new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a>, new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map</a>, new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a>, new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap">WeakMap</a>, new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet">WeakSet</a>, new <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a> hay bất kỳ đối tượng nào được tạo ra với <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">từ khóa new</a>.</li> + <li>Kiểu phi dữ liệu {{Glossary("Function", "Function")}}, mặc dù khi gọi với typeof nó có nhãn riêng: <code>typeof instance === "function"</code>. Giá trị trả về từ typeof này là một nhãn đặc biệt cho các function, cho dù constructor của Function phát sinh từ Object constructor.</li> +</ul> + +<p>Lưu ý: vai trò có giá trị duy nhất của toán tử <code>typeof</code> là dùng để kiểm tra các kiểu Dữ liệu (sơ khai). Nếu bạn muốn kiểm tra các kiểu Cấu trúc phát sinh từ Object, <code>typeof</code> sẽ chẳng có ích gì vì nó sẽ luôn trả về <code>"object"</code>. Cách đúng đắn để kiểm tra một Object thuộc loại nào là dùng từ khóa <a href="/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a>. Tuy nhiên, ngay cả với cách này cũng có một vài ngoại lệ.</p> + +<h2 id="Giá_trị_sơ_khai">Giá trị sơ khai</h2> + +<p>Tất cả các kiểu trừ đối tượng đều được xác định giá trị bất biến (giá trị không có khả năng thay đổi). Ví dụ (và không như ngôn ngữ C), các chuỗi là bất biến. Ta gọi chúng là "giá trị sơ khai" ("primitive").</p> + +<h3 id="Kiểu_boolean">Kiểu boolean</h3> + +<p>Kiểu boolean mang hai giá trị logic là: <code>true</code>, và <code>false</code>. Xem thêm {{Glossary("Boolean")}} và {{jsxref("Boolean")}}.</p> + +<h3 id="Kiểu_null">Kiểu null</h3> + +<p>Có duy nhất một giá trị: <code>null</code>. Xem {{jsxref("null")}} và {{Glossary("Null")}} để biết thêm chi tiết.</p> + +<h3 id="Kiểu_undefined">Kiểu undefined</h3> + +<p>Một biến chưa được gán giá trị có giá trị <code>undefined</code>. Xem {{jsxref("undefined")}} và {{Glossary("Undefined")}} để biết thêm chi tiết.</p> + +<h3 id="Kiểu_số_Number">Kiểu số Number</h3> + +<p>Theo tiêu chuẩn ECMAScript, chỉ có duy nhất một kiểu số: the <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">double-precision 64-bit binary format IEEE 754 value</a> (có giá trị từ -(2<sup>53</sup> -1) đến 2<sup>53</sup> -1). <strong>Không có kiểu số nguyên</strong>. Ngoài việc có thể chứa giá trị dấu phẩy động, kiểu số có ba giá trị biểu tượng: <code>+Infinity</code>, <code>-Infinity</code>, and <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN"><code>NaN</code></a> (not-a-number).</p> + +<p>Để kiểm tra lớn hơn hay nhỏ hơn <code>+/-Infinity</code>, bạn có thể xem {{jsxref("Number.MAX_VALUE")}} hoặc {{jsxref("Number.MIN_VALUE")}} và bất đầu từ ECMAScript 6, bạn cũng có thể kiểm tra một số có nằm trong khoảng double-precision floating-point bằng cách dùng {{jsxref("Number.isSafeInteger()")}} cũng như {{jsxref("Number.MAX_SAFE_INTEGER")}} và {{jsxref("Number.MIN_SAFE_INTEGER")}}. Ngoài phạm vi này, một số trong Javascript không còn an toàn nữa.</p> + +<p>Có một số nguyên duy nhất có hai đại diện: 0 được đại diện bởi -0 và +0. ("0" là một bí danh của +0). Trong thực tế, điều này hầu như không có tác động. Ví dụ <code>+0 === -0</code> là <code>true</code>. Tuy nhiên, có thể nhân thấy điều này khi chia một số cho không:</p> + +<pre class="brush: js notranslate">> 42 / +0 +Infinity +> 42 / -0 +-Infinity +</pre> + +<p>Mặc dù một số thường chỉ đại diện cho giá trị của nó, JavaScript cung cấp <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators" title="en/JavaScript/Reference/Operators/Bitwise_Operators">một vài toán tử nhị phân</a>. Chúng có thể được sử dụng như một chuỗi boolean bằng cách dùng <a class="external" href="http://en.wikipedia.org/wiki/Mask_%28computing%29">bit masking</a>. Điều này thường được xem như là một cách tệ, tuy nhiên, JavaScript không cung cấp bất kỳ phương tiện nào khác để trình bày một tập hợp các boolean (như một mảng các boolean hay một đối tượng với các thuộc tính boolean). Bit masking cũng có xu hướng làm mã khó đọc, hiểu, và duy trì hơn. Nó có thể cấn thiết trong một môi trường rất hạn chế, giống như khi cố gắng để đối phó với hạn chế lưu trữ lưu trữ cục bộ hoặc trong trường hợp nặng khi mỗi chút so với đếm mạng. Kỹ thuật này chỉ nên được xem xét khi nó là biện pháp cuối cùng có thể được thực hiện để tối ưu hóa kích thước.</p> + +<h3 id="Kiểu_số_BigInt">Kiểu số BigInt</h3> + +<p>Kiểu {{jsxref("BigInt")}} là một kiểu giá trị số sơ khai trong JavaScript, đại diện cho các giá trị số nguyên với độ chính xác (precision) bất kỳ. Với <code>BigInt</code>, bạn có thể lưu và tính toán trên các số nguyên lớn mà nó có thể lớn hơn cả giới hạn an toàn của kiểu <code>Number</code>.</p> + +<p>Một số <code>BigInt</code> được tạo ra bằng cách thêm <code>n</code> vào cuối giá trị literal số nguyên hoặc bằng cách sử dụng constructor.</p> + +<p>Bạn có thể lấy giá trị nguyên an toàn lớn nhất của kiểu <code>Number</code> bằng cách sử dụng constant {{jsxref("Number.MAX_SAFE_INTEGER")}}. Với sự ra đời của kiểu <code>BigInt</code>, giờ đây bạn có thể tính toán với những con số còn lớn hơn {{jsxref("Number.MAX_SAFE_INTEGER")}}.</p> + +<p>Trong ví dụ sau, khi tăng dần giá trị {{jsxref("Number.MAX_SAFE_INTEGER")}}, bạn vẫn nhận được kết qua như mong muốn với <code>BigInt</code>:</p> + +<pre class="brush: js notranslate">> const x = 2n ** 53n; +9007199254740992n +> const y = x + 1n; +9007199254740993n</pre> + +<p>Bạn có thể sử dụng các toán tử <code>+</code>, <code>*</code>, <code>-</code>, <code>**</code>, và <code>%</code> với <code>BigInt</code> như với <code>Number</code>. Một số <code>BigInt</code> không hoàn toàn bằng (===) một số <code>Number</code>, nhưng có thể bằng khi ép kiểu (==).</p> + +<p>Số <code>BigInt</code> hành xử giống với <code>Number</code> khi được chuyển đổi kiểu về <code>Boolean</code>: <code>if</code>, <code>||</code>, <code>&&</code>, <code>Boolean</code>, <code>!</code>.</p> + +<p>Số <code>BigInt</code> không thể dùng chung với số <code>Number</code> để tính toán. Khi đó, lỗi {{jsxref("TypeError")}} sẽ xảy ra.</p> + +<h3 id="Kiểu_chuỗi">Kiểu chuỗi</h3> + +<p>Kiểu {{jsxref("Global_Objects/String", "chuỗi")}} được dùng để biểu diễn dữ liệu dạng văn bản. Nó là một dãy "các phần tử" số nguyên 16-bit. Mỗi phần tử có một vị trí trong chuỗi. Phần tử đầu tiên có chỉ số 0, tiếp theo là 1, ... . Độ dài của chuỗi là số phần tử của nó.</p> + +<p>Không giống với những ngôn ngữ như C, Chuỗi trong Javascript là bất biến. Nghĩa là một khi chuỗi được tạo thì không thể chỉnh sửa. Tuy nhiên, vẫn có thể tạo một chuỗi mới dựa vào các thao tác trên chuỗi cũ. Ví dụ:</p> + +<ul> + <li>Tạo một chuỗi con của chuỗi ban đầu bằng cách ghép từng ký tự hoặc dùng {{jsxref("String.substr()")}}.</li> + <li>Nối hai chuỗi bằng toán tử (<code>+</code>) hoặc hàm {{jsxref("String.concat()")}}.</li> +</ul> + +<h4 id="Cẩn_thận_với_việc_lưu_mọi_thứ_bằng_chuỗi_trong_code_của_bạn!">Cẩn thận với việc "lưu mọi thứ bằng chuỗi" trong code của bạn!</h4> + +<p>Chuỗi có thể được dùng để biểu diễn dữ liệu với cấu trúc phức tạp. Điều này mang tới một vài lợi ích ngắn hạn:</p> + +<ul> + <li>Rất dễ để xây dựng một chuỗi bằng phép nối.</li> + <li>Dễ debug (những gì bạn thấy khi in luôn là tất cả những thứ có trong chuỗi).</li> + <li>Chuỗi là mẫu số chung của rất nhiều API (<a href="/en-US/docs/Web/API/HTMLInputElement" title="HTMLInputElement">nhập</a>, <a href="/en-US/docs/Storage" title="Storage">local storage</a> values, {{ domxref("XMLHttpRequest") }} phản hồi khi dùng <code>responseText</code>, ...) và điều này có thể khiến việc chỉ làm việc với chuỗi được yêu thích.</li> +</ul> + +<p>Chuỗi có thể biểu diễn bất kì kiểu dữ liệu nào. Những đây không được xem là một ý hay. Ví dụ, đối với một separator, có thể bắt trước một chuỗi (trong khi một mảng sẽ thích hợp hơn). Thật không may, khi separator được dùng trong một "danh sách" các phần tử, danh sách bị hỏng. Một escape character có thể được chọn, ..... Tất cả những điều này yêu cầu một quy ước và tạo ra gánh nặng bảo trì không cần thiết.</p> + +<p>Chỉ nên dùng chuỗi để lưu trữ dữ liệu văn bản. Khi biểu diễn một cấu trúc phức tạp, phân tích chuỗi thành các cấu trúc dữ liệu với mức trừu tưỡng cao hơn.</p> + +<h3 id="Kiểu_Symbol">Kiểu Symbol</h3> + +<p>Kiểu Symbol là một kiểu mới trong Javascript tiêu chuẩn ECMAScript 6. Mỗi Symbol là một giá trị sơ khai <strong>đơn nhất</strong> và <strong>bất biến</strong> và có thể được dùng như một khóa của một Object (xem bên dưới). Trên một số ngôn ngữ lập trình, Symbol còn được gọi là "atom" (nguyên tử). Ta cũng có thể so sánh với các enumeration (enum) trong C. Xem {{Glossary("Symbol")}} và {{jsxref("Symbol")}} để biết thêm chi tiết.</p> + +<h2 id="Đối_tượng">Đối tượng</h2> + +<p>Trong khoa học máy tính, một đối tượng là một giá trị trong bộ nhớ được tham chiếu bởi một {{Glossary("Identifier", "định danh")}}.</p> + +<h3 id="Thuộc_tính">Thuộc tính</h3> + +<p>Trong Javascript, đối tượng có thể được xem là tập hợp các thuộc tính. Với <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Object_literals">object literal syntax</a>, một tập hợp hữu hạn các thuộc tính được khởi tạo; sau đó thuộc tính có thể được thêm hoặc loại bỏ. Giá trị thuộc tính thuộc bất kỳ kiểu dữ liệu, bao gồm những đối tượng khác (kể cả chính đối tượng đó), điều này cho phép xây những những cấu trúc dữ liệu phức tạp. Thuộc định được định danh bằng khóa. Một khóa phải là một chuỗi hoặc một Symbol.</p> + +<p>Có hai loại thuộc tính với các đặc điểm nhất định: Chứa dữ liệu và accessor.</p> + +<h4 id="Thuộc_tính_chứa_dữ_liệu">Thuộc tính chứa dữ liệu</h4> + +<p>Liên kết một khóa với một giá trị có các đặc điểm sau:</p> + +<p>Các đặc điểm của thuộc tính chứa dữ liệu</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Đặc điểm</th> + <th>Kiểu</th> + <th>Mô tả</th> + <th>Giá trị mặc định</th> + </tr> + <tr> + <td>[[Value]]</td> + <td>Bất kỳ</td> + <td>Giá trị của thuộc tính.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Writable]]</td> + <td>Boolean</td> + <td>Nếu là <code>false</code>, thuộc tính [[Value]] không thể thay đổi.</td> + <td>false</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td>Nếu là <code>true</code>, khóa của giá trị có thể được liệt kê bằng vòng lặp <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a>.</td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td>Nếu là <code>false</code>, thuộc tính không thể bị xóa cũng như không thể thay đổi các đặc điểm của nó.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<h4 id="Accessor">Accessor</h4> + +<p>Liên kết một khóa với một hoặc hai hàm accessor (get và/hoặc set):</p> + +<table class="standard-table"> + <caption>Attributes of an accessor property</caption> + <tbody> + <tr> + <th>Đặc điểm</th> + <th>Loại</th> + <th>Mô tả</th> + <th>Giá trị mặc định</th> + </tr> + <tr> + <td>[[Get]]</td> + <td>Hàm hoặc undefined</td> + <td>Hàm được gọi không đối số và trả về giá trị mỗi khi có truy cập tới thuộc tính. Xem <a href="/en-US/docs/Web/JavaScript/Reference/Operators/get"><code>get</code></a>.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Set]]</td> + <td>Hàm hoặc undefined</td> + <td>Hàm được gọi với một đối số mỗi khi thuộc tính được gán một giá trị. Xem <a href="/en-US/docs/Web/JavaScript/Reference/Operators/set"><code>set</code></a>.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td>Nếu là <code>true</code>, khóa của giá trị có thể được liệt kê bằng vòng lặp <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a>.</td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td>Nếu là <code>false</code>, thuộc tính không thể bị xóa cũng như không thể thay đổi các đặc điểm của nó.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<h3 id="Đối_tượng_thông_thường_và_hàm">Đối tượng "thông thường" và hàm</h3> + +<p>Mội đối tượng là một bảng các khóa và giá trị. Khóa là một chuỗi và giá trị có thể là bất kỳ thứ gì. Điều này khiến đối tượng phù hợp với <a class="external" href="https://vi.wikipedia.org/wiki/B%E1%BA%A3ng_b%C4%83m">hashmaps</a>.</p> + +<p>Hàm là một đối tượng với khả năng có thể gọi.</p> + +<h3 id="Đối_tượng_Date">Đối tượng Date</h3> + +<p>Để biểu diễn một thời điểm hay ngày tháng, Lựa chọn tốt nhất là sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a>.</p> + +<h3 id="Tập_hợp_có_thứ_tự_Mảng_và_mảng_đã_định_kiểu">Tập hợp có thứ tự: Mảng và mảng đã định kiểu</h3> + +<p><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="Array">Mảng</a> là một đối tượng có một quan hệ đặc biệt giữa các thuộc tính có khóa nguyên và thuộc tính 'length'. Thêm vào đó, mảng thừa kế các thuộc tính của <code>Array.prototype</code> cung cấp một số ít các hàm xeur lý danh sách. Ví dụ, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" title="en/JavaScript/Reference/Global_Objects/Array/indexOf">indexOf</a></code> (tìm giá trị trên một mảng) hay <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="en/JavaScript/Reference/Global_Objects/Array/push">push</a></code> (thêm một phần tử vào cuối danh sach), .... Điều này biến mảng trở thành ứng cử viên hoàn hào cho danh sách hoặc tập hợp.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Typed_arrays">Mảng đã định kiểu</a> là loại mới trong ECMAScript 6 và biểu diễn dữ liệu nhị phân như một mảng. Bảng sau đây giúp bạn so sánh với kiểu dữ liệu trong C:</p> + +<p>{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}</p> + +<h3 id="Keyed_collections_Maps_Sets_WeakMaps_WeakSets">Keyed collections: Maps, Sets, WeakMaps, WeakSets</h3> + +<p>These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.</p> + +<p>One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.</p> + +<p>Usually, to bind data to a DOM node, one could set properties directly on the object or use <code>data-*</code> attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.</p> + +<h3 id="Structured_data_JSON">Structured data: JSON</h3> + +<p>JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.</p> + +<h3 id="More_objects_in_the_standard_library">More objects in the standard library</h3> + +<p>JavaScript has a standard library of built-in objects. Please have a look at the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">reference</a> to find out about more objects.</p> + +<h2 id="Determining_types_using_the_typeof_operator">Determining types using the <code>typeof</code> operator</h2> + +<p>The <code>typeof</code> operator can help you to find the type of your variable. Please read the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">reference page</a> for more details and edge cases.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-8', 'Types')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a class="link-https" href="https://github.com/nzakas/computer-science-in-javascript/">Nicholas Zakas collection of common data structure and common algorithms in JavaScript.</a></li> + <li><a href="https://github.com/monmohan/DataStructures_In_Javascript" title="https://github.com/monmohan/DataStructures_In_Javascript">Search Tre(i)es implemented in JavaScript</a></li> +</ul> diff --git a/files/vi/web/javascript/guide/control_flow_and_error_handling/index.html b/files/vi/web/javascript/guide/control_flow_and_error_handling/index.html new file mode 100644 index 0000000000..55931e4a1f --- /dev/null +++ b/files/vi/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,405 @@ +--- +title: Control flow and error handling +slug: Web/JavaScript/Guide/Control_flow_and_error_handling +translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</div> + +<p class="summary">JavaScript hỗ trợ một tập hợp lệnh gọn nhẹ, các lệnh điều khiển luồng chuyên biệt, mà khi kết hợp lại có thể tăng tính tương tác cho ứng dụng của bạn lên đáng kể. Chương này giới thiệu sơ qua về các lệnh này.</p> + +<p>Mục <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript reference</a> chứa các chi tiết đầy đủ về các câu lệnh trong chương này. Dấu chấm phẩy (<code>;</code>) được dùng để ngăn cách giữa các lệnh trong code JavaScript.</p> + +<p>Bât cứ một biểu thức JavaScript nào cũng đều là một câu lệnh. Xem <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a> để biết thông tin đầy đủ về các biểu thức.</p> + +<h2 id="Block_statement">Block statement</h2> + +<p>Một trong những lệnh căn bản nhất là khối lệnh (block statement), được dùng để nhóm lại các câu lệnh. Khối lệnh được phân định bởi cặp dấu ngoặc nhọn:</p> + +<pre class="syntaxbox">{ + lệnh_1; + lệnh_2; + . + . + . + lệnh_n; +} +</pre> + +<h3 id="Ví_dụ"><strong>Ví dụ</strong></h3> + +<p>Khối lệnh thường được dùng với lệnh điều khiển luồng (như là <code>if</code>, <code>for</code>, <code>while</code>).</p> + +<pre class="brush: js">while (x < 10) { + x++; +} +</pre> + +<p>Ở đây, <code>{ x++; }</code> là một khối lệnh.</p> + +<p><strong>Quan trọng</strong>: Trước ECMAScript2015 (phiên bản thứ 6), JavaScript <strong>chưa có</strong> phạm vi khối (block-scope). Trong phiên bản JavaScript cũ hơn, biến được khai báo trong khối được đặt phạm vi theo hàm hoặc đoạn mã bao bọc khối đó, và ảnh hưởng của việc thiết lập chúng sẽ vượt ra khỏi phạm vi của khối. Nói cách khác, khối lệnh không định nghĩa phạm vi. Các khối độc lập ("standalone" - tức là đi kèm với lệnh điều khiển nào) trong JavaScript có thể sản sinh kết quả khác so với khối lệnh tương tự trong Java hay C. Chẳng hạn:</p> + +<pre class="brush: js">var x = 1; +{ + var x = 2; +} +console.log(x); // trả về 2 +</pre> + +<p>Đoạn mã này trả về 2 bởi vì câu lệnh <code>var x</code> bên trong khối có cùng phạm vi với câu lệnh <code>var x</code> trước khối. Trong C hoặc Java, đoạn mã này sẽ trả về 1.</p> + +<p>Kể từ ECMAScript2015, hai kiểu khai báo biến mới là <code>let</code> và <code>const</code> đều được đặt trong phạm vi khối lệnh. Tham khảo {{jsxref("Statements/let", "let")}} và {{jsxref("Statements/const", "const")}} để biết thêm chi tiết.</p> + +<h2 id="Lệnh_điều_kiện">Lệnh điều kiện</h2> + +<p>Lệnh điều kiện là tập hợp các dòng lệnh sẽ thực thi nếu một điều kiện nhất định trả về true. JavaScript hỗ trợ hai lệnh điều kiện: <code>if...else</code> và <code>switch</code>.</p> + +<h3 id="Lệnh_if...else"><code>Lệnh if...else</code></h3> + +<p>Dùng mệnh đề <code>if</code> để thực thi lệnh nếu điều kiện trả về true. Có thể dùng thêm mệnh đề <code>else</code> để thực thi lệnh nếu điều kiện trả về <code>false</code>. Lệnh <code>if</code> trông như sau:</p> + +<pre class="syntaxbox">if (điều_kiện) { + lệnh_1; +} else { + lệnh_2; +}</pre> + +<p>Ở đây, <code>điều_kiện</code> có thể là bất cứ biểu thức nào để đánh giá true hoặc false. Xem <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description">Boolean</a> để hiểu cách thức trả về <code>true</code> và <code>false</code>. Nếu <code>điều_kiện</code> trả về true, <code>lệnh_1</code> sẽ được thực thi; trái lại, <code>lệnh_2</code> sẽ được thực thi. <code>lệnh_1</code> và <code>lệnh_2</code> có thể là bất cứ câu lệnh nào, bao gồm các câu lệnh <code>if</code> lồng nhau.</p> + +<p>Bạn cũng có thể dùng lệnh <code>else if</code> để có một dãy điều kiện liên tiếp nhau, chẳng hạn như sau:</p> + +<pre class="syntaxbox">if (điều_kiện_1) { + lệnh_1; +} else if (điều_kiện_2) { + lệnh_2; +} else if (điều_kiện_n) { + lệnh_n; +} else { + lệnh_cuối; +} +</pre> + +<p>Trong trường hợp có nhiều điều kiện, chỉ thực thi các lệnh trong điều kiện đầu tiên trả về true. Để thực thi nhiều lệnh cùng lúc, hãy nhóm chúng lại trong một khối lệnh (<code>{ ... }</code>) . Nói tóm lại, ta luôn nên dùng khối lệnh, nhất là khi lồng trong câu lệnh <code>if</code>:</p> + +<pre class="syntaxbox">if (điều_kiện) { + lệnh_1_nếu_điều_kiện_là_true; + lệnh_2_nếu_điều_kiện_là_true; +} else { + lệnh_3_nếu_điều_kiện_là_false; + lệnh_4_nếu_điều_kiện_là_false; +} +</pre> + +<div>Đừng dùng lệnh gán trong biểu thức điều kiện, bởi vì lệnh gán có thể bị hiểu lầm với so sánh ngang bằng nếu xem sơ qua đoạn code. Chẳng hạn, đừng viết như sau:</div> + +<pre class="example-bad brush: js">// Dễ bị hiểu lầm là "x == y" trong khi ở bên dưới là gán giá trị y cho x +if (x = y) { + /* tập hợp các câu lệnh */ +} +</pre> + +<p>Nếu cần phải gán trong biểu thức điều kiện, hãy bọc chúng lại trong cặp dấu ngoặc tròn, chẳng hạn:</p> + +<pre class="brush: js">if ((x = y)) { + /* tập hợp các câu lệnh */ +} +</pre> + +<h4 id="Giá_trị_Falsy">Giá trị Falsy</h4> + +<p>Các giá trị sau sẽ trả về false (còn được gọi là giá trị {{Glossary("Falsy")}}):</p> + +<ul> + <li><code>false</code></li> + <li><code>undefined</code></li> + <li><code>null</code></li> + <li><code>0</code></li> + <li><code>NaN</code></li> + <li>Chuỗi rỗng (<code>""</code>)</li> +</ul> + +<p>Mọi giá trị khác, bao gồm tất cả object, trả về true khi được truyền vào câu lệnh điều kiện.</p> + +<p><strong>Chú ý:</strong> Đừng nhầm lẫn giữa giá trị Boolean sơ khai <code>true</code> và <code>false</code> với giá trị true và false của object {{jsxref("Boolean")}}. Chẳng hạn:</p> + +<pre class="brush: js">var b = new Boolean(false); +if (b) // điều kiện này trả về true +if (b == true) // điều kiện này trả về false +</pre> + +<h4 id="Ví_dụ_2"><strong>Ví dụ</strong></h4> + +<p>Trong ví dụ sau, hàm <code>checkData</code> trả về <code>true</code> nếu số lượng ký tự của object <code>Text</code> là 3; trái lại, một thông báo sẽ hiện ra và hàm sẽ trả về <code>false</code>.</p> + +<pre class="brush: js">function checkData() { + if (document.form1.threeChar.value.length == 3) { + return true; + } else { + alert('Enter exactly three characters. ' + + document.form1.threeChar.value + ' is not valid.'); + return false; + } +} +</pre> + +<h3 id="Lệnh_switch">Lệnh <code>switch</code></h3> + +<p>Lệnh <code>switch</code> cho phép một chương trình đánh giá một biểu thức và nổ lực thử nghiệm dần để tìm ra trường hợp giống nhau giữa giá trị của biểu thức đó với <code>case</code> label. Nếu một sự kết hợp được tìm thấy, chương trình sẽ chạy câu lệnh liên quan. Câu lệnh <code>switch</code> như sau:</p> + +<pre class="syntaxbox">switch (expression) { + case label_1: + statements_1 + [break;] + case label_2: + statements_2 + [break;] + ... + default: + statements_def + [break;] +} +</pre> + +<ul> + <li>Trước hết, chương trình sẽ tìm mệnh đề <code>case</code> có nhãn giống với giá trị của biểu thức và truyền dẫn việc điểu khiển tới mệnh đề đó, thực thi các lệnh liên quan.</li> + <li>Nếu không có nhãn nào khớp, chương trình sẽ tìm mệnh đề mặc định <code>default</code>, + <ul> + <li>Nếu tìm thấy mệnh đề mặc định <code>default</code>, chương trình sẽ truyền luồng điểu khiển tới mệnh đề đó, thực thi các lệnh liên quan.</li> + <li>Nếu không tìm thấy mệnh đề mặc định <code>default</code>, chương trình tiếp tục thực thi cho tới cuối lệnh <code>switch</code>. (Theo quy ước, mệnh đề <code>default</code> được viết cuối cùng, nhưng không bắt buộc).</li> + </ul> + </li> +</ul> + +<h4 id="Lệnh_break">Lệnh break</h4> + +<p>Lệnh tuỳ chọn <code>break</code> liên kết với từng mệnh đề <code>case</code> nhằm đảm bảo chương trình nhảy ra khỏi <code>switch</code> một khi câu lệnh liên quan tại vị trí mệnh đề phù hợp đã thực hiện xong, và sau đó tiếp tục thực hiện câu lệnh phía sau lệnh <code>switch</code>. Nếu không có <code>break</code>, chương trình sẽ thực thi toàn bộ câu lệnh tiếp theo còn lại trong <code>switch</code> mà không cần đánh giá xem giá trị của biểu thức và <code>case</code> label có khớp nhau không.</p> + +<h4 id="Ví_dụ_3"><strong>Ví dụ</strong></h4> + +<p>Trong ví dụ sau, nếu <code>fruittype</code> được gán giá trị "Bananas", chương trình sẽ khớp với nhãn "Bananas" và thực thi các lệnh đi kèm. Khi chương trình chạy tới <code>break</code>, chương trình ngừng và thực thi các lệnh sau khối lệnh <code>switch</code>. Nếu không có <code>break</code>, lệnh ứng với nhãn "Cherries" cũng sẽ được thực thi.</p> + +<pre class="brush: js">switch (fruittype) { + case 'Oranges': + console.log('Oranges are $0.59 a pound.'); + break; + case 'Apples': + console.log('Apples are $0.32 a pound.'); + break; + case 'Bananas': + console.log('Bananas are $0.48 a pound.'); + break; + case 'Cherries': + console.log('Cherries are $3.00 a pound.'); + break; + case 'Mangoes': + console.log('Mangoes are $0.56 a pound.'); + break; + case 'Papayas': + console.log('Mangoes and papayas are $2.79 a pound.'); + break; + default: + console.log('Sorry, we are out of ' + fruittype + '.'); +} +console.log("Is there anything else you'd like?");</pre> + +<h2 id="Lệnh_xử_lý_ngoại_lệ">Lệnh xử lý ngoại lệ</h2> + +<p>Bạn có thể quăng ngoại lệ (exeption) bằng lệnh <code>throw</code> và xử lý chúng bằng lệnh <code>try...catch</code>.</p> + +<ul> + <li><a href="#throw_statement">Lệnh <code>throw</code></a></li> + <li><a href="#try...catch_statement">Lệnh <code>try...catch</code></a></li> +</ul> + +<h3 id="Kiểu_ngoại_lệ">Kiểu ngoại lệ</h3> + +<p>Gần như mọi object đều có thể bị quăng ra trong JavaScript. Tuy vậy, không phải object nào khi quăng ra cũng được tạo ra tương tự nhau. Trong khi thông thường các số và chuỗi được quăng ra để thông báo lỗi, song sử dụng một trong số những kiểu ngoại lệ chuyên biệt cho mục đích này thường hiệu quả hơn:</p> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types">Ngoại lệ ECMAScript</a></li> + <li>{{domxref("DOMException")}} and {{domxref("DOMError")}}</li> +</ul> + +<h3 id="Lệnh_throw">Lệnh <code>throw</code></h3> + +<p>Lệnh <code>throw</code> để quăng ra ngoại lệ. Khi muốn quăng ra ngoại lệ, bạn phải đặc tả biểu thức chứa giá trị để quăng ra:</p> + +<pre class="syntaxbox">throw expression; +</pre> + +<p>Bạn có thể quăng ra biểu thức nào cũng được, không chỉ biểu thức dành riêng cho kiểu ngoại lệ. Ví dụ sau đây quăng ra vô số kiểu:</p> + +<pre class="brush: js">throw 'Error2'; // String type +throw 42; // Number type +throw true; // Boolean type +throw {toString: function() { return "I'm an object!"; } }; +</pre> + +<div class="note"><strong>Ghi chú:</strong> Bạn có thể đặc tả object khi quăng ngoại lệ. Rồi đặt tham chiếu tới thuộc tính của object đó trong khối <code>catch</code>.</div> + +<pre class="brush: js">// Tạo object có kiểu UserException +function UserException(message) { + this.message = message; + this.name = 'UserException'; +} + +// Bắt ngoại lệ in ra dòng lỗi màu mè một tí +// (như khi in lên console chả hạn) +UserException.prototype.toString = function() { + return this.name + ': "' + this.message + '"'; +} + +// Tạo một instance của object rồi quăng ra +throw new UserException('Value too high');</pre> + +<h3 id="Lệnh_try...catch">Lệnh <code>try...catch</code></h3> + +<p>Lệnh <code>try...catch</code> đánh dấu một khối để thử, và xác định khi nào sẽ quăng ra ngoại lệ. Khi ngoại lệ bị quăng ra, lệnh <code>try...catch</code> sẽ tóm gọn nó.</p> + +<p>Lệnh <code>try...catch</code> bao gồm khối <code>try</code>, chứa một hoặc nhiều câu lệnh, và khối <code>catch</code>, chứa các lệnh dành để xử lý khi có ngoại lệ bị quăng ra trong khối <code>try</code>.</p> + +<p>Tức là, bạn muốn lệnh trong khối <code>try</code> thành công, và nhỡ nó không thành công, bạn muốn truyền luồng xử lý xuống khối <code>catch</code>. Nếu bất cứ lệnh nào trong khối <code>try</code> (hoặc hàm được gọi trong khối <code>try</code>) quăng ra ngoại lệ, luồng điều khiển sẽ ngay lập tức chuyển xuống khối <code>catch</code>. Nếu không có ngoại lệ nào bị quăng ra trong khối <code>try</code>, khối <code>catch</code> sẽ bị bỏ qua. Khối <code>finally</code> thực thi sau khi khối <code>try</code> và <code>catch</code> thực thi xong nhưng trước các lệnh đặt ngay sau lệnh <code>try...catch</code>.</p> + +<p>Ví dụ sau dùng lệnh <code>try...catch</code>. Trong ví dụ này, ta gọi một hàm nhận vào một giá trị và trả về tên tháng tương ứng. Nếu giá trị truyền vào không tương ứng với số tháng (1-12), một ngoại lệ sẽ bị quăng ra có kiểu <code>"InvalidMonthNo"</code> và lệnh trong khối <code>catch</code> sẽ đặt lại giá trị cho biến <code>monthName</code> thành <code>unknown</code>.</p> + +<pre class="brush: js">function getMonthName(mo) { + mo = mo - 1; // Chỉnh lại số tháng cho hợp với chỉ số mảng (1 = Jan, 12 = Dec) + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', + 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + if (months[mo]) { + return months[mo]; + } else { + throw 'InvalidMonthNo'; // dùng từ khoá throw ở đây nhé + } +} + +try { // lệnh để thử + monthName = getMonthName(myMonth); // hàm để quăng ra ngoại lệ +} +catch (e) { + monthName = 'unknown'; + logMyErrors(e); // truyền object ngoại lệ vào hàm xử lý lỗi của bạn +} +</pre> + +<h4 id="Khối_catch">Khối <code>catch</code></h4> + +<p>Bạn có thể dùng khối <code>catch</code> để xử lý tất cả ngoại lệ sinh ra trong khối <code>try</code>.</p> + +<pre class="syntaxbox">catch (catchID) { + statements +} +</pre> + +<p>Khối <code>catch</code> nhận vào một định danh (<code>catchID</code> như trong cú pháp phía trên) giữ giá trị mà lệnh <code>throw</code> quăng ra; bạn có thể dùng định danh này để lấy thông tin về ngoại lệ bị quăng ra. JavaScript tạo ra định danh này khi chương trình chạy vào khối <code>catch</code>; định danh này chỉ tồn tại trong khối <code>catch</code>; sau khi khối <code>catch</code> thực thi xong, định danh đó sẽ không còn tồn tại nữa.</p> + +<p>Chẳng hạn, đoạn code sau quăng ra một ngoại lệ. Khi ngoại lệ xảy ra, điều khiển được truyền xuống khối <code>catch</code>.</p> + +<pre class="brush: js">try { + throw 'myException'; // sinh ngoại lệ +} +catch (e) { + // lệnh xử lý ngoại lệ + logMyErrors(e); // truyền object ngoại lệ xuống hàm xử lý lỗi +} +</pre> + +<p><strong>Thực tiễn tốt nhất: </strong>Khi log error ra console bên trong một <code>catch</code> block, hãy sử dụng <code>console.error()</code> thay vì <code>console.log()</code>, nó sẽ định dạng dòng văn bản như là một lỗi, và thêm nó vào danh sách các dòng văn bản lỗi được tạo ra bởi trang. Điều này tốt cho việc debugging.</p> + +<h4 id="Khối_finally">Khối <code>finally</code></h4> + +<p>Khối <code>finally</code> chứa các lệnh thực thi ngay sau khi thực thi khối <code>try</code> và <code>catch</code> nhưng trước các lệnh liền sau lệnh <code>try...catch</code>. Khối <code>finally</code> vẫn thực thi dù có xảy ra ngoại lệ hay không. Nếu ngoại lệ bị quăng ra, các lệnh trong khối <code>finally</code> vẫn thực thi dù khối <code>catch</code> có xử lý ngoại lệ hay không.</p> + +<p>Bạn có thể dùng khối <code>finally</code> để khiến mã của bạn lỗi một cách yên bình nhỡ ngoại lệ xảy ra; chả hạn, bạn muốn giải phóng tài nguyên khỏi đoạn mã của mình. Ví dụ sau mở một tệp tin và thực thi lệnh dùng tài nguyên của tệp đó (JavaScript phía server cho phép bạn truy cập vào tệp tin). Nếu có ngoại lệ bị quăng ra trong lúc đang mở tệp tin, khối <code>finally</code> sẽ đóng đoạn tệp tin lại trước khi đoạn mã bị lỗi.</p> + +<pre class="brush: js">openMyFile(); +try { + writeMyFile(theData); // Ghi vào tệp, có thể có lỗi +} catch(e) { + handleError(e); // Nếu có lỗi thì dùng hàm này để xử lý +} finally { + closeMyFile(); // Luôn luôn đóng tệp lại +} +</pre> + +<p>Nếu khối <code>finally</code> trả về giá trị thì giá trị đó sẽ trở thành giá trị trả về của cả dãy lệnh <code>try-catch-finally</code>, bỏ qua mọi lệnh <code>return</code> trong khối <code>try</code> và <code>catch</code>:</p> + +<pre class="brush: js">function f() { + try { + console.log(0); + throw 'bogus'; + } catch(e) { + console.log(1); + return true; // lệnh return ở đây bị tạm ngưng + // cho tới khi thực thi xong khối finally + console.log(2); // không thực thi tới + } finally { + console.log(3); + return false; // ghi đè lệnh "return" phía trên + console.log(4); // không thực thi tới + } + // "return false" sẽ thực thi ngay lúc này + console.log(5); // không thực thi tới +} +console.log(f()); // 0, 1, 3, false +</pre> + +<p>Ghi đè giá trị trả về bằng khối <code>finally</code> cũng áp dụng với các ngoại lệ bị quăng ra trong khối <code>catch</code>:</p> + +<pre class="brush: js">function f() { + try { + throw 'bogus'; + } catch(e) { + console.log('caught inner "bogus"'); + throw e; // lệnh thow này bị tạm ngưng + // cho tới khi thực thi xong khối finally + } finally { + return false; // ghi đè lệnh "throw" phía trên + } + // "return false" sẽ thực thi ngay lúc này +} + +try { + console.log(f()); +} catch(e) { + // khối này sẽ không bao giờ tới được + // bởi vì khối catch phía trên đã bị ghi đè + // bởi lệnh return trong finally + console.log('caught outer "bogus"'); +} + +// ĐẦU RA +// caught inner "bogus" +// false</pre> + +<h4 id="Lồng_lệnh_try...catch">Lồng lệnh try...catch</h4> + +<p>Bạn có thể lồng một hoặc nhiều lệnh <code>try...catch</code>. Nếu lệnh <code>try...catch</code> bên trong không có khối <code>catch</code> :</p> + +<ol> + <li>Nó nên có khối <code>finally</code> và</li> + <li>Lệnh <code>try...catch</code> bọc bên ngoài phải bắt được cái gì đấy. Để biết thêm thông tin, hãy đọc <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#Nested_try-blocks">lồng khối try</a> trên trang <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code>.</li> +</ol> + +<h3 id="Tận_dụng_object_Error">Tận dụng object <code>Error</code></h3> + +<p>Tuỳ theo kiểu của lỗi, bạn có thể dùng thuộc tính 'name' và 'message' để lấy ra thông điệp lỗi rõ ràng hơn. 'name' lấy ra class chung của Error (tức là 'DOMException' hoặc 'Error'), trong khi 'message' thường lấy ra thông điệp về lỗi súc tích hơn thông điệp tạo ra bởi ép object lỗi thành xâu ký tự.</p> + +<p>Nếu bạn muốn quăng ra ngoại lệ của riêng mình, để tận dụng được những thuộc tính này (ví dụ như khi khối catch không phân biệt giữa ngoại lệ của bạn và của hệ thống), bạn có thể dùng hàm khởi tạo Error. Chẳng hạn:</p> + +<pre class="brush: js">function doSomethingErrorProne() { + if (ourCodeMakesAMistake()) { + throw (new Error('The message')); + } else { + doSomethingToGetAJavascriptError(); + } +} +.... +try { + doSomethingErrorProne(); +} catch (e) { + console.log(e.name); // logs 'Error' + console.log(e.message); // logs 'The message' or a JavaScript error message +} +</pre> + +<div>{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</div> diff --git a/files/vi/web/javascript/guide/cu-phap-lap-trinh/index.html b/files/vi/web/javascript/guide/cu-phap-lap-trinh/index.html new file mode 100644 index 0000000000..64f63492d2 --- /dev/null +++ b/files/vi/web/javascript/guide/cu-phap-lap-trinh/index.html @@ -0,0 +1,710 @@ +--- +title: Cú pháp lập trình +slug: Web/JavaScript/Guide/cu-phap-lap-trinh +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div> + +<p class="summary">Phần này nói về các cú pháp cơ bản của ngôn ngữ JavaScript, các cách khai báo biến, các loại dữ liệu và chính tả (literal).</p> + +<h2 id="Cơ_bản">Cơ bản</h2> + +<p>Cú pháp của JavaScript (JS) phần lớn được vay mượn từ Java, nhưng JS cũng chịu ảnh hưởng từ cú pháp của các ngôn ngữ lập trình khác như Awk, Perl và Python.</p> + +<p>JavaScript là ngôn ngữ lập trình sử dụng chuẩn kí tự <strong>Unicode</strong> và khi viết cũng cần phải lưu ý phân biệt chữ HOA và chữ thường (<strong>case-sensitive). </strong>Điều này có nghĩa là các từ như Früh (trong tiếng Đức có nghĩa là "sớm" - early) có thể được sử dụng đặt tên cho biến.</p> + +<pre>let Früh = "foobar" +</pre> + +<p>In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;).</p> + +<p>Dấu chấm phẩy (;) chỉ cần thiết nếu trên cùng một dòng có từ hai câu lệnh trở lên. Trường hợp câu lệnh nằm riêng một dòng thì không cần dấu chấm phẩy.</p> + +<p><em>ECMAScript cũng có những nguyên tắc để tự động thêm dấu chấm phẩy (<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">ASI</a>) để đánh dấu kết thúc một dòng lệnh. (Để biết thêm, xem tài liệu tham khảo chi tiết tại đây: JavaScript's <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">lexical grammar</a>.)</em></p> + +<p>Thực tế thì nên luôn luôn thêm một dấu chấm phẩy vào cuối mỗi câu lệnh, thậm chí khi điều này là không bắt buộc. Việc làm này sẽ giúp tránh bớt bug.</p> + +<p>Các đoạn mã Javascript sẽ được đọc từ trái qua phải và được chuyển thể thành một chuỗi các input elements bao gồm: <em>tokens, control characters, line terminators, comments</em> hoặc {{glossary("whitespace")}}. (Spaces, tabs, và các ký tự đánh dấu dòng mới được xem là whitespace.)</p> + +<h2 id="Comments">Comments</h2> + +<p>Cú pháp của<strong> comments</strong> thì ... giống với C++ và một số ngôn ngữ lập trình khác:</p> + +<pre class="brush: js">// a one line comment <-- đây là cách comment trên 1 dòng + +/* this is a longer, cho những dòng dài hoặc nhiều dòng + multi-line comment. hãy sử dụng kiểu comment này + */ + +/* You can't, however /* nest comments */ SyntaxError */ <-- Không nên lồng comment trong comment, như đoạn comment này sẽ gây ra lỗi vì "/*" được mở bên trong comment trước đó không có hiệu lực đối với từ SyntaxError nên dấu đóng comment "*/" sẽ gây ra lỗi cú pháp. </pre> + +<p>Comments hoạt động như whitespace, và sẽ bị bỏ qua trong quá trình script chạy.</p> + +<p class="brush: js"><em><strong>Note:</strong> Bạn có thể thấy loại cú pháp comment này trong một số file javascript <strong>#!/usr/bin/env node</strong>.</em></p> + +<p class="brush: js"><em>Đây là cú pháp <strong>hashbang comment</strong>, và là một comment đặc biệt sử dụng để chỉ định đường dẫn đến một Javascript interpreter cụ thể có nhiệm vụ sẽ chạy đoạn script. Xem chi tiết <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Hashbang_comments">Hashbang comments</a>.</em></p> + +<h2 id="Khai_báo_biến">Khai báo biến</h2> + +<p>Có 3 kiểu khai báo biến trong JavaScript.</p> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Khai báo một biến, và tùy ý bạn có hoặc không khởi tạo giá trị cho nó.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>Khai báo một block-scoped, hoặc biến local, chỉ có thể truy cập được trong block bao quanh nó.</dd> + <dt> + <pre>function foo() { + var x = 10; + if (true) { + let x = 20; // x ở đây được khai báo lại nhưng khi ra khỏi block-scoped nó sẽ nhận lại giá trị bên trên là 10 + console.log(x); // in ra 20 + } + console.log(x); // in ra 10 +}</pre> + </dt> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>Khai báo một hằng block-scoped, read-only.</dd> +</dl> + +<h3 id="Biến">Biến</h3> + +<p>Bạn sử dụng biến như là tên tượng trưng cho các giá trị trong chương trình. Tên của biến được gọi là {{Glossary("Identifier", "identifier")}}, tuân theo những quy tắc nhất định.</p> + +<p>Tên biến phải bắt đầu bằng một 'chữ cái', kí tự gạch dưới (<code>_</code>), hoặc kí tự dollar (<code>$</code>). Các ký tự tiếp theo cũng có thể là các chữ số <code>0-9</code>. Vì JavaScript là case sensitive, các chữ các bao gồm các ký tự từ "<code>A</code>" đến "<code>Z</code>" (viết hoa) và "<code>a</code>" đến "<code>z</code>" (viết thường).</p> + +<p>Bạn có thể sử dụng chuẩn ISO 8859-1 hoặc các kí tự Unicode như å và ü trong tên biến, thậm chí cả các kí tự dạng <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>.</p> + +<p>Ví dụ: <code>Number_hits</code>, <code>temp99</code>, and <code>_name</code>.</p> + +<h3 id="Declaring_variables">Declaring variables</h3> + +<p>Có hai cách khai báo biến:</p> + +<ul> + <li>Sử dụng từ khóa {{jsxref("Statements/var", "var")}}. Ví dụ <code>var x = 42</code>. Cú pháp này dùng khai báo cả 2 loại biến <strong>local </strong>và <strong>global</strong>, tùy thuộc vào ngữ cảnh thực thi.</li> + <li>Sử dụng từ khóa {{jsxref("Statements/const", "const")}} hoặc {{jsxref("Statements/let", "let")}}. Ví dụ <code>let y = 13</code>. Cú pháp này dùng khai báo biến local nhưng chỉ có phạm vi trong block-scoped. (Xem <a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Guide/cu-phap-lap-trinh$edit#Variable_scope">Variable scope</a> bên dưới).</li> +</ul> + +<p>Bạn cũng có thể khai báo biến mà không dùng các từ khóa trên, ví dụ <code>x = 42</code>. Điều này sẽ tạo ra một biến <strong><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Description">undeclared global</a></strong> variable. Nó sẽ tạo nên một warning trong JavaScript. Undeclared variables có thể dẫn đến các hành vi không mong muốn. Nên khuyến cáo không nên sử dụng chúng.</p> + +<h3 id="Evaluating_variables">Evaluating variables</h3> + +<p>Một biến được khai báo với cú pháp <code>var</code> hoặc <code>let</code> mà không gán giá trị, sẽ có giá trị mặc định là {{jsxref("undefined")}}.</p> + +<p>Truong trường hợp truy cập đến một biến chưa được khai báo, thì exception {{jsxref("ReferenceError")}} sẽ được thrown:</p> + +<pre>var a; +console.log('The value of a is ' + a); // The value of a is undefined + +console.log('The value of b is ' + b); // The value of b is undefined +var b; +// This one may puzzle you until you read 'Variable hoisting' below + +console.log('The value of c is ' + c); // Uncaught ReferenceError: c is not defined + +let x; +console.log('The value of x is ' + x); // The value of x is undefined + +console.log('The value of y is ' + y); // Uncaught ReferenceError: y is not defined +let y; </pre> + +<p>Bạn có thể sử dụng <code>undefined</code> để xét xem một biến có đang mang giá trị không. Dưới đây là một ví dụ, biến <code>input</code> chưa được gán giá trị, nên biến <code>input</code> lúc này mang giá trị mặc định <code>undefined</code> vậy câu điều kiện <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else" title="en-US/docs/JavaScript/Reference/Statements/if...else">if</a></code> là <code>return true</code> và không chạy vào <code>else</code>.</p> + +<pre class="brush: js">var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +} +</pre> + +<p>Giá trị <code>undefined</code> tương đương với <code>fasle</code> khi sử dụng trong bối cảnh boolean, như ví dụ dưới đây, chương trình sẽ chạy function <code>myFunction</code> vì element <code>myArray[0]</code>là <code>undefined</code> trả về <code>false</code>.</p> + +<pre class="brush: js">var myArray = []; +if (!myArray[0]) { + myFunction(); +} + +function myFunction() { + alert('return false'); +} +</pre> + +<p>Khi biến có giá trị = <code>undefined </code>thực hiện phép toán với biến có giá trị cụ thể hoặc hằng số sẽ cho ra giá trị = <code>NaN</code> (not a number). </p> + +<pre class="brush: js">var a; +a + 2 = NaN</pre> + +<p><code>Null</code> khác với <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Undefined</span></font>. Khi biến có giá trị {{jsxref("null")}}, biến sẽ mang giá trị 0 trong các phép toán (numeric) và <code>false</code> trong các ngữ cảnh boolean. Ví dụ:</p> + +<pre class="brush: js">var n = null; +console.log(n * 32); // Will log 0 to the console +</pre> + +<h3 id="Variable_scope">Variable scope</h3> + +<p>Khi bạn khai báo một biến bên ngoài function, biến đó được gọi là <em>global </em>variable, bởi vì biến đó sẽ có hiệu lực đến bất kì đoạn code nào khác trong document hiện tại. Khi bạn khai báo một biến bên trong một function, nó gọi là <em>local </em>variable, vì nó chỉ có thể dùng được trong phạm vi function đó.</p> + +<p>Javascript trước phiên bản ECMAScript 6 không có định nghĩa <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement" title="en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement">block statement</a> scope; thay vào đó, một biến được khai báo trong một block được xem là có giá trị local đối với function (hoặc global scope) mà block đó cư trú.</p> + +<p>Ví dụ sau đây sẽ log ra <code>5</code>, vì scope của <code>x</code> là global context (hoặc function context nếu đoạn code này là một phần của function khác). Scope của <code>x</code> không bị giới hạn vào block câu lệnh <code>if</code> trực tiếp gần nhất.</p> + +<pre class="brush: js">if (true) { + var x = 5; +} +console.log(x); // 5 +</pre> + +<p>Điều này đã thay đổi khi sử dụng kiểu khai báo <code>let</code> được giới thiệu trong ECMAScript 6.</p> + +<pre class="brush: js">if (true) { + let y = 5; +} +console.log(y); // ReferenceError: y is not defined (y bị giới hạn trực tiếp trong block chứa nó) +</pre> + +<h3 id="Variable_hoisting">Variable hoisting</h3> + +<p>Một thứ không bình thường khác về các biến trong JavaScript là bạn có thể tham chiếu đến một biến tại vị trí phía trước câu lệnh khai báo. Khái niệm này gọi là <strong>hoisting</strong>; các biến trong JavaScript ở khía cạnh nào đó sẽ được "hoisted" (treo) hoặc lifted (nâng) vào vị trí trên cùng của câu lệnh hoặc hàm gần nó nhất. Tuy nhiên, các variables bị hoisted này sẽ trả về giá trị <code>undefined</code>. Nên cho dù bạn khai báo và khởi tạo sau khi bạn sử dụng hoặc tham chiếu đến biến này, thì trước đó nó vẫn trả về <code>undefined</code>.</p> + +<pre class="brush: js">/** + * Example 1 + */ +console.log(x); // undefined +var x = 3; +console.log(x); // 3 + +/** + * Example 2 + */ +// will return a value of undefined +var myvar = "my value"; + +(function() { + console.log(myvar); // undefined vì bên dưới có dòng khai báo var myvar, điều này làm biến myvar bị hoisting và nhận giá trị mới là undefined (giá trị 'my value' lúc này không còn hiệu lực vì biến đã bị hoisting) + var myvar = "local value"; +})(); +</pre> + +<p>Ví dụ bên trên có thể được biểu đạt theo cách khác như sau:</p> + +<pre class="brush: js">/** + * Example 1 + */ +var x; +console.log(x === undefined); // logs "true" +x = 3; + +/** + * Example 2 + */ +var myvar = "my value"; + +(function() { + var myvar; + console.log(myvar); // undefined + myvar = "local value"; +})(); +</pre> + +<p>Vì vấn đề hoisting này, tất cả các câu lệnh khai báo biến với <code>var</code> bên trong một function nên được đặt gần với đầu của function nhất có thể. Làm điều này giúp gia tăng độ rõ ràng của code (trường hợp dùng <code>var</code> như trong ví dụ 2 ở trên sẽ gây ra hoisting).</p> + +<h3 id="Function_hoisting">Function hoisting</h3> + +<p>Trong trường hợp của các function, chỉ các function được tạo theo kiểu function declaration là bị hoisted, còn function được tạo theo kiểu function expression thì không. Khác với variable hoisting, hoisted function không trả về giá trị mặc định <code>undefined</code>. Ví dụ:</p> + +<pre class="brush: js">/* Function declaration */ + +foo(); // "bar" + +function foo() { + console.log('bar'); +} + + +/* Function expression */ + +baz(); // TypeError: baz is not a function + +var baz = function() { + console.log('bar2'); +};</pre> + +<h3 id="Biến_toàn_cục_global_variables">Biến toàn cục (global variables)</h3> + +<p>Các global variables trên thực tế là những properties của global object. Trong các web page, global object chính là <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Window" title="The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window."><code>window</code></a>, nên bạn có thể set và truy cập đến các global variables bằng cách sử dụng cú pháp <code>window.<em>variable</em></code><em>.</em></p> + +<p>Hệ quả là, bạn có thể truy cập đến các global variables được khai báo trong một window hoặc frame từ một window hoặc frame khác, bằng cách chỉ định rõ tên của window hoặc frame. Ví dụ, nếu một biến có tên <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">phoneNumber</span></font> được khai báo trong một document, bạn có thể tham chiếu đến biến này từ một <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">iframe</span></font> như là <code>parent.phoneNumber</code>.</p> + +<h3 id="Constants">Constants</h3> + +<p>Bạn có thể tạo các hằng số read-only với từ khóa {{jsxref("Statements/const", "const")}}. Cú pháp đặt tên cho hằng cũng giống như biến, tên hằng phải bắt đầu bằng một chữ cái, hoặc dấu gạch dưới <code>_</code>, hoặc dấu dollar <code>$</code>, và có thể bao gồm mọi ký tự chữ, số, hoặc dấu gạch dưới.</p> + +<pre class="brush: js">const PI = 3.14; +</pre> + +<p>Một hằng số đã khai báo không thể thay đổi giá trị thông qua việc gán lại giá trị hoặc không thể bị khai báo lại trong khi đoạn script đang chạy. Và bắt buộc phải được gán giá trị ngay khi khởi tạo.</p> + +<p>Các nguyên tắc về scope cho các hằng số cũng giống như cách các biến block-scoped như <code>let</code> hoạt động.</p> + +<p>Bạn không thể khai báo một hằng số với tên trùng với tên function hoặc biến trong cùng một scope. Ví dụ:</p> + +<pre class="example-bad brush: js">// THIS WILL CAUSE AN ERROR +function f() {}; +const f = 5; + +// THIS WILL CAUSE AN ERROR ALSO +function f() { + const g = 5; + var g; + + //statements +} +</pre> + +<p>Tuy nhiên, khi gán một object vào một hằng, thì các thuộc tính của object đó là not protected, nên câu lệnh dưới đây sẽ được thực thi mà không lỗi.</p> + +<pre>const MY_OBJECT = {'key': 'value'}; +MY_OBJECT.key = 'otherValue';</pre> + +<p>Cũng tương tự, các nội dung trong một mảng cũng là not protected, nên câu lệnh dưới đây sẽ được thực thi mà không lỗi.</p> + +<pre>const MY_ARRAY = ['HTML','CSS']; +MY_ARRAY.push('JAVASCRIPT'); +console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT'];</pre> + +<h2 id="Cấu_trúc_dữ_liệu_và_kiểu_dữ_liệu">Cấu trúc dữ liệu và kiểu dữ liệu</h2> + +<h3 id="Kiểu_dữ_liệu">Kiểu dữ liệu</h3> + +<p>Tiêu chuẩn mới nhất của ECMAScript định nghĩa 8 kiểu dữ liệu:</p> + +<ul> + <li>Bảy kiểu dữ liệu nguyên thủy {{Glossary("Primitive", "primitives")}}: + <ol> + <li>{{Glossary("Boolean")}}. <code>true</code> và <code>false</code>.</li> + <li>{{Glossary("null")}}. Một từ khóa đạc biệt biểu thị giá trị null. Vì JavaScript là case-sensitive, <code>null</code> sẽ không giống với <code>Null</code>, <code>NULL</code>, hoặc bất kỳ biến thể khác.</li> + <li>{{Glossary("undefined")}}. Một thuộc tính top-level mà giá trị của nó là không xác định.</li> + <li>{{Glossary("Number")}}. Một số nguyên (integer) hoặc số thực dấu chấm động (floating point number) <code>42</code> or <code>3.14159</code>.</li> + <li>{{Glossary("BigInt")}}. An integer with arbitrary precision. For example: <code>9007199254740992n</code>.</li> + <li>{{Glossary("String")}}. Một chuỗi các ký tự đại diện cho một giá trị văn bản. Ví dụ: "Howdy".</li> + <li>{{Glossary("Symbol")}} (new in ECMAScript 6). Một kiểu dữ liệu mà các instance của nó là duy nhất và bất biến.</li> + </ol> + </li> + <li>Và {{Glossary("Object")}}</li> +</ul> + +<p>Mặc dù những kiểu dữ liệu này tương đối ít, chúng cho phép bạn có thể thể hiện những hàm rất hữu dụng. {{jsxref("Object", "Objects")}} và {{jsxref("Function", "functions")}} là những phần tử nền tảng khác của JavaScript. Bạn có thể xem object như là những vùng chứa được đặt tên (named container) để phục vụ cho các giá trị, và các hàm là những quy trình thủ tục để đoạn script của bạn thi hành.</p> + +<h3 id="Chuyển_đổi_kiểu_dữ_liệu">Chuyển đổi kiểu dữ liệu</h3> + +<p>JavaScript là dynamically typed language. Điều đó có nghĩa bạn không cần phải chỉ định kiểu dữ liệu của biến khi bạn khai báo biến, và kiểu dữ liệu được tự động chuyển đổi khi cần thiết trong quá trình đoạn script được thực thi.</p> + +<p>Cho nên, ví dụ, bạn có thể định nghĩa một biến như sau:</p> + +<pre class="brush: js">var answer = 42; +</pre> + +<p>Và sau đó, bạn có thể gán cùng một biến này với một giá trị chuỗi, ví dụ:</p> + +<pre class="brush: js">answer = "Thanks for all the fish..."; +</pre> + +<p>Bởi vì JavaScript là dynamically typed, việc gán giá trị này sẽ không gây ra lỗi.</p> + +<h3 id="Các_số_và_toán_tử">Các số và toán tử '+'</h3> + +<p>Trong các biểu thức (expression) có sự liên quan giữa các giá trị numeric và string với toán tử <code>+</code>, JavaScript sẽ chuyển đổi giá trị số sang chuỗi. Ví dụ:</p> + +<pre class="brush: js">x = "The answer is " + 42 // "The answer is 42" +y = 42 + " is the answer" // "42 is the answer" +</pre> + +<p>Với tất cả mọi loại toán tử khác, JavaScript sẽ không chuyển đổi giá trị numeric sang string. Ví dụ:</p> + +<pre class="brush: js">"37" - 7 // 30 +"37" + 7 // "377" +</pre> + +<h3 id="Chuyển_từ_kiểu_chuỗi_string_sang_kiểu_số_number">Chuyển từ kiểu chuỗi (string) sang kiểu số (number)</h3> + +<p>Tong trường hợp một giá trị biểu thị một số nhưng lại được lưu trong bộ nhớ như là một chuỗi, có các phương thức để chuyển đổi.</p> + +<ul> + <li id="parseInt()_and_parseFloat()">{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("parseFloat", "parseFloat()")}}</li> +</ul> + +<p><code>parseInt</code> sẽ chỉ trả về các số nguyên, nên mục đích của nó là làm giảm bớt giá trị cho các số decimals. Thêm nữa, một thực hành tốt nhất cho <code>parseInt</code> là luôn luôn thêm vào nó tham số radix. Tham số radix được dùng để chỉ định hệ số học nào sẽ được sử dụng.</p> + +<pre>parseInt('101', 2) // 5</pre> + +<p>Một phương thức khác để nhận được giá trị số từ một chuỗi là dùng toán tử <code>+</code> </p> + +<pre class="brush: js">"1.1" + "1.1" = "1.11.1" +(+"1.1") + (+"1.1") = 2.2 +// Note: the parentheses are added for clarity, not required.</pre> + +<h2 id="Literals">Literals</h2> + +<p>Literals (nguyên văn), đại diện cho các giá trị trong JavaScript. Đây là những giá trị cố định - không phải biến - mà bạn cung cấp một cách <em>litterally </em>trong script của bạn. Phần này mô tả những kiểu literals sau đây:</p> + +<ul> + <li>{{anch("Array literals")}}</li> + <li>{{anch("Boolean literals")}}</li> + <li>{{anch("Floating-point literals")}}</li> + <li>{{anch("Integers")}}</li> + <li>{{anch("Object literals")}}</li> + <li>{{anch("String literals")}}</li> +</ul> + +<h3 id="Array_literals">Array literals</h3> + +<p>Một array literal là một danh sách của không hoặc nhiều biểu thức, mỗi biểu thức trong đó đại diện cho một phần tử của mảng (array element), được bao bọc trong dấu ngoặc vuông (<code>[]</code>). Khi bạn tạo một mảng bằng cách dùng array literal, nó được khởi tạo với những giá trị cụ thể như là các element của mảng, và <code>length</code> của mảng là số lượng đối số (argument).</p> + +<p>Ví dụ sau tạo ra mảng <code>coffees</code> với 3 phần tử và một <code>length</code> của 3:</p> + +<pre class="brush: js">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<p><strong>Note: </strong>Một array literal là một kiểu của object initializer. Xem <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers" title="en-US/docs/JavaScript/Guide/Working with Objects#Using Object Initializers">Using Object Initializers</a>.</p> + +<p>Nếu một mảng được tạo ra sử dụng một literal trong một top-level script, JavaScript sẽ interpret mảng mỗi lần nó đánh giá biểu thức có chứa array literal. Ngoài ra, một literal được sử dụng trong một hàm sẽ được tạo ra mỗi lần function được gọi.</p> + +<p><strong>Note: </strong>Các array literals cũng là các <code>Array</code> objects. Xem {{jsxref("Array")}} and <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> để biết chi tiết về <code>Array</code> objects.</p> + +<h4 id="Dấu_phẩy_dư_trong_các_array_literals">Dấu phẩy dư trong các array literals</h4> + +<p>Bạn không cần phải xác định mọi phần tử trong một array literal. Nếu bạn đặt 2 dấu phẩy trên cùng một hàng, mảng sẽ tạo ra một phần tử mang giá trị <code>undefined</code>. Ví dụ sau tạo ra mảng <code>fish</code>.</p> + +<pre class="brush: js">var fish = ["Lion", , "Angel"]; +</pre> + +<p>Mảng này gồm 2 phần tử có giá trị và một phần tử rỗng (<code>fish[0]</code> là "Lion", <code>fish[1]</code> là <code>undefined</code>, và <code>fish[2]</code> là "Angel").</p> + +<p>Nếu bạn thêm một dấu phẩy theo sau (trailing comma) phần tử cuối cùng của mãng, dấu phẩy này sẽ bị bỏ qua. Trong ví dụ sau, <code>length</code> của mảng là 3. Không có <code>myList[3]</code>. Tất cả dấu phẩy khác trong danh sách ngầm chỉ định là một phần tử mới. (<strong>Note:</strong> trailing commas có thể xem là lỗi đối với các trình duyệt cũ và tốt nhất là nên xóa chúng đi).</p> + +<pre class="brush: js">let myList = ['home', , 'school', ]; +</pre> + +<p>Trong ví dụ bên dưới, <code>length</code> của mảng là 4, <code>myList[0]</code> và <code>myList[2]</code> bị thiếu.</p> + +<pre class="brush: js">var myList = [ , 'home', , 'school']; +</pre> + +<p>Trong ví dụ dưới, <code>length</code> của mảng là 4, <code>myList[1]</code> và <code>myList[3]</code> bị thiếu. <strong>Chỉ có dấu phẩy cuối cùng bị bỏ qua.</strong></p> + +<pre class="brush: js">var myList = ['home', , 'school', , ]; +</pre> + +<p>Hiểu được hành vi của cac dấu phẩy thêm này rất quan trọng để hiểu được JavaScript như là một ngôn ngữ. Tuy nhiên, khi viết code của riêng bạn, bạn nên khai báo một cách rõ ràng các phần tử bị thiếu (missing elements) là <code>undefined</code>. Làm vậy sẽ gia tăng độ rõ ràng cho code và dễ bảo trì sau này.</p> + +<h3 id="Boolean_literals">Boolean literals</h3> + +<p>Kiểu Boolean có 2 giá trị literal: <code>true</code> và<code>false</code>.</p> + +<p><strong>Cẩn thận:</strong> Đừng nhầm lẫn giá trị Boolean nguyên thủy <code>true</code> và <code>false</code> với true và fales của {{jsxref("Boolean")}} object. Boolean object là một lớp bao bên ngoài kiểu dữ liệu Boolean nguyên thủy. Xem {{jsxref("Boolean")}} để biết thêm.</p> + +<h3 id="Numeric_literals">Numeric literals</h3> + +<p>Kiểu dữ liệu {{jsxref("Number")}} và {{jsxref("BigInt")}} có thể được biểu diễn bằng hệ decimal (hệ 10), hệ hexadecimal (hệ 16), octal (hệ 8) và binary (base 2 - hệ nhị phân).</p> + +<ul> + <li>Một <em>decimal</em> numeric literal là một dãy liên tục của các chữ số mà không dẫn đầu bởi số <code>0</code> (zero).</li> + <li>Ký tự số <code>0</code> (zero) dẫn đầu trên một numeric literal, hoặc <code>0o</code> (hoặc <code>0O</code>) ám chỉ rằng nó nằm trong hệ <em>octal. Octal numerics chỉ gồm các ký tự số từ </em><code>0</code>-<code>7</code>.</li> + <li><code>0x</code> (hoặc <code>0X</code>) ám chỉ kiểu dữ liệu <em>hexadecimal </em>numeric. Hexadecimal numerics có thể gồm các ký tự số (<code>0</code>-<code>9</code>) và các chữ cái <code>a-f</code> và <code>A-F</code>. (Việc viết hoa chữ cái sẽ không làm thay đối giá trị của nó. Vì vậy <code>0xa</code> = <code>0xA</code> = <code>10</code> và <code>0xf</code> = <code>0xF</code> = <code>15</code>).</li> + <li>Một ký tự <code>0b</code> (hoặc <code>0B</code>) dẫn đầu ám chỉ hệ nhị phân <em>binary </em>numeric literal. Binary numerics chỉ có thể bao gồm ký tự <code>0</code> và <code>1</code>.</li> +</ul> + +<p>Một số ví dụ của numeric literals:</p> + +<pre class="eval">0, 117, -345, 123456789123456789n (decimal, base 10) +015, 0001 -0o77, 0o777777777777n (octal, base 8) +0x1123, 0x00111, -0xF1A7, 0x123456789ABCDEFn (hexadecimal, "hex" or base 16) +0b11, 0b0011, -0b11, 0b11101001010101010101n (binary, base 2) +</pre> + +<p>Chi tiết xem thêm tại: <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Numeric literals in the Lexical grammar reference</a>.</p> + +<h3 id="Floating-point_literals">Floating-point literals</h3> + +<p>Một floating-point literal (literal số thực dấu chấm động) có thể có các bộ phận sau:</p> + +<ul> + <li>Một số nguyên hệ 10 decimal integer (có thể thêm vào trước "<code>+</code>" hoặc "<code>-</code>"),</li> + <li>Một dấu chấm hệ 10 ("<code>.</code>"), </li> + <li>Một phần thập phân (một số hệ 10 khác),</li> + <li>Một số mũ.</li> +</ul> + +<p>Bộ phận số mũ là một ký tự "<code>e</code>" hoặc "<code>E</code>", theo sau nó là một số nguyên integer (số nguyên integer này có thể có thêm phía trước là dấu "<code>+</code>" hoặc "<code>-</code>"). Một floating-point literal phải có ít nhất một ký tự số, và hoặc là một dấu chấm hệ 10 hoặc là ký tự "<code>e</code>" (hoặc "<code>E</code>"). Tóm lại, cú pháp như sau:</p> + +<pre class="eval">[(+|-)][digits][.digits][(E|e)[(+|-)]digits] +</pre> + +<p>Ví dụ: </p> + +<pre class="eval">3.1415926 +-.123456789 +-3.1E+12 +.1e-23 +</pre> + +<h3 id="Object_literals">Object literals</h3> + +<p>Một object literal là một danh sách của không hoặc nhiều cặp property names và associated values (tên thuộc tính và giá trị được liên kết) của một một object, bao bọc bởi cặp dấu ngoặc nhọn (<code>{}</code>).</p> + +<p>Lưu ý đừng sử dụng một object literal ngay tại vị trí bắt đầu của một câu lệnh! Điều này sẽ dẫn đến một lỗi (hoặc nó sẽ thực thi theo cách bạn không mong muốn), vì dấu mở ngoặc nhọn <code>{</code> sẽ được interpreted như là bắt đầu của một block.</p> + +<p>Ví dụ dưới đây là một ví dụ của object literal. Phần tử đầu tiên của object <code>car</code> định nghĩa là một thuộc tính (property), <code>myCar</code>, và được gán giá trị kiểu chuỗi là "<code>myCar</code>", phần tử thứ 2, thuộc tính <code>getCar</code>, ngay lập tức được gán giá trị là kết quả trả về của việc gọi hàm <code>(CarTypes("Honda"));</code> phần tử thứ 3, thuộc tính <code>special</code>, sử dụng một biến đã tồn tại (<code>sales</code>).</p> + +<pre class="brush: js">var Sales = "Toyota"; + +function CarTypes(name) { + if (name == "Honda") { + return name; + } else { + return "Sorry, we don't sell " + name + "."; + } +} + +var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales }; + +console.log(car.myCar); // Saturn +console.log(car.getCar); // Honda +console.log(car.special); // Toyota +</pre> + +<p>Thêm nữa, bạn có thể sử dụng cả kiểu số hoặc chữ để đặt tên cho thuộc tính của object, hoặc bạn có thể lồng một object bên trong một object khác. Ví dụ:</p> + +<pre class="brush: js">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +console.log(car.manyCars.b); // Jeep +console.log(car[7]); // Mazda +</pre> + +<p>Các tên thuộc tính của object có thể là bất kỳ chuỗi nào, bao gồm cả chuỗi rỗng <code>''</code>. Nếu tên thuộc tính không phải là một JavaScript <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variables">identifier</a> hợp lệ, hoặc nó là số, thì nó phải được bao bọc trong các dấu nháy.</p> + +<p>Các tên thuộc tính mà không phải là các identifier hợp lệ không thể được truy cập đến như các thuộc tính thông thường là dùng dấu chấm (<code>.</code>), nhưng <em>có thể</em> được truy cập đến và set giá trị bằng cặp dấu ngoặc vuông giống mảng ("<code>[]</code>").</p> + +<pre class="brush: js">var unusualPropertyNames = { + "": "An empty string", + "!": "Bang!" +} +console.log(unusualPropertyNames.""); // SyntaxError: Unexpected string +console.log(unusualPropertyNames[""]); // An empty string +console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token ! +console.log(unusualPropertyNames["!"]); // Bang!</pre> + +<p>Please note:</p> + +<pre class="brush: js">var foo = {a: "alpha", 2: "two"}; +console.log(foo.a); // alpha +console.log(foo[2]); // two +//console.log(foo.2); // Error: missing ) after argument list +//console.log(foo[a]); // Error: a is not defined +console.log(foo["a"]); // alpha +console.log(foo["2"]); // two +</pre> + +<h4 id="Enhanced_Object_literals">Enhanced Object literals</h4> + +<p>Trong ES2015, các object literals được mở rộng từ đó hỗ trợ thêm việc cài đặt các prototype tại construction, shorthand cho việc gán biến <code>foo: foo</code>, các phương thức defining, make <code>super</code> calls, và xử lý các tên thuộc tính với các biểu thức. Cùng nhau, những thứ này cũng mang object listerals và khai báo <code>class</code> đến gần nhau hơn, và cho phép các thiết kế object-based để đạt được lợi ích từ một số tiện nghi giống nhau.</p> + +<pre>var obj = { + // __proto__ + __proto__: theProtoObj, + // Shorthand for ‘handler: handler’ + handler, + // Methods + toString() { + // Super calls + return 'd ' + super.toString(); + }, + // Computed (dynamic) property names + [ 'prop_' + (() => 42)() ]: 42 +};</pre> + +<h3 id="RegExp_literals">RegExp literals</h3> + +<p>Một regex literal (được định nghĩa chi tiết <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">sau đây</a>) là một mô hình mẫu bao bọc giữa các dấu xuyệt <code>/</code>. Ví dụ:</p> + +<pre>var re = /ab+c/;</pre> + +<h3 id="String_literals">String literals</h3> + +<p>Một string literal là không có hoặc có nhiều ký tự bao bọc trong dấu (<code>"</code>) hoặc (<code>'</code>). Một chuỗi (string) phải được giới hạn trong cặp dấu cùng loại; hoặc là cùng nháy đơn hoặc là cùng nháy kép. Ví dụ:</p> + +<ul> + <li><code>"foo"</code></li> + <li><code>'bar'</code></li> + <li><code>"1234"</code></li> + <li><code>"one line \n another line"</code></li> + <li><code>"John's cat"</code></li> +</ul> + +<p>Bạn có thể gọi các phương thức của {{jsxref("String")}} object lên một giá trị string nguyên văn (string literal) - JavaScript tự động chuyển đổi string literal sang một String object tạm, gọi phương thức để chạy, chạy xong hủy bỏ String object tạm đó. Bạn cũng có thể sử dụng thuộc tính <code>String.length</code> với một string literal:</p> + +<pre class="brush: js">console.log("John's cat".length) +// Will print the number of symbols in the string including whitespace. +// In this case, 10. +</pre> + +<p>Trong ES2015, <em>template literals</em> cũng được đưa vào sử dụng. Template literals bao bọc trong dấu back-tick (<code>`</code>) (<a href="http://en.wikipedia.org/wiki/Grave_accent" rel="noopener">dấu huyền</a>) thay vì dấu nháy đơn hay nháy kép.</p> + +<p>Các template strings cung cấp cú pháp đặc biệt (synctactic sugar) để xây dựng các chuỗi (string). (Điều này tương tự với đặc điểm nội suy chuỗi string interpolation trong Perl, Python, v.v...)</p> + +<p>Tùy trường hợp, một thẻ tag có thể được thêm vào để cho phép việc xây dựng chuỗi được tùy chỉnh, tránh injection attacks, hoặc xây dựng nên những cấu trúc dữ liệu higher-level từ các nội dung của chuỗi.</p> + +<pre>// Basic literal string creation +// `In JavaScript '\n' is a line-feed.` + +// Multiline strings +`In JavaScript, template strings can run + over multiple lines, but double and single + quoted strings cannot.` + +// String interpolation +var name = 'Bob', time = 'today'; +`Hello ${name}, how are you ${time}?` + +// Construct an HTTP request prefix used to interpret the replacements and construction +POST`http://foo.org/bar?a=${a}&b=${b} + Content-Type: application/json + X-Credentials: ${credentials} + { "foo": ${foo}, + "bar": ${bar}}`(myOnReadyStateChangeHandler); +</pre> + +<p>Bạn nên sử dụng các string literals đơn thuần nếu không cần thiết phải sử dụng đến String object. Xem {{jsxref("String")}} để biết chi tiết về <code>String</code> objects.</p> + +<h4 id="Sử_dụng_các_ký_tự_đặc_biệt_trong_chuỗi">Sử dụng các ký tự đặc biệt trong chuỗi</h4> + +<p>Ngoài các ký tự thông thường, bạn cũng có thể thêm vào các ký tự đặc biệt trong chuỗi, ví dụ:</p> + +<pre class="brush: js">"one line \n another line" +</pre> + +<p>Bảng dưới đây liệt kê danh sách các ký tự đặc biệt có thể sử dụng trong các chuỗi JavaScript.</p> + +<table class="standard-table"> + <caption>Table: JavaScript special characters</caption> + <thead> + <tr> + <th scope="col">Character</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>Null Byte</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>Backspace - Khoảng cách</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed -</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line - Dòng mới</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab - Tab một tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab - Tab dọc</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe or single quote - trích dẫn đơn</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Double quote - ngoặc kép.</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Backslash character</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See {{anch("Unicode escape sequences")}}.</td> + </tr> + </tbody> +</table> + +<h4 id="Escaping_characters">Escaping characters</h4> + +<p>Đối với các ký tự không có trong bảng trên, dấu backslash <code>\</code> được thêm vào trước sẽ bị bỏ qua, nhưng cách dùng này đã không còn nữa và nên được tránh dùng.</p> + +<p>Bạn có thể chèn vào một dấu ngoặc kép bên trong một chuỗi bằng cách đặt phía trước nó một dấu backslash <code>\</code>. Điều này tức là escaping dấu trích dẫn. Ví dụ:</p> + +<pre class="brush: js">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +console.log(quote); +</pre> + +<p>Kết quả của đoạn code trên là:</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>Để thêm một dấu backslash thật sự vào trong chuỗi, bạn phải escape dấu backslash đó. Ví dụ, để gán dường dẫn file <code>c:\temp</code> vào một chuỗi:</p> + +<pre class="brush: js">var home = "c:\\temp"; +</pre> + +<p>Bạn cũng có thể escape các line breaks bằng cách đặt vào trước chúng một dấu backslash. Backslash và line break đều sẽ được remove khỏi giá trị của chuỗi.</p> + +<pre class="brush: js">var str = "this string \ +is broken \ +across multiple\ +lines." +console.log(str); // this string is broken across multiplelines. +</pre> + +<p>Mặc dù JavaScript không có cú pháp "heredoc", bạn có thể gần đạt được điều này bằng cách thêm vào một linebreak escape và một escaped linebreak ở cuối mỗi dòng:</p> + +<pre class="brush: js">var poem = +"Roses are red,\n\ +Violets are blue.\n\ +I'm schizophrenic,\n\ +And so am I." +</pre> + +<h2 id="Thông_tin_thêm">Thông tin thêm</h2> + +<p>Chương này tập trung vào cú pháp cơ bản cho các việc khai báo và các kiểu dữ liệu. Để biết rõ hơn về cấu trúc ngôn ngữ JavaScript, xem các chương tiếp theo trong bộ hướng dẫn này:</p> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Control flow and error handling</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a></li> +</ul> + +<p>Trong chương tiếp theo, chúng ta sẽ tìm hiểu về control flow constructs và error handling.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p> diff --git a/files/vi/web/javascript/guide/details_of_the_object_model/index.html b/files/vi/web/javascript/guide/details_of_the_object_model/index.html new file mode 100644 index 0000000000..12101a6ddf --- /dev/null +++ b/files/vi/web/javascript/guide/details_of_the_object_model/index.html @@ -0,0 +1,742 @@ +--- +title: Details of the object model +slug: Web/JavaScript/Guide/Details_of_the_Object_Model +translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}</div> + +<p class="summary">JavaScript là một ngôn ngữ dựa trên đối tượng và nguyên mẫu, hơn là dựa trên class. Bởi vì điều này, làm nó kém rõ ràng về cách mà JavaScript cho phép chúng ta tạo cấu trúc cây của đối tượng cũng như tạo sự kế thừa cho thuộc tính và giá trị của chúng. Chương này cố gắng làm rõ đặc điểm này.</p> + +<p>Chương này giả định rằng bạn đã hiểu căn bản JavaScript và bạn đã sử dụng hàm của JavaScript để tạo đối tượng đơn giản.</p> + +<h2 id="Ngôn_ngữ_Class-based_vs._Ngôn_ngữ_prototype-based">Ngôn ngữ Class-based vs. Ngôn ngữ prototype-based</h2> + +<p>Ngôn ngữ dựa theo class, ví dụ Java và C++, tách biệt 2 thực thể chính: lớp (class) và thực thể (instance).</p> + +<ul> + <li>Một class định nghĩa tất cả các thuộc tính mà nó quy định tính chất của tập các object (xem phương thức và trường trong Java, hay thành viên trong C++, như là những thuộc tính). Một class là sự trù tượng hơn là một thành viên cụ thể của tập các object mà nó mô tả. Ví dụ, <code>Employee</code> class có thể biểu diễn tập hợp của tất cả employee.</li> + <li>Mặt khác một thực thể (instance) là một thực thể của một class, và là một trong những thành viên của nó. Ví dụ, <code>Victoria</code> có thể là một thực thể của <code>Employee</code> class, nó đại diện cho một cá nhân như là một employee. Một thực thể có chính xác cùng thuộc tính của class cha của nó (không hơn, không kém).</li> +</ul> + +<p>Ngôn ngữ dựa trên nguyên mẫu, như JavaScript, không tách biệt điều này, nó đơn giản chỉ là những object. Một ngôn ngữ dựa trên nguyên mẫu có ký hiệu của một <em>prototypical object</em>, một object được dùng làm mẫu mà từ mẫu đó nó tạo ra thuộc tính cho object mới. Hơn nữa, bất kỳ object nào cũng có thể được liên kết để dùng làm nguyên mẫu của một object khác, điều này cho phép object thứ hai chia sẽ thuộc tính với object thứ nhất.</p> + +<h3 id="Định_nghĩa_một_class">Định nghĩa một class</h3> + +<p>Ngôn ngữ dựa trên class, bạn định nghĩa một class bằng từ khóa định nghĩa class riêng biệt rõ ràng. Trong đó bạn có thể chỉ định phương thức đặc biệt, gọi là hàm dựng, để khởi tạo thực thể của class. Một hàm dựng có thể khởi tạo giá trị cho thuộc tính của thực thể và thực hiện những xử lý phù hợp tại thời điểm đó. Bạn có thể dùng toán tử <code>new</code> cùng với tên class để tạo thực thể của class.</p> + +<p>JavaScript cũng dùng mô hình tương tự, nhưng không có từ khóa riêng biệt để định nghĩa class (với phiên bản trước ES6). Thay vào đó, bạn có thể định nghĩa hàm dựng để tạo object với tập hợp các giá trị và thuộc tính ban đầu. Bất kỳ hàm JavaScript nào cũng có thể dùng như là constructor. Bạn có thể dùng từ toán tử <code>new</code> với hàm dựng để tạo object mới.</p> + +<h3 id="Class_con_và_sự_kế_thừa">Class con và sự kế thừa</h3> + +<p>Trong ngôn ngữ dựa trên class, bạn tạo cây thứ tự của class thông qua những định nghĩa class. Khi định nghĩa một class, bạn có thể chỉ định class đang tạo là class con của một class khác đang tồn tại. Class con kế thừa tất cả các thuộc tính của class cha và có thể thêm vào những thuộc tính mới hoặc chỉnh sửa thuộc tính được kế thừa. Ví dụ, giả sử class <code>Employee</code> chỉ có thuộc tính <code>name</code> và <code>dept</code>, và <code>Manager</code> là class con của <code>Employee</code> và định nghĩa thêm thuộc tính <code>reports</code>. Trong trường hợp này thực thể của class <code>Manager</code> sẽ có ba thuộc tính: <code>name</code>, <code>dept</code>, and <code>reports</code></p> + +<p>JavaScript cài đặt tính kế thừa bằng cách cho phép bạn liên kết một object mẫu với bất kỳ hàm dựng nào. Vì vậy, bạn có thể tạo chính xác như ví dụ <code>Employee</code> — <code>Manager</code> trên, nhưng thuật cú pháp sẽ nhưng hơi khác một tí. Trước tiên bạn định nghĩa hàm dựng <code>Employee</code>, và trong thân hàm khởi tạo thuộc tính <code>name</code> và <code>dept</code>. Tiếp theo bạn định nghĩa hàm dựng <code>Manager</code>, mà nó gọi hàm dựng <code>Employee</code> và khởi tạo thuộc tính <code>reports</code>. Cuối cúng bạn gán object mới kế thừa từ <code>Employee.prototype</code> như <code>prototype</code> cho hàm được dựng <code>Manager</code>. Sau đó, khi tạo một thực thể <code>Manager</code> mới, nó sẽ kế thừa thuộc tính <code>name</code> và <code>dept</code> của <code>Employee</code>.</p> + +<h3 id="Việc_thêm_và_xóa_những_thuộc_tính">Việc thêm và xóa những thuộc tính</h3> + +<p>Trong ngôn ngữ dựa trên class, bạn thông thường tạo một class lúc biên dịch và rồi bạn khởi tạo thực thể của class tại lúc biên dịch hoặc lúc thực thi. Bạn không thể thay đổi số lượng và kiểu của thuộc tính của class sau khi bạn định nghĩa class. Trong JavaScript, bạn có thể thêm hoặc xóa thuộc tính của bất kỳ object nào. Nếu bạn thêm một thuộc tính của một object mà được sử dụng như prototype của một tập các object, những object đó cũng sẽ có những thuộc tính mới.</p> + +<h3 id="Tóm_tắt_lại_những_khác_biệt">Tóm tắt lại những khác biệt</h3> + +<p>Sau đây là bản tóm tắt ngắn những khác biệt. Phần còn lại của chương mô tả chi tiết việc sử dụng hàm dựng của JavaScript và prototype để tạo cấu trúc cây đối tượng và so sánh với phương pháp tương tự trong Java.</p> + +<table class="standard-table"> + <caption>So sánh class-based (Java) và prototype-based (JavaScript)</caption> + <thead> + <tr> + <th scope="col">Class-based (Java)</th> + <th scope="col">Prototype-based (JavaScript)</th> + </tr> + </thead> + <tbody> + <tr> + <td>Class và thực thể của nó là hai đối tượng riêng biệt.</td> + <td>Tất cả đối tượng có thể kế thừa từ một đối tượng khác.</td> + </tr> + <tr> + <td>Dùng cú pháp riêng của class để định nghĩa class; khởi tạo thực thể của class dùng hàm dựng của class.</td> + <td>Định nghĩa và tạo một tập các đối tượng chỉ với hàm dựng.</td> + </tr> + <tr> + <td>Tạo object đơn với toán tử <code>new</code>.</td> + <td>Cùng cách như class-based.</td> + </tr> + <tr> + <td>Xây dựng cấu trúc cây object bằng cách sử dụng định nghĩa class để tạo class con của class đang tồn tại.</td> + <td>Xây dựng cấu trúc cây object bằng cách gán một object như prototype của hàm dựng.</td> + </tr> + <tr> + <td>Kế thừa thuộc tính theo cơ chế class nối tiếp.</td> + <td>Kế thừa những thuộc tính theo cơ chế prototype nối tiếp.</td> + </tr> + <tr> + <td>Khi định nghĩa class, bạn chỉ định tất cả các thuộc tính của các thực thể của class. Và không thể thêm thuộc tính mới lúc thực thi.</td> + <td>Hàm dựng và prototype chỉ định giá trị ban đầu của thuộc tính. Và có thể thêm hoặc xoá thuộc tính động trên từng đối tượng hoặc toàn bộ các object.</td> + </tr> + </tbody> +</table> + +<h2 id="Ví_dụ_Employee">Ví dụ Employee</h2> + +<p>Phần còn lại của chương này sử dụng cấu trúc cây nhân viên được trình bày như hình bên dưới.</p> + +<div style="display: table-row;"> +<div style="display: table-cell; width: 350px; text-align: center; vertical-align: middle; padding: 10px;"> +<p>Cấu trúc cây object đơn giản:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/3060/figure8.1.png"></p> +</div> + +<div style="display: table-cell; vertical-align: middle; padding: 10px;"> +<ul> + <li><code>Employee</code> có những thuộc tính <code>name</code> (mà có giá trị mặc định là một chuỗi rỗng) và <code>dept</code> (mà giá trị mặc định là chuỗi "general").</li> + <li><code>Manager</code> kế thừa từ <code>Employee</code>. Nó thêm thuộc tính <code>reports</code> (mà giá trị mặc định là một mảng rỗng sẽ dùng để lưu một mảng các <code>Employee</code> object)</li> + <li><code>WorkerBee</code> cũng kế thừa từ <code>Employee</code>. Nó thêm thuộc tính <code>projects</code> (mà có giá trị mặc định là một mảng rỗng sẽ dùng để lưu trữ một mảng các giá trị kiểu chuỗi).</li> + <li><code>SalesPerson</code> kế thừa từ <code>WorkerBee</code>. Nó thêm thuộc tính <code>quota</code> (mà có giá trị mặc định là 100). Nó cũng ghi đè giá trị của thuộc tính <code>dept</code> với giá trị "sales", để chỉ ra rằng tất cả salespersons thuộc cùng phòng ban.</li> + <li><code>Engineer</code> kế thừa <code>WorkerBee</code>. Nó thêm vào thuộc tính <code>machine</code> (mà có giá trị mặc định là chuỗi rỗng) và cũng ghi đè thuộc tính <code>dept</code> với giá trị "engineering".</li> +</ul> +</div> +</div> + +<h2 id="Tạo_hệ_thống_cấp_bậc">Tạo hệ thống cấp bậc</h2> + +<p>Có một vài cách để định nghĩa hàm dựng thích hợp để cài đặt hệ thống cấp bậc của nhân viên. Cách bạn muốn chọn để định nghĩa phụ thuộc phần lớn vào những gì bạn muốn làm trong ứng dụng của bạn.</p> + +<p>Phần này sẽ trình bày cách định nghĩa rất đơn giản để minh họa cách thực hiện sự kế thừa. Trong định nghĩa này, bạn không thể chỉ định giá trị nào cho thuộc tính khi bạn tạo một object. Một cách đơn giản một object mới được ra và nhận những thuộc tính với giá trị mặc định, sau đó bạn có thể thay đổi giá trị của những thuộc tính đó.</p> + +<p>Trong ứng dụng thực tế, bạn có thể định nghĩa hàm dựng mà cho phép bạn cung cấp những giá trị của thuộc tính tại thời điểm tạo object (xem thêm <a href="#More_flexible_constructors">More flexible constructors</a>). Bây giờ, ta chỉ dùng cách đơn giản để minh họa sự kế thừa.</p> + +<p>Việc định nghĩa <code>Employee</code> trong Java và JavaScript thì khá tương tự. Sự khác biệt chỉ là bạn cần chỉ định kiểu của mỗi thuộc tính trong Java nhưng không cần trong JavaScript (bởi vì Java là ngôn ngữ <a href="http://en.wikipedia.org/wiki/Strong_and_weak_typing">kiểu ràng buộc mạnh</a> trong khi JavaScript là ngôn ngữ kiểu rành buộc yếu.</p> + +<div class="twocolumns"> +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">function Employee() { + this.name = ''; + this.dept = 'general'; +} +</pre> + +<h4 id="Java"><br> + Java</h4> + +<pre class="brush: java">public class Employee { + public String name = ""; + public String dept = "general"; +} +</pre> +</div> + +<p>Việc định nghĩa <code>Manager</code> và <code>WorkerBee</code> chỉ ra sự khác nhau trong cách chỉ định đối tượng cấp cao hơn trong chuỗi kế thừa nối tiếp. Trong JavaScript, bạn có thể thêm nguyên mẫu (trở thành class cha) như là thuộc tính <code>prototype</code> của hàm dựng, rồi ghi đè <code>prototype.constructor</code> lên hàm dựng. Bạn có thể làm điều này bất kỳ thời điểm nào sau khi đã định nghĩa hàm dựng. Trong Java, bạn chỉ định class cha trong khi định nghĩa class. Bạn không thể thay đổi class cha sau khi định nghĩa class.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_2">JavaScript</h4> + +<pre class="brush: js">function Manager() { + Employee.call(this); + this.reports = []; +} +Manager.prototype = Object.create(Employee.prototype); +Manager.prototype.constructor = Manager; + +function WorkerBee() { + Employee.call(this); + this.projects = []; +} +WorkerBee.prototype = Object.create(Employee.prototype); +WorkerBee.prototype.constructor = WorkerBee; +</pre> + +<h4 id="Java_2"><br> + Java</h4> + +<pre class="brush: java">public class Manager extends Employee { + public Employee[] reports = + new Employee[0]; +} + + + +public class WorkerBee extends Employee { + public String[] projects = new String[0]; +} + + +</pre> +</div> + +<p> </p> + +<p>Việc định nghĩa <code>Engineer</code> và <code>SalesPerson</code> giúp tạo objects theo thứ tự giảm dần từ <code>Employee</code> rồi xuống <code>WorkerBee</code>. Một object được tạo ra từ lớp con sẽ có tất cả thuộc tính của lớp cha ở trên trong chuỗi nối tiếp đó. Hơn nữa những định nghĩa ở lớp con có thể ghi đè những giá trị kế thừa từ lớp cha.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_3">JavaScript</h4> + +<pre class="brush: js">function SalesPerson() { + WorkerBee.call(this); + this.dept = 'sales'; + this.quota = 100; +} +SalesPerson.prototype = Object.create(WorkerBee.prototype); +SalesPerson.prototype.constructor = SalesPerson; + +function Engineer() { + WorkerBee.call(this); + this.dept = 'engineering'; + this.machine = ''; +} +Engineer.prototype = Object.create(WorkerBee.prototype) +Engineer.prototype.constructor = Engineer; +</pre> + +<h4 id="Java_3"><br> + Java</h4> + +<pre class="brush: java">public class SalesPerson extends WorkerBee { + public String dept = "sales"; + public double quota = 100.0; +} + + +public class Engineer extends WorkerBee { + public String dept = "engineering"; + public String machine = ""; +} + +</pre> +</div> + +<p>Với việc sử dụng cách định nghĩa này, bạn có thể tạp hóa việc khởi tạo giá trị cho thuộc tính của thực thể với những giá trị mặc định cho các thuộc tính. Hình tiếp theo sẽ minh họa việc sử dụng cách định nghĩa trong JavaScript để tạo những object mới và hiển thị giá trị của thuộc tính của những object đó.</p> + +<div class="note"> +<p><strong>Lưu Ý:</strong> Thuật ngữ thực thể (instance) có ý nghĩa kỹ thuật cụ thể trong ngôn ngữ class-based. Trong ngôn ngữ này, một thực thể (instance) là một thực thể riêng biệt của class và là tách biệt với class. Trong JavaScript, "thực thể" không có khái niệm kỹ thuật riêng bởi vì JavaScript không tách biệt sự khác nhau giữa class và instance. Tuy nhiên, khi nói về JavaScript, "thực thể" có thể được sử dụng để ám chỉ những object được tạo ra bằng hàm dựng. Vì vậy, trong ví dụ này, bạn có thể nói <code><code>jane</code></code> là một thực thể của <code><code>Engineer</code></code>. Tương tự, mặc dù những thuật ngữ <em><em>parent</em>, <em>child</em>, <em>ancestor</em></em>, và <em><em>descendant</em></em> không có ý nghĩa chính thống trong JavaScript, bạn có thể sử dụng chúng để ám chỉ những đối tượng cấp cao hơn hoặc thấp hơn trong cây thừa kế.</p> +</div> + +<h3 id="Việc_tạo_những_đối_tượng_bằng_cách_đơn_giản">Việc tạo những đối tượng bằng cách đơn giản</h3> + +<div class="twocolumns"> +<h4 id="Cây_object">Cây object</h4> + +<p>Cây sau được tạo ra bằng những câu lệnh ở bên phải.</p> + +<p><img src="https://mdn.mozillademos.org/files/10412/=figure8.3.png"></p> + +<p> </p> + +<h4 id="Individual_objects_Jim_Sally_Mark_Fred_Jane_etc._Instances_created_from_constructor">Individual objects = Jim, Sally, Mark, Fred, Jane, etc.<br> + "Instances" created from constructor</h4> + +<pre class="brush: js">var jim = new Employee; +// Parentheses can be omitted if the +// constructor takes no arguments. +// jim.name is '' +// jim.dept is 'general' + +var sally = new Manager; +// sally.name is '' +// sally.dept is 'general' +// sally.reports is [] + +var mark = new WorkerBee; +// mark.name is '' +// mark.dept is 'general' +// mark.projects is [] + +var fred = new SalesPerson; +// fred.name is '' +// fred.dept is 'sales' +// fred.projects is [] +// fred.quota is 100 + +var jane = new Engineer; +// jane.name is '' +// jane.dept is 'engineering' +// jane.projects is [] +// jane.machine is '' +</pre> +</div> + +<h2 id="Thuộc_tính_của_Object">Thuộc tính của Object</h2> + +<p>Phần này mô tả cách mà những thuộc tính của những object có thể được kế thừa từ object khác trong chuỗi prototype và điều gì xãy ra khi bạn thêm một thuộc tính lúc thực thi.</p> + +<h3 id="Việc_kế_thừa_thuộc_tính">Việc kế thừa thuộc tính</h3> + +<p>Giả định bạn tạo <code>mark</code> object như là một <code>WorkerBee</code> với câu lệnh sau:</p> + +<pre class="brush: js">var mark = new WorkerBee; +</pre> + +<p>khi JavaScript thấy toán tử <code>new</code>, nó sẽ tạo một object mới và âm thầm đặt những giá trị của thuộc tính bên trong [[Prototype]] cho <code>WorkerBee.prototype</code> và truyền đối tượng mới tạo như là giá trị của từ khóa <em><code>this</code></em> cho hàm dựng <code>WorkerBee</code>. Thuộc tính [[Prototype]] xác định chuỗi prototype được dùng để trả về cho những giá trị của thuộc tính. Một khi những thuộc tính được thiết lập, JavaScript trả về đối tượng mới và những câu lệnh gán thiết lập giá trị thuộc tính của đối tượng <code>mark.</code></p> + +<p>Quy trình này không đặt giá trị cho những thuộc tính kế thừa từ chuỗi prototype trực tiếp vào trong đối tượng <code>mark</code>. Khi bạn lấy giá trị của một thuộc tính, JavaScript đầu tiên sẽ kiểm tra xem nếu giá trị tồn tại trực tiếp trên chính đối tượng đó. Nếu có, giá trị sẽ được trả về. Nếu không tồn tại trên chính đối tượng đó, JavaScript kiểm tra chuỗi prototype (sử dụng thuộc tính [[Prototype]]). Nếu một object trong chuỗi prototype có giá trị cho thuộc tính, giá trị sẽ được trả về. Nếu không tồn tại thuộc tính, JavaScript sẽ trả lời là không có thuộc tính. Bằng cách này, đối tượng <code>mark</code> có những thuộc tính và những giá trị sau:</p> + +<pre class="brush: js">mark.name = ''; +mark.dept = 'general'; +mark.projects = []; +</pre> + +<p>Đối tượng <code>mark</code> được gán những giá trị cục bộ cho thuộc tính <code>name</code> và <code>dept</code> bằng hàm dựng Employee. Nó được gán giá trị cục bộ cho thuộc tính <code>projects</code> bằng hàm dựng <code>WorkerBee</code>. Điều này giúp tạo ra sự kế thừa của các thuộc tính trong JavaScript. Một vài điểm tinh tế trong qui trình này được mô tả trong <a href="#Property_inheritance_revisited">Property inheritance revisited.</a></p> + +<p>Bởi vì hàm dựng không cho phép bạn chỉ định những giá trị riêng của thực thể, những thông tin này là chung. Những giá trị của thuộc tính là mặc định được chia sẻ cho tất cả các đối tượng được tạo ra từ <code>WorkerBee</code>. Tất nhiên bạn có thể thay đổi giá trị của bất kỳ thuộc tính nào. Bạn có thể làm điều đó trên <code>mark</code> object bằng những câu lệnh sau:</p> + +<pre class="brush: js">mark.name = 'Doe, Mark'; +mark.dept = 'admin'; +mark.projects = ['navigator'];</pre> + +<h3 id="Thêm_thuộc_tính">Thêm thuộc tính</h3> + +<p>Trong JavaScript, bạn có thể thêm thuộc tính cho object lúc thực thi. Bạn không bị rành buộc phải sử dụng chỉ những thuộc tính được cung cấp bởi hàm dựng. Để thêm một thuộc tính cụ thể cho một object riêng lẻ, bạn có thể gán giá trị cho thuộc tính của object đó như sau:</p> + +<pre class="brush: js">mark.bonus = 3000; +</pre> + +<p>Bây giờ object <code>mark</code> có thuộc tính <code>bonus</code>, những thực thể của <code>WorkerBee</code> không có thuộc tính này.</p> + +<p>Nếu bạn thêm thuộc tính mới vào một object mà đang được sử dụng làm prototype cho một hàm dựng, bạn đang thêm thuộc tính đó cho tất cả các object mà kế thừa từ prototype. Ví dụ, bạn có thể thêm thuộc tính <code>specialty</code> cho tất cả employees bằng câu lệnh sau:</p> + +<pre class="brush: js">Employee.prototype.specialty = 'none'; +</pre> + +<p>Ngay sau khi thực thi câu lệnh này, đối tượng <code>mark</code> cũng có thuộc tính <code>specialty</code> với giá trị <code>"none"</code>. Hình sau minh họa việc thêm thuộc tính vào prototype của <code>Employee</code> và sau đó ghi đè nó lên prototype của <code>Engineer</code>.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4422/=figure8.4.png" style="height: 519px; width: 833px;"><br> + <small><strong>Adding properties</strong></small></p> + +<h2 id="Những_hàm_dựng_linh_hoạt_hơn">Những hàm dựng linh hoạt hơn</h2> + +<p>Những hàm dựng đã được trình bày ở trên không cho phép chúng ta chỉ định giá trị cho thuộc tính khi chúng ta tạo thực thể. Với Java, bạn có thể cung cấp đối số cho hàm dựng để khởi tạo giá trị của thuộc tính cho những thực thể. Hình sau minh họa cách để thực hiện điều này.<br> + </p> + +<p><img alt="" class="internal" id="figure8.5" src="/@api/deki/files/4423/=figure8.5.png" style="height: 481px; width: 1012px;"><br> + <small><strong>Việc chỉ định thuộc tính trong hàm dựng, cách 1</strong></small></p> + +<p>Bảng minh họa sau trình bày cách định nghĩa những đối tượng này trong Java và JavaScript.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_4">JavaScript</h4> + +<h4 id="Java_4">Java</h4> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function Employee(name, dept) { + this.name = name || ''; + this.dept = dept || 'general'; +} +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Employee { + public String name; + public String dept; + public Employee () { + this("", "general"); + } + public Employee (String name) { + this(name, "general"); + } + public Employee (String name, String dept) { + this.name = name; + this.dept = dept; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function WorkerBee(projs) { + + this.projects = projs || []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class WorkerBee extends Employee { + public String[] projects; + public WorkerBee () { + this(new String[0]); + } + public WorkerBee (String[] projs) { + projects = projs; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js"> +function Engineer(mach) { + this.dept = 'engineering'; + this.machine = mach || ''; +} +Engineer.prototype = new WorkerBee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Engineer extends WorkerBee { + public String machine; + public Engineer () { + dept = "engineering"; + machine = ""; + } + public Engineer (String mach) { + dept = "engineering"; + machine = mach; + } +} +</pre> +</div> + +<p>Những định nghĩa này trong JavaScript sử dụng cú pháp đặc biệt để thiết lập giá trị mặc định:</p> + +<pre class="brush: js">this.name = name || ''; +</pre> + +<p>Trong JavaScript toán tử luận lý OR (<code>||</code>) ước lượng giá trị đầu tiên của đối số. Nếu đối số được chuyển đổi thành true, toán tử trả về giá trị của đối số đó. Ngược lại toán tử trả về đối số thứ hai. Vì vậy, đoạn mã trên kiểm tra xem nếu <code>name</code> có giá trị cho thuộc tính <code>name</code>. Nếu có, nó thiết lập giá trị đó cho <code>this.name</code>. Ngược lại, nó đặt giá trị chuỗi rỗng vào <code>this.name</code>. Chương này sử dụng cú pháp vắn tắt, tuy nhiên nó có thể làm chúng ta khó hiểu lúc ban đầu.</p> + +<div class="note"> +<p><strong>Lưu Ý:</strong> Cách này có thể không hoạt động như mong đợi nếu hàm dựng được gọi với đối số mà được chuyển đổi thành false (ví dụ như 0 (zero) và chuỗi rỗng (<code><code>""</code></code>). trong trường hợp này giá trị mặc định sẽ được chọn)</p> +</div> + +<p>Với những định nghĩa này, khi bạn tạo một thực thể của một object, bạn có thể chỉ định giá trị cho những thuộc tính được định nghĩa cục bộ. Bạn có thể sử dụng những câu lệnh sau để tạo một <code>Engineer</code>:</p> + +<pre class="brush: js">var jane = new Engineer('belau'); +</pre> + +<p>Thuộc tính của <code>Jane</code> bây giờ là:</p> + +<pre class="brush: js">jane.name == ''; +jane.dept == 'engineering'; +jane.projects == []; +jane.machine == 'belau'; +</pre> + +<p>Lưu ý là với những định nghĩa này, bạn không thể chỉ định giá trị khởi tạo cho một thuộc tính được kế thừa như thuộc tính <code>name</code>. Nếu bạn muốn chỉ định một giá trị khởi tạo cho thuộc tính được kế thừa trong JavaScript, bạn cần để thêm câu lệnh cho hàm khởi tạo.</p> + +<p>Hàm tạo đã tạo một đối tượng chung và rồi sau đó những giá trị được khởi tạo cho những thuộc tính cục bộ trực tiếp của đối tượng mới. Bạn có thể khởi tạo thêm những thuộc tính bằng cách trực tiếp gọi những hàm dựng khác của chuỗi prototype. Hình sau sẽ minh họa điều đó.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4430/=figure8.6.png" style="height: 534px; width: 1063px;"><br> + <small><strong>Những giá trị đang được chỉ định trong hàm dựng, hình 2</strong></small></p> + +<p>Hãy xem xét một trong những định nghĩa một cách chi tiết. Đây là định nghĩa mới cho hàm dựng <code>Engineer</code>:</p> + +<pre class="brush: js">function Engineer(name, projs, mach) { + this.base = WorkerBee; + this.base(name, 'engineering', projs); + this.machine = mach || ''; +} +</pre> + +<p>Giả định rằng bạn tạo một đối tượng <code>Engineer</code> mới như sau:</p> + +<pre class="brush: js">var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau'); +</pre> + +<p>JavaScript thực thi theo những bước sau:</p> + +<ol> + <li>Toán tử <code>new</code> tạo một object và thiết lập giá trị <code>__proto__</code> của object mới tạo với giá trị là <code>Engineer.prototype</code>.</li> + <li>Toán tử mới sẽ truyền object mới cho hàm dựng <code>Engineer</code> như là giá trị của từ khóa <code>this</code>.</li> + <li>Hàm dựng tạo một thuộc tính mới được gọi là <code>base</code> cho đối tượng đó và gán giá trị của hàm dựng <code>WorkerBee</code> cho thuộc tính <code>base</code>. Điều này làm hàm dựng trở thành một phương thức của đối tượng <code>Engineer</code>. Tên của thuộc tính <code>base</code> thì không có gì đặc biệt. Bạn có thể dùng bất kỳ tên hợp lệ nào như là classBase, _base,... <code>base</code> đơn giản chỉ là một con trỏ đến hàm.</li> + <li>Hàm dựng gọi phương thức <code>base</code>, truyền vào hàm dựng như những đối số (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code> và <code>"engineering"</code>). Việc sử dụng tường minh <code>"engineering"</code> trong hàm dựng mà tất cả đối tượng <code>Engineer</code> có cùng giá trị cho thuộc tính được kế thừa <code>dept</code>, và giá trị ghi đè giá trị mà được kế thừa từ <code>Employee</code>.</li> + <li>Bởi vì <code>base</code> là phương thức của <code>Engineer</code>, JavaScript gắn từ khóa <code>this</code> với object được tạo ra ở bước 1. Vì thế hàm <code>WorkerBee</code> truyền các giá trị <code>"Doe, Jane"</code> và <code>"engineering"</code> cho hàm dựng <code>Employee</code>. Dựa trên giá trị trả về của hàm dựng <code>Employee</code>, hàm <code>WorkerBee</code> sử dụng những đối số còn lại để thiết lập giá trị cho thuộc tính <code>projects</code>.</li> + <li>Dựa trên giá trị trả về của phương thức <code>base</code>, hàm dựng <code>Engineer</code> khởi tạo thuộc tính <code>machine</code> của đối tượng với giá trị <code>"belau"</code>.</li> + <li>Dựa trên giá trị trả về của hàm dựng, JavaScript gán đối tượng cho biến <code>jane</code>.</li> +</ol> + +<p>Bạn có thể nghĩ rằng, việc phải gọi hàm dựng <code>WorkerBee</code> bên trong hàm dựng <code>Engineer</code>, để đảm bảo việc cài đặt sự kế thừa cho tất cả đối tượng <code>Engineer</code>. Điều này không quá quan trọng. Việc gọi hàm dựng <code>WorkerBee</code> để đảm bảo tất cả đối tượng <code>Engineer</code> được tạo ra với các thuộc tính được chỉ định trong tất cả các hàm dựng được gọi. Tuy nhiên nếu bạn thêm thuộc tính vào prototype của <code>Employee</code> hoặc <code>WorkerBee</code>, những thuộc tính đó không được kế thừa bởi đối tượng <code>Engineer</code>. Ví dụ, giả sử bạn có đoạn mã sau:</p> + +<pre class="brush: js">function Engineer(name, projs, mach) { + this.base = WorkerBee; + this.base(name, 'engineering', projs); + this.machine = mach || ''; +} +var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau'); +Employee.prototype.specialty = 'none'; +</pre> + +<p>Đối tượng <code>jane</code> không kế thừa thuộc tính <code>specialty</code>. Bạn vẫn cần cài đặt tường minh prototype để đảm bảo sự kế thừa động. Giả sử bạn có đoạn mã sau:</p> + +<pre class="brush: js">function Engineer(name, projs, mach) { + this.base = WorkerBee; + this.base(name, 'engineering', projs); + this.machine = mach || ''; +} +Engineer.prototype = new WorkerBee; +var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau'); +Employee.prototype.specialty = 'none'; +</pre> + +<p>Bây giờ thuộc tính <code>specialty</code> của đối tượng <code>jane</code> là "none".</p> + +<p>Một cách khác để kế thừa là dùng hàm phương thức <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global Objects/Function/call">call()</a></code> / <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global Objects/Function/apply"><code>apply()</code></a>. Hai đoạn mã sau là tương đương:</p> + +<div class="twocolumns"> +<pre class="brush: js">function Engineer(name, projs, mach) { + this.base = WorkerBee; + this.base(name, 'engineering', projs); + this.machine = mach || ''; +} +</pre> + +<pre class="brush: js">function Engineer(name, projs, mach) { + WorkerBee.call(this, name, 'engineering', projs); + this.machine = mach || ''; +} +</pre> +</div> + +<p>Việc sử dụng phương thức <code>call()</code> làm cho code rõ ràng hơn và <code>base</code> không còn cần thiết nữa.</p> + +<h2 id="Xem_lại_sự_kế_thừa_thuộc_tính">Xem lại sự kế thừa thuộc tính</h2> + +<p>Đoạn trên đã mô tả cách hàm dựng và prototype trong JavaScript cung cấp cơ chế kế thừa và cây kế thừa. Trong phần này, chúng ta sẽ nói về điểm tinh tế mà thật sự chưa phù hợp để mô tả ở những phần trước.</p> + +<h3 id="Dùng_Giá_Trị_Cục_Bộ_hay_là_Giá_Trị_Được_Kế_Thừa">Dùng Giá Trị Cục Bộ hay là Giá Trị Được Kế Thừa</h3> + +<p>Khi bạn truy xuất thuộc tính của object, JavaScript thực hiện những bước sau:</p> + +<ol> + <li>Kiểm tra nếu tồn tại thuộc tính trực tiếp, nó trả về giá trị của thuộc tính đó.</li> + <li>Nếu không có thuộc tính trực tiếp, kiểm tra trong chuỗi prototype (sử dụng thuộc tính <code>__proto__</code>).</li> + <li>Nếu một object trong chuỗi prototype chứa giá trị cho một thuộc tính đang tìm thì trả về giá trị của thuộc tính đó.</li> + <li>Nếu không tồn tại thuộc tính như vậy, thì object đó không có thuộc tính đang truy xuất.</li> +</ol> + +<p>Kết quả nhận được của những bước trên phụ thuộc vào cách bạn định nghĩa đối tượng. Ví dụ sau minh họa những cách định nghĩa đối tượng:</p> + +<pre class="brush: js">function Employee() { + this.name = ''; + this.dept = 'general'; +} + +function WorkerBee() { + this.projects = []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p>Với cách định nghĩa này, giả định rằng bạn tạo đối tượng <code>amy</code> là thực thể của <code>WorkerBee</code> với đoạn lệnh sau:</p> + +<pre class="brush: js">var amy = new WorkerBee; +</pre> + +<p>Đối tượng <code>amy</code> có một biến cục bộ (riêng) là <code>projects</code>. Các thuộc tính <code>name</code> và <code>dept</code> thì không là thuộc tính riêng của <code>amy</code> mà được lấy ra từ thuộc tính <code>__proto__</code>. Vì vậy, đối tượng <code>amy</code> có những thuộc tính với những giá trị sau:</p> + +<pre class="brush: js">amy.name == ''; +amy.dept == 'general'; +amy.projects == []; +</pre> + +<p>Giả định rằng bạn thay đổi giá trị của thuộc tính <code>name</code> trong prototype của <code>Employee</code>:</p> + +<pre class="brush: js">Employee.prototype.name = 'Unknown'; +</pre> + +<p>Bạn mong muốn rằng giá trị mới sẽ được thiết lập cho tất cả các thực thể của <code>Employee</code>. Nhưng điều nay không xãy ra.</p> + +<p>Khi bạn tạo bất kỳ thực thể nào của đối tượng từ <code>Employee</code>, thì thực thể đó sẽ tạo thuộc tính <code>name</code> riêng trực tiếp trên chính thực thể đó (cụ thể đó là giá trị rỗng). Điều này có nghĩa là khi bạn thiết lập giá trị cho prototype của <code>WorkerBee</code> bằng một đối tượng kiểu <code>Employee</code>, thì <code>WorkerBee.prototype</code> có lưu giá trị riêng cho thuộc tính <code>name</code>. Vì vậy, khi JavaScript tìm kiếm thuộc tính <code>name</code> của đối tượng <code>amy</code> (tạo ra từ <code>WorkerBee</code>), JavaScript tìm kiếm giá riêng cho thuộc tính đó trong <code>WorkerBee.prototype</code>. Do đó nó không tìm kiếm xa hơn trong chuỗi prototype.</p> + +<p>Nếu bạn muốn thay đổi giá trị của một thuộc tính lúc thực thi và muốn giá trị mới đó áp dụng cho tất cả các thực thể được tạo ra, thì bạn không thể khởi tạo thuộc tính trong hàm dựng. Thay vào đó, ban thêm nó vào hàm vào trong thuộc tính prototype của hàm dựng. Ví dụ sau minh họa cách chúng ta đạt được mục đích này:</p> + +<pre class="brush: js">function Employee() { + this.dept = 'general'; // Note that this.name (a local variable) does not appear here +} +Employee.prototype.name = ''; // A single copy + +function WorkerBee() { + this.projects = []; +} +WorkerBee.prototype = new Employee; + +var amy = new WorkerBee; + +Employee.prototype.name = 'Unknown'; +</pre> + +<p>Trong trường hợp này thuộc tính <code>name</code> của <code>amy</code> nhận giá trị "Unknown".</p> + +<p>Tóm lại, nếu bạn muốn đặt giá trị mặc định cho thuộc tính và bạn muốn thay đổi giá trị mặc định lúc thực thi, bạn nên cài đặt thuộc tính trên prototype của hàm dựng, không phải tạo trực tiếp thuộc tính lúc thực thi hàm dựng.</p> + +<h3 id="Xác_định_mối_quan_hể_của_thực_thể">Xác định mối quan hể của thực thể</h3> + +<p>Việc tìm kiếm thuộc tính trong JavaScript sẽ được thực hiện trên chính danh sách các thuộc tính riêng trực tiếp của object trước, nếu thuộc tính không được tìm thấy, nó sẽ tìm trên object đặc biệt là <code>__proto__</code>. Việc kiểm tra sẽ được thực thi đệ qui, qui trình này được gọi là "Tìm kiếm trong chuỗi prototype".</p> + +<p>Thuộc tính đặc biệt <code>__proto__</code> được tạo ra khi một đối tượng được tạo ra. Nó chính là giá trị được gán cho thuộc tính <code>prototype</code> của hàm dựng. Ví vậy biểu thức <code>new Foo()</code> tạo ra một object với <code>__proto__ == <code class="moz-txt-verticalline">Foo.prototype</code></code>. Tiếp theo đó, những thay đổi trên thuộc tính <code class="moz-txt-verticalline">Foo.prototype</code> sẽ làm thay đổi thuộc tính cho tất cả đối tượng mà được tạo ra bởi <code>new Foo()</code>.</p> + +<p>Mỗi object đều cho thuộc tính <code>__proto__</code> và mỗi hàm đều có thuộc tính <code>prototype</code>. Vì vậy những đối tượng có mối liên hệ thông qua cơ chế 'thừa kế prototype' với những đối tượng khác. Bạn có thể kiểm tra sự thừa kế bằng cách so sánh thuộc tính <code>__proto__</code> của object với prototype của một hàm. JavaScript cung cấp một toán tử để thực hiện điều này là <code>instanceof</code>, Toán tử sẽ trả về kết quả true nếu đối tượng được kết thừa từ prototype của hàm. Như ví dụ sau:</p> + +<pre class="brush: js">var f = new Foo(); +var isTrue = (f instanceof Foo);</pre> + +<p>Để minh họa cụ thể hơn, chúng ta xem ví dụ sau. Giả định bạn đã có đoạn mã như định nghĩa trong <a href="#Inheriting_properties">Kế thừa thuộc tính</a>. Tạo một đối tượng <code>Engineer</code> như sau:</p> + +<pre class="brush: js">var chris = new Engineer('Pigman, Chris', ['jsd'], 'fiji'); +</pre> + +<p>Với đối tượng nay, những câu lệnh sau tất cả đều đúng:</p> + +<pre class="brush: js">chris.__proto__ == Engineer.prototype; +chris.__proto__.__proto__ == WorkerBee.prototype; +chris.__proto__.__proto__.__proto__ == Employee.prototype; +chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype; +chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; +</pre> + +<p>Dựa trên những điểm trên, bạn có thể viết hàm <code>instanceOf</code> như sau:</p> + +<pre class="brush: js">function instanceOf(object, constructor) { + object = object.__proto__; + while (object != null) { + if (object == constructor.prototype) + return true; + if (typeof object == 'xml') { + return constructor.prototype == XML.prototype; + } + object = object.__proto__; + } + return false; +} +</pre> + +<div class="note"><strong>Lưu Ý:</strong> Đoạn lệnh trên dùng toán tử typeof để kiểm tra object để kiểm tra đó là XML object, đây là cách khắc phục lỗi của JavaScript cho đối tượng XML.</div> + +<p>Dùng hàm instanceOf trên, biểu thức luôn đúng:</p> + +<pre class="brush: js">instanceOf(chris, Engineer) +instanceOf(chris, WorkerBee) +instanceOf(chris, Employee) +instanceOf(chris, Object) +</pre> + +<p>Nhưng biểu thức sau thì sai:</p> + +<pre class="brush: js">instanceOf(chris, SalesPerson) +</pre> + +<h3 id="Thông_tin_toàn_cục_trong_hàm_dựng">Thông tin toàn cục trong hàm dựng</h3> + +<p>Khi bạn định nghĩa hàm dựng, bạn cần cẩn thận nếu bạn thiết lập giá trị cho biến toàn cục. Giả sử bạn muốn giá trị ID duy nhất được tự động gán cho mỗi employee mới. Bạn có thể sử dụng cách định nghĩa sau cho <code>Employee</code> sau:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee(name, dept) { + this.name = name || ''; + this.dept = dept || 'general'; + this.id = idCounter++; +} +</pre> + +<p>Với định nghĩa này, khi bạn tạo một <code>Employee</code> mới, hàm dựng gán giá trị ID kế tiếp và rồi tăng biến đếm toàn cục ID lên một đơn vị. Vì vậy, những câu lệnh tiếp theo sau đây, <code>victoria.id</code> là 1 và <code>harry.id</code> là 2:</p> + +<pre class="brush: js">var victoria = new Employee('Pigbert, Victoria', 'pubs'); +var harry = new Employee('Tschopik, Harry', 'sales'); +</pre> + +<p>Thoạt nhìn mọi thứ có vẽ tốt. Tuy nhiên, <code>idCounter</code> được tăng lên mỗi lần một đối tượng <code>Employee</code> được tạo ra cho mọi trường hợp cả những trường hợp không mong muốn. Nếu bạn tạo toàn bộ cây cấp bậc <code>Employee</code> như hình trong chương này, hàm dựng <code>Employee</code> được gọi mỗi là bạn cài đặt một prototype. Giả sử bạn có đoạn lệnh sau:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee(name, dept) { + this.name = name || ''; + this.dept = dept || 'general'; + this.id = idCounter++; +} + +function Manager(name, dept, reports) {...} +Manager.prototype = new Employee; + +function WorkerBee(name, dept, projs) {...} +WorkerBee.prototype = new Employee; + +function Engineer(name, projs, mach) {...} +Engineer.prototype = new WorkerBee; + +function SalesPerson(name, projs, quota) {...} +SalesPerson.prototype = new WorkerBee; + +var mac = new Engineer('Wood, Mac'); +</pre> + +<p>Giả sử ta không quan tâm những câu lệnh bên trong hàm dựng, thuộc tính <code>base</code> và gọi hàm <code>base</code> trong chuỗi prototype. Trong trường hợp này, ngay khi đối tượng <code>mac</code> được tạo, <code>mac.id</code> là 5.</p> + +<p>Tuy theo yêu cầu của ứng dụng, nó có thể là vấn đề quan trọng hoặc không khi biến đếm được tăng lên. Nếu bạn quan tâm tính chính xác của giá trị tăng thêm của biến đếm, Một giải pháp cho vấn đề này là:</p> + +<pre class="brush: js">function Employee(name, dept) { + this.name = name || ''; + this.dept = dept || 'general'; + if (name) + this.id = idCounter++; +} +</pre> + +<p>Khi bạn tạo một thực thể của <code>Employee</code> để sử dụng như prototype, bạn không cung cấp đối số cho hàm dựng. Việc sử dụng định nghĩa của hàm dựng, khi bạn không cung cấp đối số, hàm dựng không gán giá trị cho id và không cập nhật biến đếm. Vì vậy, để một đối tượng <code>Employee</code> được gán id, bạn phải chỉ định tên cho employee. Trong ví dụ này, mac.id sẽ là 1.</p> + +<p>Một cách khác, bạn có thể tạo một bản sao của đối tượng prototype của Employee để gán cho WorkerBee:</p> + +<pre class="brush: js">WorkerBee.prototype = Object.create(Employee.prototype); +// instead of WorkerBee.prototype = new Employee +</pre> + +<h3 id="Không_hỗ_trợ_đa_kế_thừa">Không hỗ trợ đa kế thừa</h3> + +<p>Một vài ngôn ngữ hướng đối tượng cho phép đa kế thừa. Nghĩa là một object có thể kế thừa những thuộc tính và giá rị từ những đối tượng cha không liên quan.</p> + +<p>Việc kế thừa những thuộc tính xảy ra lúc thực thi bởi JavaScript trong khi tìm kiếm chuỗi prototype của object cho một giá trị. Bởi vì một object chỉ có một prototype đơn, JavaScript không thể kế thừa động từ nhiều hơn một chuỗi prototype.</p> + +<p>Trong JavaScript, bạn có thể áp dụng nhiều hàm dựng trong hàm dựng. Điều này chứng minh tính khả thi của đa kế thừa. Xem xét ví dụ sau:</p> + +<pre class="brush: js">function Hobbyist(hobby) { + this.hobby = hobby || 'scuba'; +} + +function Engineer(name, projs, mach, hobby) { + this.base1 = WorkerBee; + this.base1(name, 'engineering', projs); + this.base2 = Hobbyist; + this.base2(hobby); + this.machine = mach || ''; +} +Engineer.prototype = new WorkerBee; + +var dennis = new Engineer('Doe, Dennis', ['collabra'], 'hugo'); +</pre> + +<p>Giả sử <code>WorkerBee</code> được định nghĩa như trên. Trong trường hợp này, đối tượng <code>dennis</code> có những thuộc tính sau:</p> + +<pre class="brush: js">dennis.name == 'Doe, Dennis'; +dennis.dept == 'engineering'; +dennis.projects == ['collabra']; +dennis.machine == 'hugo'; +dennis.hobby == 'scuba'; +</pre> + +<p>Vì vậy <code>dennis</code> có thuộc tính từ hàm dựng <code>Hobbyist</code>. Tuy nhiên, giả sử sau đó bạn thêm một thuộc tính vào prototype của hàm dựng của <code>Hobbyist</code>:</p> + +<pre class="brush: js">Hobbyist.prototype.equipment = ['mask', 'fins', 'regulator', 'bcd']; +</pre> + +<p>Đối tượng <code>dennis</code> không kế thừa thuộc tính mới này.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}</div> diff --git a/files/vi/web/javascript/guide/expressions_and_operators/index.html b/files/vi/web/javascript/guide/expressions_and_operators/index.html new file mode 100644 index 0000000000..a843b8d769 --- /dev/null +++ b/files/vi/web/javascript/guide/expressions_and_operators/index.html @@ -0,0 +1,920 @@ +--- +title: Biểu thức và toán tử +slug: Web/JavaScript/Guide/Expressions_and_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> + +<p class="summary">Chương này mô tả biểu thức và toán tử của JavaScript, bao gồm toán tử gán, toán tử so sánh, arithmetic, thao tác bit, toán tử luận lý, chuỗi, toán tử ba ngôi và nhiều hơn nữa.</p> + +<p>Để xem danh sách đầy đủ và chi tiết các toán tử và biểu thức, mời truy cập vào <a href="/en-US/docs/Web/JavaScript/Reference/Operators">reference</a>.</p> + +<h2 id="Toán_tử">Toán tử</h2> + +<p>JavaScript có các loại toán tử như sau. Phần này mô tả về các toán tử và có bao gồm thông tin về thứ tự ưu tiên của chúng.</p> + +<ul> + <li><a href="#Toán_tử_gán">Toán tử gán</a></li> + <li><a href="#Toán_tử_so_sánh">Toán tử so sánh</a></li> + <li><a href="#Toán_tử_số_học">Toán tử số học</a></li> + <li><a href="#Bitwise">Toán tử thao tác bit</a></li> + <li><a href="#Logical">Toán tử luận lý</a></li> + <li><a href="#String">Toán tử chuỗi</a></li> + <li><a href="#Conditional">Toán tử điều kiện (ba ngôi)</a></li> + <li><a href="#Comma">Toán tử phẩy</a></li> + <li><a href="#Unary">Toán tử một ngôi</a></li> + <li><a href="#Relational">Toán tử quan hệ</a></li> +</ul> + +<p>JavaScript có cả toán tử <em>hai ngôi</em> và<em>một ngôi</em>, và một toán tử đặc biệt ba ngôi, toán tử quan hệ. Toán tử hai ngôi yêu cầu hai toán hạng, một toán hạng ở trước và một toán hạng ở sau toán tử:</p> + +<pre class="syntaxbox"><em>toán_hạng_1</em> <em>toán_tử</em> <em>toán_hạng_2</em> +</pre> + +<p>Chẳng hạn, <code>3+4</code> hoặc <code>x*y</code>.</p> + +<p>Toán tử một ngôi yêu cầu một toán tử, ở trước hoặc ở sau toán tử:</p> + +<pre class="syntaxbox"><em>toán_tử</em> <em>toán_hạng</em> +</pre> + +<p>hoặc</p> + +<pre class="syntaxbox"><em>toán_hạng</em> <em>toán_tử</em> +</pre> + +<p>Chẳng hạn, <code>x++</code> hoặc <code>++x</code>.</p> + +<h3 id="Toán_tử_gán"><a id="Assignment" name="Assignment">Toán tử gán</a></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Toán tử gán</a> gán giá trị cho toán hạng bên trái nó dựa theo giá trị của toán hạng bên phải nó. Toná tử gán đơn giản là toán tử bằng (<code>=</code>), gán giá trị cho toán hạng bên trái nó bằng giá trị của toán hạng bên phải nó. Vậy, <code>x = y</code> tức là gán giá trị của <code>y</code> cho <code>x</code>.</p> + +<p>Ngoài ra còn có các toán tử gán kết hợp được liệt kê trong bảng dưới:</p> + +<table class="standard-table"> + <caption>Toán tử gán kết hợp</caption> + <thead> + <tr> + <th>Tên</th> + <th>Viết tắt</th> + <th>Ý nghĩa</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Assignment">Toán tử gán</a></td> + <td><code>x = y</code></td> + <td><code>x = y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment">Cộng xong rồi gán</a></td> + <td><code>x += y</code></td> + <td><code>x = x + y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Subtraction_assignment">Trừ xong rồi gán</a></td> + <td><code>x -= y</code></td> + <td><code>x = x - y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Multiplication_assignment">Nhân xong rồi gán</a></td> + <td><code>x *= y</code></td> + <td><code>x = x * y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Division_assignment">Chia xong rồi gán</a></td> + <td><code>x /= y</code></td> + <td><code>x = x / y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Remainder_assignment">Chia lấy dư xong rồi gán</a></td> + <td><code>x %= y</code></td> + <td><code>x = x % y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Exponentiation_assignment">Luỹ thừa rồi gán</a>{{experimental_inline}}</td> + <td><code>x **= y</code></td> + <td><code>x = x ** y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Left_shift_assignment">Dịch bit trái rồi gán</a></td> + <td><code>x <<= y</code></td> + <td><code>x = x << y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Right_shift_assignment">Dịch bit phải rồi gán</a></td> + <td><code>x >>= y</code></td> + <td><code>x = x >> y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Unsigned_right_shift_assignment">Dịch phải kiểu unsigned rồi gán</a></td> + <td><code>x >>>= y</code></td> + <td><code>x = x >>> y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Bitwise_AND_assignment">AND bit rồi gán</a></td> + <td><code>x &= y</code></td> + <td><code>x = x & y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Bitwise_XOR_assignment">XOR bit rồi gán</a></td> + <td><code>x ^= y</code></td> + <td><code>x = x ^ y</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Bitwise_OR_assignment">OR bit rồi gán</a></td> + <td><code>x |= y</code></td> + <td><code>x = x | y</code></td> + </tr> + </tbody> +</table> + +<h4 id="Phân_rã">Phân rã</h4> + +<p>Với phép gán phức tạp hơn, cú pháp <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">phân rã rồi gán</a> là một biểu thức JavaScript cho phép phân tách dữ liệu từ mảng hoặc object sử dụng cú pháp sao chép cấu trúc của mảng hoặc object literal.</p> + +<pre class="brush: js">var foo = ['one', 'two', 'three']; + +// không dùng phân rã +var one = foo[0]; +var two = foo[1]; +var three = foo[2]; + +// dùng phân rã +var [one, two, three] = foo;</pre> + +<h3 id="Toán_tử_so_sánh"><a name="Comparison">Toán tử so sánh</a></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Toán tử so sánh</a> so sánh toán hạng của nó và trả về giá trị luận lý dựa theo tính đúng sai của phép so sánh. Toán hạng có thể thuộc là số, chuỗi, luận lý, hoặc object. Chuỗi được so sánh theo thứ tự từ điển, qua giá trị mã Unicode. Trong nhiều trường hợp, nếu hai toán hạng không cùng kiểu, JavaScript sẽ tự động ép kiểu sao cho phù hợp. Hành vi này thường xảy ra khi so sánh dữ liệu kiểu số. Duy có hai toán tử so sánh, bao gồm <code>===</code> và <code>!==</code>, không tự động ép kiểu mà sẽ so sánh bằng chính xác. Bảng sau mô tả các toán tử so sánh bao gồm cả code mẫu:</p> + +<pre class="brush: js">var var1 = 3; +var var2 = 4; +</pre> + +<table class="standard-table"> + <caption>Toán tử so sánh</caption> + <thead> + <tr> + <th scope="col">Toán tử</th> + <th scope="col">Mô tả</th> + <th scope="col">Ví dụ trả về true/th></th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">Bằng</a> (<code>==</code>)</td> + <td>Trả về <code>true</code> nếu các toán hạng bằng nhau.</td> + <td><code>3 == var1</code> + <p><code>"3" == var1</code></p> + <code>3 == '3'</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">Không bằng</a> (<code>!=</code>)</td> + <td>Trả về <code>true</code> nếu các toán hạng không bằng nhau.</td> + <td><code>var1 != 4<br> + var2 != "3"</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">Bằng chính xác</a> (<code>===</code>)</td> + <td>Trả về <code>true</code> nếu các toán hạng bằng nhau và cùng kiểu. Xem thêm tại {{jsxref("Object.is")}} và <a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness" title="/en-US/docs/Web/JavaScript/Guide/Sameness">sameness in JS</a>.</td> + <td><code>3 === var1</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">Không bằng chính xác</a> (<code>!==</code>)</td> + <td>Trả về <code>true</code> nếu các toán hạng không bằng nhau, hoặc khác kiểu.</td> + <td><code>var1 !== "3"<br> + 3 !== '3'</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">Lớn hơn</a> (<code>></code>)</td> + <td>Trả về <code>true</code> nếu toán hạng bên trái lớn hơn toán hạng bên phải.</td> + <td><code>var2 > var1<br> + "12" > 2</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">Lớn hơn hoặc bằng</a> (<code>>=</code>)</td> + <td>Trả về <code>true</code> nếu toán hạng bên trái lớn hơn hoặc bằng toán hạng bên phải.</td> + <td><code>var2 >= var1<br> + var1 >= 3</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">Nhỏ hơn</a> (<code><</code>)</td> + <td>Trả về <code>true</code> nếu toán hạng bên trái nhỏ hơn toán hạng bên phải.</td> + <td><code>var1 < var2<br> + "2" < 12</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_or_equal_operator">Nhỏ hơn hoặc bằng</a> (<code><=</code>)</td> + <td>Trả về <code>true</code> nếu toán hạng bên trái ?nhỏ hơn hoặc bằng toán hạng bên phải.</td> + <td><code>var1 <= var2<br> + var2 <= 5</code></td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Lưu ý: </strong>(<strong>=></strong>) không phải là toán tử, mà là cú pháp của <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Hàm mũi tên</a>.</p> +</div> + +<h3 id="Toán_tử_số_học"><a name="Arithmetic">Toán tử số học</a></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators">Toán tử số học</a> nhận giá trị kiểu số (cả literal lẫn biến) là toán hạng của nó và trả về một giá trị kiểu số. Các toán tử số học thông thường là toán tử cộng (<code>+</code>), trừ (<code>-</code>), nhân (<code>*</code>), và chia (<code>/</code>). Những toán tử này hoạt động tương tự như trong các ngôn ngữ lập trình khác khi xử lý với số thực dấu phẩy động (nói chung, ?phép chia cho 0 sẽ trả về {{jsxref("Infinity")}}). Ví dụ:</p> + +<pre class="brush: js">1 / 2; // 0.5 +1 / 2 == 1.0 / 2.0; // this is true +</pre> + +<p>Ngoài những toán tử số học thông thường (+, -, * /), JavaScript cung cấp thêm các toán tử số học được liệt kê trong bảng sau:</p> + +<table class="fullwidth-table"> + <caption>Toán tử số học</caption> + <thead> + <tr> + <th scope="col">Toán tử</th> + <th scope="col">Mô tả</th> + <th scope="col">Ví dụ</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">Chia lấy dư</a> (<code>%</code>)</td> + <td>Toán tử hai ngôi. Trả về phần nguyên trong phép chia của hai toán hạng.</td> + <td>12 % 5 trả về 2.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">Tăng</a> (<code>++</code>)</td> + <td>Toán tử một ngôi. Cộng thêm một đơn vị cho toán hạng. Nếu dùng như tiền tố (<code>++x</code>), trả về giá trị sau khi cộng thêm một; nếu dùng như hậu tố (<code>x++</code>), trả về giá trị trước khi cộng thêm một.</td> + <td>Nếu <code>x</code> bằng 3, rồi <code>++x</code> sẽ thiết lập giá trị của <code>x</code> lên 4 và trả về 4, trong khi <code>x++</code> trả về 3 và sau đó mới thiết lập giá trị của <code>x</code> lên 4.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">Giảm</a> (<code>--</code>)</td> + <td>Toán tử một ngôi. Trừ đi một đơn vị cho toán hạng. Giá trị trả về tương tự như toán tử tăng.</td> + <td>Nếu <code>x</code> bằng 3, rồi <code>--x</code> sẽ thiết lập giá trị của <code>x</code> về 2 và trả về 2, trong khi <code>x--</code> trả về 3 và sau đó mới thiết lập giá trị của <code>x</code> về 2.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">Phủ định một ngôi</a> (<code>-</code>)</td> + <td>Toán tử một ngôi. Trả về giá trị phủ định của toán hạng.</td> + <td>Nếu <code>x</code> bằng 3, thì <code>-x</code> trả về -3.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">Cộng một ngôi</a> (<code>+</code>)</td> + <td>Toán tử một ngôi. Ép kiểu toán hạng về dạng số học, nếu kiểu của toán hạng đó không phải là số.</td> + <td><code>+"3"</code> trả về <code>3</code>.<br> + <code>+true</code> trả về <code>1.</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation">Toán tử luỹ thừa</a> (<code>**</code>) {{experimental_inline}}</td> + <td>Tính toán giá trị <code>cơ số</code> theo <code>luỹ thừa</code> số mũ, tức là, <code>cơ số<sup>số mũ</sup></code></td> + <td><code>2 ** 3</code> trả về <code>8</code>.<br> + <code>10 ** -1</code> trả về <code>0.1</code>.</td> + </tr> + </tbody> +</table> + +<h3 id="Toán_tử_thao_tác_bit"><a id="Bitwise" name="Bitwise">Toán tử thao tác bit</a></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Toán tử thao tác bit</a> coi toán hạng của nó là một tập 32 bit (gồm 0 và 1), thay vì là kiểu thập phân, thập lục phân, hay bát phân. Chẳng hạn, số thập phân 9 được biểu diễn trong hệ nhị phân là 1001. Toán tử thao tác bit xử lý phép toán dựa theo dạng biểu diễn nhị phân ấy, nhưng trả về giá trị kiểu số thông thường trong JavaScript.</p> + +<p>Bảng tóm tắt các toán tử thao tác bit của JavaScript.</p> + +<table class="standard-table"> + <caption>Toán tử thao tác bit</caption> + <thead> + <tr> + <th scope="col">Toán tử</th> + <th scope="col">Cách dùng</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">Toán tử AND bit</a></td> + <td><code>a & b</code></td> + <td>trả về a one in each bit position for which the corresponding bits of both operands are ones.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">Toán tử OR bit</a></td> + <td><code>a | b</code></td> + <td>trả về a zero in each bit position for which the corresponding bits of both operands are zeros.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">Toán tử XOR bit</a></td> + <td><code>a ^ b</code></td> + <td>trả về a zero in each bit position for which the corresponding bits are the same.<br> + [trả về a one in each bit position for which the corresponding bits are different.]</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">Toán tử NOT bit</a></td> + <td><code>~ a</code></td> + <td>Inverts the bits of its operand.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Left_shift">Dịch trái</a></td> + <td><code>a << b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the left, shifting in zeros from the right.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Right_shift">Dịch phải giữ nguyên dấu</a></td> + <td><code>a >> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Unsigned_right_shift">Dịch phải với 0</a></td> + <td><code>a >>> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off, and shifting in zeros from the left.</td> + </tr> + </tbody> +</table> + +<h4 id="Bitwise_Logical_Operators" name="Bitwise_Logical_Operators">Toán tử luận lý bit</h4> + +<p>Về lý thuyết, cơ chế hoạt động của toán tử luận lý bit được giải thích như sau:</p> + +<ul> + <li>Toán hạng được chuyển đổi về dạng số nguyên 32-bit và biểu diễn bằng một dãy bit (0 và 1). Số dài hơn 32 bit sẽ bị cắt đi một số bit. Chẳng hạn, số nguyên sau đây, dài hơn 32 bit sẽ được chuyển đổi về dạng số nguyên 32 bit: + <pre>Trước: 11100110111110100000000000000110000000000001 +Sau: 10100000000000000110000000000001</pre> + </li> + <li>Mỗi bit của toán hạng thứ nhất sẽ dóng với bit tương ứng của toán hạng thứ hai.</li> + <li>Toán tử sẽ áp dụng với từng cặp bit và trả.</li> +</ul> + +<p>Chẳng hạn, biểu diễn nhị phân của 9 là 1001, và biểu diễn nhị phân của 15 là 1111. Vậy nếu áp dụng toán tử luận lý bit vào các giá trị này, thì kết quả trả về sẽ được như trong bảng sau:</p> + +<table class="standard-table"> + <caption>Ví dụ về toán tử thao tác bit</caption> + <thead> + <tr> + <th scope="col">Biểu thức</th> + <th scope="col">Kết quả</th> + <th scope="col">Mô tả nhị phân</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>15 & 9</code></td> + <td><code>9</code></td> + <td><code>1111 & 1001 = 1001</code></td> + </tr> + <tr> + <td><code>15 | 9</code></td> + <td><code>15</code></td> + <td><code>1111 | 1001 = 1111</code></td> + </tr> + <tr> + <td><code>15 ^ 9</code></td> + <td><code>6</code></td> + <td><code>1111 ^ 1001 = 0110</code></td> + </tr> + <tr> + <td><code>~15</code></td> + <td><code>-16</code></td> + <td><code>~</code><code>00000000...</code><code>00001111 = </code><code>1111</code><code>1111</code><code>...</code><code>11110000</code></td> + </tr> + <tr> + <td><code>~9</code></td> + <td><code>-10</code></td> + <td><code>~</code><code>00000000</code><code>...</code><code>0000</code><code>1001 = </code><code>1111</code><code>1111</code><code>...</code><code>1111</code><code>0110</code></td> + </tr> + </tbody> +</table> + +<p>Chú ý: tất cả 32 bit được đảo ngược bởi toán tử luận lý NOT có bit trái nhất đặt thành 1 để biểu diễn số âm (biểu diễn bù hai). <code>~x</code> thực thi ra cùng một kết quả như <code>-x - 1</code>.</p> + +<h4 id="Bitwise_Shift_Operators" name="Bitwise_Shift_Operators">Toán tử dịch bit</h4> + +<p>Toán tử dịch bit nhận hai toán hạng: toán hạng thứ nhất là số lượng bit được dịch, còn toán hạng thứ hai chỉ ra vị trí bit để bắt đầu dịch. Hướng dịch bit phụ thuộc vào toán tử được sử dụng.</p> + +<p>Toán tử dịch bit chuyển đổi toán hạng của nó thành dạng số nguyên 32-bit và trả về kết quả cùng kiểu với toán hạng bên trái.</p> + +<p>Toán tử dịch bit được liệt kê theo danh sách sau.</p> + +<table class="fullwidth-table"> + <caption>Toán tử dịch bit</caption> + <thead> + <tr> + <th scope="col">Toán tử</th> + <th scope="col">Mô tả</th> + <th scope="col">Ví dụ</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#<<_(Left_shift)">Dịch trái</a><br> + (<code><<</code>)</td> + <td>Dịch toán hạng thứ nhất theo một lượng bằng toán hạng thứ hai sang trái. Các bit dịch trái bị tràn sẽ bị loại bỏ. Các bit 0 được dịch vào từ bên phải.</td> + <td><code>9<<2</code> trả về 36, bởi vì 1001 dịch 2 bit sang trái sẽ thành 100100, tương ứng với 36.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#>>_(Sign-propagating_right_shift)">Dịch phải bit giữ nguyên dấu</a> (<code>>></code>)</td> + <td>Dịch toán hạng thứ nhất theo một lượng bằng toán hạng thứ hai sang phải. Các bit dịch phải bị tràn sẽ bị loại bỏ. Bản sao của bit trái nhất được dịch vào từ trái.</td> + <td><code>9>>2</code> trả về 2, bởi vì 1001 dịch 2 bit sang phải sẽ thành 10, tương ứng với 2. Tương tự, <code>-9>>2</code> trả về -3, bởi vì dấu vẫn được giữ nguyên.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#>>>_(Zero-fill_right_shift)">Dịch phải bit với 0</a> (<code>>>></code>)</td> + <td>Dịch toán hạng thứ nhất theo một lượng bằng toán hạng thứ hai sang phải. Các bit dịch phải bị tràn sẽ bị loại bỏ. Bit 0 được dịch vào từ trái sang.</td> + <td><code>19>>>2</code> trả về 4, bởi vì 10011 dịch 2 bit sang phải sẽ thành 100, tương ứng với 4. Với số không âm, toán tử này tương tự với dịch phải giữ nguyên dấu.</td> + </tr> + </tbody> +</table> + +<h3 id="Toán_tử_luận_lý"><a id="Logical" name="Logical">Toán tử luận lý</a></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators">Toán tử logic</a> thường được dùng với giá trị Boolean (kiểu logic); khi đó, chúng trả về giá trị Boolean. Tuy nhiên, toán tử <code>&&</code> và <code>||</code> thực tế trả về giá trị của một trong những toán hạng xác định, nên nếu hai toán tử này được dùng với giá trị không phải kiểu Boolean, chúng có thể trả về một giá trị không phải Boolean. Toán tử logic được mô tả trong bảng dưới.</p> + +<table class="fullwidth-table"> + <caption>Toán tử logic</caption> + <thead> + <tr> + <th scope="col">Toán tử</th> + <th scope="col">Cách dùng</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">Logic AND</a><code> </code>(<code>&&</code>)</td> + <td><code>expr1 && expr2</code></td> + <td>Trả về <code>expr1</code> nếu nó có thể biến đổi thành <code>false</code>; ngược lại, trả về <code>expr2</code>. Như vậy, khi dùng với giá trị Boolean, <code>&&</code> trả về <code>true</code> nếu cả hai toán hạng đều là true; ngược lại, trả về <code>false</code>.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">Logic OR </a>(<code>||</code>)</td> + <td><code>expr1 || expr2</code></td> + <td>Trả về <code>expr1</code> nếu nó có thể biến đổi thành <code>true</code>; ngược lại, trả về <code>expr2</code>. Vì vậy, khi dùng với giá trị Boolean, <code>||</code> trả về <code>true</code> nếu cả hai toán hạng đều là true; nếu cả hai false, trả về <code>false</code>.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">Logic NOT </a>(<code>!</code>)</td> + <td><code>!expr</code></td> + <td>Trả về <code>false</code> nếu toán hạng đứng ngay sau nó có thể biến đổi thành <code>true</code>; ngược lại, trả về <code>true</code>.</td> + </tr> + </tbody> +</table> + +<p>Ví dụ về các biểu thức có thể biến đổi thành <code>false</code> là những biểu thức khi thực thi trả về null, 0, NaN, chuỗi rỗng (""), hoặc undefined.</p> + +<p>Sau đây là các ví dụ cho toán tử <code>&&</code> (luận lý AND).</p> + +<pre class="brush: js">var a1 = true && true; // t && t trả về true +var a2 = true && false; // t && f trả về false +var a3 = false && true; // f && t trả về false +var a4 = false && (3 == 4); // f && f trả về false +var a5 = 'Cat' && 'Dog'; // t && t trả về Dog +var a6 = false && 'Cat'; // f && t trả về false +var a7 = 'Cat' && false; // t && f trả về false +</pre> + +<p>Sau đây là các ví dụ cho toán tử || (luận lý OR).</p> + +<pre class="brush: js">var o1 = true || true; // t || t trả về true +var o2 = false || true; // f || t trả về true +var o3 = true || false; // t || f trả về true +var o4 = false || (3 == 4); // f || f trả về false +var o5 = 'Cat' || 'Dog'; // t || t trả về Cat +var o6 = false || 'Cat'; // f || t trả về Cat +var o7 = 'Cat' || false; // t || f trả về Cat +</pre> + +<p>Sau đây là các ví dụ cho toán tử ! (luận lý NOT).</p> + +<pre class="brush: js">var n1 = !true; // !t trả về false +var n2 = !false; // !f trả về true +var n3 = !'Cat'; // !t trả về false +</pre> + +<h4 id="Short-Circuit_Evaluation" name="Short-Circuit_Evaluation">Thực thi đoản-mạch</h4> + +<p>Vì các biểu thức luận lý được thực thi từ trái sang phải, ta có thể dùng chúng để thử tính "đoán-mạch" qua các quy định sau:</p> + +<ul> + <li><code>false</code> && <em>bất cứ gì</em> là thực thi đoản-mạch ra false.</li> + <li><code>true</code> || <em>bất cứ gì</em> là thực thi đoản-mạch ra true.</li> +</ul> + +<p>Quy định luận lý đảm bảo rằng các thực thi trên luôn đúng. Chú ý phần <em>bất cứ gì</em> trong các biểu thức trên không được thực thi, bởi vậy sẽ không xảy ra bất cứ tác dụng phụ nào.</p> + +<h3 id="Toán_tử_chuỗi"><a id="String" name="String">Toán tử chuỗi</a></h3> + +<p>Ngoài toán tử so sánh, có thể dùng để so sánh chuỗi, toán tử ghép (+) ghép hai giá trị chuỗi lại với nhau, trả về một chuỗi mới là hợp của hai chuỗi cũ.</p> + +<p>Chẳng hạn,</p> + +<pre class="brush: js">console.log('my ' + 'string'); // console logs the string "my string".</pre> + +<p>Toán tử gán rút gọn += cũng có thể dùng để ghép chuỗi.</p> + +<p>Chẳng hạn,</p> + +<pre class="brush: js">var mystring = 'alpha'; +mystring += 'bet'; // "alphabet" sẽ ghép với giá trị này trước khi gán vào mystring.</pre> + +<h3 id="Toán_tử_điều_kiện_(ba_ngôi)"><a id="Conditional" name="Conditional">Toán tử điều kiện (ba ngôi)</a></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Toán tử điều kiện</a> là toán tử duy nhất của JavaScript cần tới ba toán hạng. Kết quả có thể là một trong hai giá trị tuỳ theo điều kiện. Cú pháp:</p> + +<pre class="syntaxbox"><em>điều_kiện</em> ? <em>giá_trị_1</em> : <em>giá_trị_2</em> +</pre> + +<p>Nếu <code>điều_kiện</code> trả về true, toán tử có giá trị <code>giá_trị_1</code>. Ngược lại toán tử có giá trị <code>giá_trị_2</code>. Bạn có thể dùng toán tử điều kiện ở bất cứ đâu như một toán tử bình thường.</p> + +<p>Chẳng hạn,</p> + +<pre class="brush: js">var status = (age >= 18) ? 'adult' : 'minor'; +</pre> + +<p>Đoạn code này gán giá trị "adult" cho biến <code>status</code> nếu <code>age</code> lớn hơn hoặc bằng 18. Ngược lại, nó gán giá trị "minor" cho <code>status</code>.</p> + +<h3 id="Comma_operator" name="Comma_operator"><a name="Comma">Toán tử dấu phẩy</a></h3> + +<p>Toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator">dấu phẩy</a> (<code>,</code>) đơn thuần tính toán cả hai giá trị toán hạng của nó và trả về giá trị của toán hạng cuối. Toán tử này được dùng chủ yếu trong vòng lặp <code>for</code>, để cho phép cập nhật nhiều biến cùng lúc sau mỗi lần thực hiện vòng lặp.</p> + +<p>Chẳng hạn, nếu <code>a</code> là một mảng 2-chiều với 10 phần tử mỗi chiều, đoạn code sau dùng toán tử dấu phẩy để cập nhật hai biến cùng một lúc. Console in ra giá trị của các phần tử nằm trong đường chéo:</p> + +<pre class="brush: js">var x = [0,1,2,3,4,5,6,7,8,9] +var a = [x, x, x, x, x]; + +for (var i = 0, j = 9; i <= j; i++, j--) + console.log('a[' + i + '][' + j + ']= ' + a[i][j]); +</pre> + +<h3 id="Toán_tử_một_ngôi"><a id="Unary" name="Unary">Toán tử một ngôi</a></h3> + +<p>Toán tử một ngôi là phép toán chỉ có duy nhất một toán hạng.</p> + +<h4 id="delete" name="delete"><code>delete</code></h4> + +<p>Toán tử <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code> xoá một object, một thuộc tính của object, hoặc một phần tử ở chỉ mục xác định trong mảng. Cú pháp là:</p> + +<pre class="brush: js">delete objectName; +delete objectName.property; +delete objectName[index]; +delete property; // chỉ được khi cài trong lệnh with +</pre> + +<p>Với <code>objectName</code> là tên của object, <code>property</code> là thuộc tính đang tồn tại, và <code>index</code> là giá trị nguyên của chỉ mục tương ứng với vị trí của thuộc tính trong mảng.</p> + +<p>Dạng thứ tư chỉ hoạt động khi được cài trong lệnh <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code>, để xoá một thuộc tính khỏi object.</p> + +<p>Bạn có thể dùng toán tử <code>delete</code> để xoá biến được khởi tạo ngầm nhưng không thể xoá được các biến được khởi tạo bằng lệnh <code>var</code>.</p> + +<p>Nếu toán tử <code>delete</code> thành công, nó đặt thuộc tính hoặc phần tử đó thành <code>undefined</code>. Toán tử <code>delete</code> trả về <code>true</code> nếu phép toán khả thi; nó trả về <code>false</code> nếu phép toán bất khả thi.</p> + +<pre class="brush: js">x = 42; +var y = 43; +myobj = new Number(); +myobj.h = 4; // tạo thuộc tính h +delete x; // trả về true (có thể xoá nếu khởi tạo ngầm) +delete y; // trả về false (không thể xoá nếu khởi tạo bằng var) +delete Math.PI; // trả về false (không thể xoá thuộc tính tiền định nghĩa) +delete myobj.h; // trả về true (có thể xoá thuộc tính người dùng định nghĩa) +delete myobj; // trả về true (có thể xoá nếu khợi tạo ngầm) +</pre> + +<h5 id="Xoá_phần_tử_mảng">Xoá phần tử mảng</h5> + +<p>Khi bạn xoá một phần tử của mảng, chiều dài mảng không bị ảnh hưởng. Chẳng hạn, nếu bạn xoá <code>a[3]</code>, <code>a[4]</code> vẫn là <code>a[4]</code> và <code>a[3]</code> là undefined.</p> + +<p>Khi toán tử <code>delete</code> loại bỏ một phần tử khỏi mảng, phần tử đó không còn tồn tại trong mảng. Trong ví dụ sau, <code>trees[3]</code> đã được loại bỏ bởi <code>delete</code>. Tuy nhiên, <code>trees[3]</code> vẫn có thể được trỏ tới và trả về <code>undefined</code>.</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +delete trees[3]; +if (3 in trees) { + // sẽ không chạy vào đây +} +</pre> + +<p>Nếu bạn muốn kiểm tra sự tồn tại của một phần tử trong mảng nhưng có giá trị là undefined, hãy dùng từ khoá <code>undefined</code> thay cho toán tử <code>delete</code>. Trong ví dụ tiếp sau đây, <code>trees[3]</code> được gán giá trị <code>undefined</code>, nhưng phần tử của mảng vẫn tồn tại:</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +trees[3] = undefined; +if (3 in trees) { + // sẽ chạy vào đây +} +</pre> + +<h4 id="typeof" name="typeof"><code>typeof</code></h4> + +<p>Toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof"><code>typeof</code></a> có thể dùng theo cả hai cách dưới đây:</p> + +<pre class="syntaxbox">typeof operand +typeof (operand) +</pre> + +<p>Toán tử <code>typeof</code> trả về một chuỗi ký tự thể hiện kiểu của toán hạng. <code>operand</code> có thể là chuỗi ký tự, biến, từ khoá, hoặc object cần xác định kiểu. Không bắt buộc phải thêm dấu ngoặc tròn.</p> + +<p>Giả sử bạn có các biến sau:</p> + +<pre class="brush: js">var myFun = new Function('5 + 2'); +var shape = 'round'; +var size = 1; +var foo = ['Apple', 'Mango', 'Orange']; +var today = new Date(); +</pre> + +<p>Toán tử <code>typeof</code> trả về kết quả lần lượt cho từng biến:</p> + +<pre class="brush: js">typeof myFun; // trả về "function" +typeof shape; // trả về "string" +typeof size; // trả về "number" +typeof foo; // trả về "object" +typeof today; // trả về "object" +typeof doesntExist; // trả về "undefined" +</pre> + +<p>Với từ khoá <code>true</code> và <code>null</code>, toán tử <code>typeof</code> trả về kết quả sau:</p> + +<pre class="brush: js">typeof true; // trả về "boolean" +typeof null; // trả về "object" +</pre> + +<p>Với số hoặc chuỗi ký tự, toán tử <code>typeof</code> trả về kết quả sau:</p> + +<pre class="brush: js">typeof 62; // trả về "number" +typeof 'Hello world'; // trả về "string" +</pre> + +<p>Với giá trị thuộc tính, toán tử <code>typeof</code> trả về kiểu dữ liệu mà thuộc tính đó bao hàm:</p> + +<pre class="brush: js">typeof document.lastModified; // trả về "string" +typeof window.length; // trả về "number" +typeof Math.LN2; // trả về "number" +</pre> + +<p>Với phương thức hoặc hàm, toán tử <code>typeof</code> trả về kết quả như sau:</p> + +<pre class="brush: js">typeof blur; // trả về "function" +typeof eval; // trả về "function" +typeof parseInt; // trả về "function" +typeof shape.split; // trả về "function" +</pre> + +<p>Với các object tiền định nghĩa, toán tử <code>typeof</code> trả về kết quả như sau:</p> + +<pre class="brush: js">typeof Date; // trả về "function" +typeof Function; // trả về "function" +typeof Math; // trả về "object" +typeof Option; // trả về "function" +typeof String; // trả về "function" +</pre> + +<h4 id="void" name="void"><code>void</code></h4> + +<p>Toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/void"><code>void</code> operator</a> có thể dùng theo cả hai cách dưới đây:</p> + +<pre class="syntaxbox">void (expression) +void expression +</pre> + +<p>Toán tử <code>void</code> xác định biểu thực cần thực hiện mà không trả về giá trị nào. <code>expression</code> là một biểu thức JavaScript cần thực hiện. Dấu ngoặc tròn bao quanh expression là không bắt buộc, nhưng sẽ rất phong cách nếu dùng chúng.</p> + +<p>Bạn có thể dùng toán tử <code>void</code> để xác định biểu thức cần thực thi trong một siêu liên kết. Biểu thức sẽ được thực hiện nhưng không văn bản hiện tại sẽ không tải lại tại chỗ.</p> + +<p>Đoạn code sau tạo ra một siêu liên kết không thực hiện bất cứ điều gì khi có người dùng nhấn vào. Khi người dùng nhấn vào, <code>void(0)</code> thực hiện thành <code>undefined</code>, vốn không có hiệu ứng gì trong JavaScript.</p> + +<pre class="brush: html"><a href="javascript:void(0)">Click here to do nothing</a> +</pre> + +<p>Đoạn code sẽ tiến hành hoàn tất mẫu đơn khi người dùng bấm vào siêu liên kết.</p> + +<pre class="brush: html"><a href="javascript:void(document.form.submit())"> +Click here to submit</a></pre> + +<h3 id="Toán_tử_quan_hệ"><a name="Relational">Toán tử quan hệ</a></h3> + +<p>Toán tử quan hệ so sánh các toán hạng của nó và trả về giá trị <code>Boolean</code> tuỳ thuộc phép so sánh có true hay không.</p> + +<h4 id="in"><code>in</code></h4> + +<p>Toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code></a> trả về <code>true</code> nếu thuộc tính nhất định có trong object nhất định. Cú pháp là:</p> + +<pre class="brush: js">propNameOrNumber in objectName +</pre> + +<p>với <code>propNameOrNumber</code> là chuỗi ký tự hoặc số đại diện cho tên của thuộc tính hoặc chỉ mục mảng, và <code>objectName</code> là tên của object.</p> + +<p>Các ví dụ dưới đây chỉ ra vài cách dùng toán tử <code>in</code>.</p> + +<pre class="brush: js">// Arrays +var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +0 in trees; // trả về true +3 in trees; // trả về true +6 in trees; // trả về false +'bay' in trees; // trả về false (bạn phải xác định được chỉ mục của mảng, + // không phải giá trị tại vị trí chỉ mục đó) +'length' in trees; // trả về true (length là một thuộc tính của Array) + +// object dựng sẵn +'PI' in Math; // trả về true +var myString = new String('coral'); +'length' in myString; // trả về true + +// object tự tạo +var mycar = { make: 'Honda', model: 'Accord', year: 1998 }; +'make' in mycar; // trả về true +'model' in mycar; // trả về true +</pre> + +<h4 id="instanceof" name="instanceof"><code>instanceof</code></h4> + +<p>Toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"><code>instanceof</code></a> trả về <code>true</code> nếu một object nhất định có kiểu của object nhất định. Cú pháp là:</p> + +<pre class="syntaxbox">objectName instanceof objectType +</pre> + +<p>với <code>objectName</code> là tên của object để so sánh với <code>objectType</code>, và <code>objectType</code> là kiểu của object, như là {{jsxref("Date")}} hay {{jsxref("Array")}}.</p> + +<p>Dùng <code>instanceof</code> khi bạn cần xác nhận kiểu của một object trong runtime (thời gian chạy). Chẳng hạn, khi bắt ngoại lệ, bạn có thể tìm tới từng ngoại lệ riêng biện tuỳ thuộc vào kiểu ngoại lệ được quăng (throw) ra.</p> + +<p>Chẳng hạn, đoạn code dưới đây dùng <code>instanceof</code> để xác định xem liệu <code>theDay</code> có phải là một <code>Date</code> object hay không. Bởi vì <code>theDay</code> là một <code>Date</code> object, các lệnh trong sau điều kiện <code>if</code> được thực thi.</p> + +<pre class="brush: js">var theDay = new Date(1995, 12, 17); +if (theDay instanceof Date) { + // lệnh sẽ được thực thi +} +</pre> + +<h3 id="Thứ_tự_thực_hiện_toán_tử">Thứ tự thực hiện toán tử</h3> + +<p><em>Thứ tự thực hiện</em> của toán tử xác định thứ tự thực hiện trong một biểu thức. Bạn có thể vượt quyền ưu tiên bằng cách dùng dấu ngoặc tròn.</p> + +<p>Bảng sau chỉ ra thứ tự thực hiện toán tử, từ cao nhất tới thấp nhất.</p> + +<table class="standard-table"> + <caption>Thứ tự thực hiện các toán tử</caption> + <thead> + <tr> + <th scope="col">?Loại toán tử</th> + <th scope="col">Individual operators</th> + </tr> + </thead> + <tbody> + <tr> + <td>member</td> + <td><code>. []</code></td> + </tr> + <tr> + <td>gọi / tạo mới instance</td> + <td><code>() new</code></td> + </tr> + <tr> + <td>phủ định/tăng</td> + <td><code>! ~ - + ++ -- typeof void delete</code></td> + </tr> + <tr> + <td>nhân/chia</td> + <td><code>* / %</code></td> + </tr> + <tr> + <td>cộng/trừ</td> + <td><code>+ -</code></td> + </tr> + <tr> + <td>dịch bit</td> + <td><code><< >> >>></code></td> + </tr> + <tr> + <td>quan hệ</td> + <td><code>< <= > >= in instanceof</code></td> + </tr> + <tr> + <td>bằng</td> + <td><code>== != === !==</code></td> + </tr> + <tr> + <td>bitwise-and</td> + <td><code>&</code></td> + </tr> + <tr> + <td>bitwise-xor</td> + <td><code>^</code></td> + </tr> + <tr> + <td>bitwise-or</td> + <td><code>|</code></td> + </tr> + <tr> + <td>logical-and</td> + <td><code>&&</code></td> + </tr> + <tr> + <td>logical-or</td> + <td><code>||</code></td> + </tr> + <tr> + <td>điều kiện</td> + <td><code>?:</code></td> + </tr> + <tr> + <td>gán</td> + <td><code>= += -= *= /= %= <<= >>= >>>= &= ^= |=</code></td> + </tr> + <tr> + <td>?dấu phẩy</td> + <td><code>,</code></td> + </tr> + </tbody> +</table> + +<p>Bảng thứ tự thực hiện chi tiết hơn có thể tìm được trong <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table">JavaScript Reference</a>.</p> + +<h2 id="Biểu_thức">Biểu thức</h2> + +<p><em>Biểu thức</em> là đơn vị code hợp lệ mà giải được ra một giá trị.</p> + +<p>Mọi biểu thức đúng cú pháp đều trả về vài giá trị nào đó nhưng về mặt lý thuyết, có hai kiểu biểu thức: kèm tác dụng phụ (chẳng hạn: những biểu thức gán giá trị cho biến nào đó) và những biểu thức thực hiện gì đấy rồi trả về giá trị.</p> + +<p>Biểu thức <code>x = 7</code> là ví dụ cho kiểu thứ nhất. Biểu thức này dùng <em>toán tử =</em> để gán giá trị cho biến <code>x</code>. Tự biểu thức trả về 7.</p> + +<p>Đoạn code <code>3 + 4</code> là ví dụ cho kiểu biểu thức thứ hai. Biểu thức này dùng toán tử + để thêm bốn vào ba mà không gán kết quả, bảy, cho một biến nào.<br> + <br> + JavaScript có các loại biểu thức sau đây:</p> + +<ul> + <li>Số học: tính toán thành một số, chẳng hạn 3.14159. (Thường dùng với <a href="#Arithmetic">toán tử số học</a>.)</li> + <li>Chuỗi ký tự: tính toán thành một chuỗi ký tự, chẳng hạn, "Fred" hoặc "234". (Thường dùng với <a href="#String">toán tử chuỗi</a>.)</li> + <li>Logic: tính toán thành true hoặc false. (Thường đi cùng với <a href="#Logical">toán tử luận lý</a>.)</li> + <li>Biểu thức nguyên thuỷ: Từ khoá căn bản và biểu thức chung trong JavaScript.</li> + <li>Biểu thức vế-trái: Giá trị bên trái là đích của phép gán.</li> +</ul> + +<h3 id="Biểu_thức_nguyên_thuỷ">Biểu thức nguyên thuỷ</h3> + +<p>Từ khoá căn bản và biểu thức chung trong JavaScript.</p> + +<h4 id="this" name="this"><code>this</code></h4> + +<p>Dùng từ khoá <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> để trỏ đến object hiện tại. Tổng quát, <code>this</code> trỏ tới object đang gọi trong một phương thức. Có thể dùng <code>this</code> cùng với dấu chấm hoặc dấu ngoặc vuông:</p> + +<pre class="syntaxbox">this['propertyName'] +this.propertyName +</pre> + +<p>Giả sử hàm <code>validate</code> xác thực thuộc tính <code>value</code> của object, truyền vào cận trên và cận dưới của nó:</p> + +<pre class="brush: js">function validate(obj, lowval, hival) { + if ((obj.value < lowval) || (obj.value > hival)) + console.log('Invalid Value!'); +} +</pre> + +<p>Bạn có thể gọi <code>validate</code> trong mỗi bộ xử lý sự kiện <code>onChange</code> trong form, dùng <code>this</code> để truyền vào phần tử của form, như trong ví dụ sau:</p> + +<pre class="brush: html"><p>Enter a number between 18 and 99:</p> +<input type="text" name="age" size=3 onChange="validate(this, 18, 99);"> +</pre> + +<h4 id="Toán_tử_nhóm">Toán tử nhóm</h4> + +<p>Toán tử nhóm <code>( )</code> kiểm soát thứ tự thực hiện trong biểu thức. Chẳng hạn, bạn có thể cho phép nhân và chia thực hiện sau khi cộng và trừ.</p> + +<pre class="brush:js">var a = 1; +var b = 2; +var c = 3; + +// thứ tự mặc định +a + b * c // 7 +// mặc định sẽ thực hiện như thế này +a + (b * c) // 7 + +// giờ vượt thứ tự nào +// cộng trước rồi mới nhân +(a + b) * c // 9 + +// tương tự như +a * c + b * c // 9 +</pre> + +<h3 id="Toán_tử_vế-trái">Toán tử vế-trái</h3> + +<p>Giá trị bên trái là đích của phép gán.</p> + +<h4 id="new" name="new"><code>new</code></h4> + +<p>Bạn có thể dùng toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code></a> để tạo ra một instance thuộc kiểu object mà người-dùng-định-nghĩa hoặc một trong những kiểu object dựng-sẵn. Dùng <code>new</code> như sau:</p> + +<pre class="brush: js">var objectName = new objectType([param1, param2, ..., paramN]); +</pre> + +<h4 id="super">super</h4> + +<p>Từ khoá <a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a> được dùng để gọi hàm thuộc cha của object. Thường dùng bởi <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classes</a> để gọi phương thức khởi tạo của lớp cha, chẳng hạn.</p> + +<pre class="syntaxbox">super([arguments]); // gọi phương thức khởi tạo của lớp cha. +super.functionOnParent([arguments]); +</pre> + +<h4 id="Toán_tử_Spread">Toán tử Spread</h4> + +<p>Toán tử <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread</a> cho phép biểu thức mở rộng tại chỗ khi có nhiều tham số (khi gọi hàm) hoặc nhiều phần tử (với array literal).</p> + +<p><strong>Ví dụ:</strong> Nếu bạn có một mảng và muốn tạo một mảng mới với mảng cũ là một thành phần trong nó, cú pháp của array literal không bao giờ là đủ và bạn bắt buộc phải code chay, dùng tổ hợp <code>push</code>, <code>splice</code>, <code>concat</code>, vân vân. Với cú pháp spread, việc này súc tích hơn hẳn:</p> + +<pre class="brush: js">var parts = ['shoulders', 'knees']; +var lyrics = ['head', ...parts, 'and', 'toes'];</pre> + +<p>Tương tự, toán tử spread cũng hoạt động với lời gọi hàm:</p> + +<pre class="brush: js">function f(x, y, z) { } +var args = [0, 1, 2]; +f(...args);</pre> + +<div>{{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> diff --git a/files/vi/web/javascript/guide/functions/index.html b/files/vi/web/javascript/guide/functions/index.html new file mode 100644 index 0000000000..069a43ef80 --- /dev/null +++ b/files/vi/web/javascript/guide/functions/index.html @@ -0,0 +1,668 @@ +--- +title: Functions +slug: Web/JavaScript/Guide/Functions +tags: + - Bắt đầu + - Hướng dẫn + - JavaScript + - hàm +translation_of: Web/JavaScript/Guide/Functions +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</div> + +<p class="summary">Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.</p> + +<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Functions">exhaustive reference chapter about JavaScript functions</a> to get to know the details.</p> + +<h2 id="Định_nghĩa_hàm">Định nghĩa hàm</h2> + +<h3 id="Khai_báo_hàm">Khai báo hàm</h3> + +<p><strong>Định nghĩa hàm</strong> (hay còn gọi là <strong>khai báo hằm</strong>, hoặc <strong>lệnh hàm</strong>) bao gồm từ khóa <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function" title="function"><code>function</code></a>, theo sau nó là:</p> + +<ul> + <li>Tên của hàm.</li> + <li>Danh sách các tham số truyền vào hàm, được đặt trong ngoặc đơn và cách nhau bởi dấu phẩy.</li> + <li>Các câu lệnh của JavaScript để tạo ra một hàm, được đặt trong ngoặc nhọn <code>{...}</code>.</li> +</ul> + +<p>Ví dụ, để định nghĩa một hàm có tên là <code>square</code>:</p> + +<pre class="brush: js">function square(number) { + return number * number; +} +</pre> + +<p>Hàm <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">square</span></font> nhận 1 tham số, có tên là <code>number</code>. Hàm này bao gồm một câu lệnh mà nó sẽ trả về tham số (<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">number</span></font>) nhân với chính nó. Câu lệnh <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return" title="return">return</a></code> chỉ định giá trị được trả lại bới hàm.</p> + +<pre class="brush: js">return number * number; +</pre> + +<p>Các tham số nguyên thủy (primitive parameters - ví dụ như một số) được truyền vào hàm <strong>bằng giá trị</strong>; giá trị được truyền vào hàm, nhưng nếu hàm thay đổi giá trị của tham số, <strong>sự thay đổi này sẽ không ánh xạ trên phạm vi global hoặc trên hàm gọi đến nó</strong> (nó sẽ không thay đổi giá trị của tham số được truyền vào ở phạm vi bên ngoài hàm).</p> + +<p>Nếu bạn truyền vào hàm một tham số là object (một giá trị non-primitive), ví dụ như một mảng {{jsxref("Array")}} hoặc một object được user tự định nghĩa, và hàm thay đổi các thuộc tính của object, thay đổi đó sẽ có hiệu lực ngay cả ở phạm vi bên ngoài của hàm, giống như ví dụ dưới đây:</p> + +<pre class="brush: js">function myFunc(theObject) { + theObject.make = "Toyota"; +} + +var mycar = {make: "Honda", model: "Accord", year: 1998}; +var x, y; + +x = mycar.make; // x nhận giá trị "Honda" + +myFunc(mycar); +y = mycar.make; // y nhận giá trị "Toyota" + // (thuộc tính make đã bị thay đổi bởi hàm myFunc) +</pre> + +<h3 id="Biểu_thức_hàm_hàm_trong_biến">Biểu thức hàm (hàm trong biến)</h3> + +<p>Trong khi việc khai báo hàm ở trên là một câu lệnh về mặt cú pháp, các hàm cũng có thể tạo ra bằng một biểu thức hàm (<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a>). Một hàm như vậy có thể <strong>nặc danh</strong>; nó không cần phải có tên. Ví dụ, hàm <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">square</span></font> có thể được khai báo như sau:</p> + +<pre class="brush: js">const square = function(number) { return number * number }; // square lúc này là một hằng giúp nặc danh cho hàm gán cho nó +var x = square(4) // x nhận giá trị 16</pre> + +<p>Tuy nhiên, một cái tên <em>có thể</em> được cung cấp trong một biểu thức hàm. Việc cung cấp tên cho phép hàm có thể chạy chính nó, hoặc có thể sử dụng hệ thống debug để nhận dạng hàm trong stack traces.</p> + +<pre class="brush: js">const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n-1) }; + +console.log(factorial(3)); +</pre> + +<p>Các biểu thức hàm rất tiện lợi trong việc truyền một hàm vào một hàm khác dưới vai trò một đối số (argument). Ví dụ sau cho thấy hàm <code>map</code> sẽ nhận một hàm khác là đối số đầu tiên và đối số thứ hai là một mảng.</p> + +<pre class="brush: js">function map(f,a) { + var result = [], // Create a new Array + i; + for (i = 0; i != a.length; i++) + result[i] = f(a[i]); + return result; +} +</pre> + +<p>Trong đoạn code dưới đây, hàm <code>map</code> nhận vào một hàm khác đã được định nghĩa bằng một biểu thức hàm, và <code>map</code> sẽ thực thi nó trên mọi phần tử của mảng (được truyền vào như một đối số thứ hai):</p> + +<pre class="brush: js">map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]); +</pre> + +<p>Kết quả trả về: [<code>0, 1, 8, 125, 1000]</code>.</p> + +<p>Trong JavaScript, một hàm có thể được định nghĩa dựa trên một điều kiện. Ví dụ, việc định nghĩa hàm dưới đây sẽ định nghĩa hàm <code>myFunc</code> chỉ khi <code>num</code> bằng 0.</p> + +<pre class="brush: js">var myFunc; +if (num == 0){ + myFunc = function(theObject) { + theObject.make = "Toyota" + } +}</pre> + +<p>Ngoài các cách định nghĩa hàm đã được mô tả, bạn cũng có thể sử dụng {{jsxref("Function")}} constructor to create functions from a string at runtime, much like {{jsxref("eval", "eval()")}}.</p> + +<p>Một <strong>phương thức</strong> là một hàm mà hàm đó chính là thuộc tính của một object. Xem thêm về object và phương thức tại đây <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects" title="en-US/docs/JavaScript/Guide/Working with Objects">Working with objects</a>.</p> + +<h2 id="Gọi_hàm">Gọi hàm</h2> + +<p><em>Việc định nghĩa</em> một hàm sẽ không <em>thực thi</em> nó. Định nghĩa một hàm đơn giản chỉ là đặt tên cho hàm và chỉ định những việc cụ thể sẽ làm khi hàm đó được gọi.</p> + +<p><strong>Gọi </strong>hàm thực chất là thi hành các hành động cụ thể với các tham số được chỉ định. Ví dụ, nếu bạn định nghĩa hàm <code>square</code>, bạn có thể gọi nó như sau:</p> + +<pre class="brush: js">square(5); +</pre> + +<p>Câu lệnh bên trên gọi hàm với một đối số của <code>5</code>. Hàm thực thi các câu lệnh của nó và trả về giá trị <code>25</code>.</p> + +<p>Các hàm phải đặt <em>trong phạm vi (</em><em>in scope)</em> khi nó được gọi, nhưng việc khai báo hàm có thể được hoisted (câu lệnh khai báo hàm xuất hiện bên dưới dòng gọi hàm trong đoạn code), như ví dụ này:</p> + +<pre class="brush: js">console.log(square(5)); +/* ... */ +function square(n) { return n*n } +</pre> + +<p>Phạm vi (scope) của một hàm là khoảng không gian bên trong hàm mà nó được khai báo (hoặc là cả chương trình, nếu nó được khai bảo ở top level, tức là nó không nằm trong hàm náo khác).</p> + +<div class="note"> +<p><strong>Ghi chú:</strong> Điều này chỉ đúng khi định nghĩa một hàm bằng cách sử dụng các cú pháp ở trên (ví dụ <code>function funcName(){}</code>). Đoạn code bên dưới sẽ không hoạt động.</p> + +<p>Điều này có nghĩa rằng function hoisting chỉ hoạt động với cách khai báo hàm thông thường (function declarations) - function hoisting không hoạt động đối với hàm được khai báo bằng biểu thức hàm (function expression).</p> +</div> + +<pre class="brush: js example-bad">console.log(square); // ReferenceError: square is not defined +console.log(square(5)); // ReferenceError: square is not defined +square = function (n) { + return n * n; +} +</pre> + +<p>Các đối số của một hàm không bị giới hạn trong phạm vi các chuỗi và các số. Bạn có thể truyền các object hoàn chỉnh vào một hàm. Hàm <code>show_props()</code>(được định nghĩa trong <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_Properties" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects#Objects_and_Properties">Working with objects</a>) là một ví dụ của một hàm mà nó nhận một object như là một đối số.</p> + +<p>Một hàm có thể gọi chính nó. Ví dụ, đây là một hàm tính giai thừa đệ quy:</p> + +<pre class="brush: js">function factorial(n){ + if ((n == 0) || (n == 1)) + return 1; + else + return (n * factorial(n - 1)); +} +</pre> + +<p>Bạn có thể tính giai thừa của <code>1</code> tới <code>5</code> như sau:</p> + +<pre class="brush: js">var a, b, c, d, e; +a = factorial(1); // a gets the value 1 +b = factorial(2); // b gets the value 2 +c = factorial(3); // c gets the value 6 +d = factorial(4); // d gets the value 24 +e = factorial(5); // e gets the value 120 +</pre> + +<p>Có những cách khác để gọi hàm. Có nhiều trường hợp mà tại đó một hàm cần phải được gọi một cách tự động, hoặc làm thay đổi số lượng đối số truyền vào một hàm, hoặc trong trường hợp mà việc gọi hàm cần được gắn với một object nhất định được quyết định tại thời điểm runtime.</p> + +<p>Điều đó lại hóa ra là <em>các hàm tự bản thân chúng là các object</em>, và kết quả là, những object này có các phương thức. (Xem {{jsxref("Function")}} object). Một trong số chúng, phương thức {{jsxref("Function.apply", "apply()")}}, có thể được dùng để đạt được mục tiêu này.</p> + +<h2 class="deki-transform" id="Phạm_vi_của_hàm_function_scope">Phạm vi của hàm (function scope)</h2> + +<p>Các biến được định nghĩa bên trong một hàm không thể được truy cập từ nơi nào khác bên ngoài hàm, bởi vì biến đó được định nghĩa chỉ trong phạm vi của hàm. Tuy nhiên, một hàm có thể truy cập đến mọi biến và mọi hàm khác trong cùng phạm vi mà nó được định nghĩa.</p> + +<p>Nói cách khác, một hàm được định nghĩa trong phạm vi global có thể truy cập tới tất cả các biến đã được định nghĩa trong phạm vi global. Một hàm được định nghĩa bên trong một hàm khác có thể truy cập đến tất cả biến được định nghĩa bên trong hàm cha của nó, và bất cứ biến nào khác mà hàm cha của nó có quyền truy cập đến.</p> + +<pre class="brush: js">// Các biến sau được định nghĩa trong phạm vi global scope +var num1 = 20, + num2 = 3, + name = "Chamahk"; + +// Hàm này được định nghĩa trong phạm vi global scope +function multiply() { + return num1 * num2; +} + +multiply(); // Returns 60 + +// Một ví dụ hàm lồng nhau +function getScore () { + var num1 = 2, + num2 = 3; + + function add() { + return name + " scored " + (num1 + num2); + } + + return add(); +} + +getScore(); // Returns "Chamahk scored 5" +</pre> + +<h2 id="Phạm_vi_và_ngăn_xếp_của_hàm">Phạm vi và ngăn xếp của hàm</h2> + +<h3 id="Recursion">Recursion</h3> + +<p>Một hàm có thể tham chiếu và gọi chính nó. Có 3 cách để một hàm có thể tham chiếu đến chính nó:</p> + +<ol> + <li>Dùng tên của hàm</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code></li> + <li>Một biến in-scope mà có tham chiếu đến hàm.</li> +</ol> + +<p>Ví dụ, xem xét việc định nghĩa hàm sau đây:</p> + +<pre class="brush: js">var foo = function bar() { + // statements go here +}; +</pre> + +<p>Bên trong phần body của hàm, các điều sau là tương tự nhau:</p> + +<ol> + <li><code>bar()</code></li> + <li><code>arguments.callee()</code></li> + <li><code>foo()</code></li> +</ol> + +<p>Một hàm mà gọi chính nó được gọi là (<em>hàm đệ quy)</em> <em>recursive function</em>. Trong một số cách hiểu, thì đệ quy (recursion) cũng tương tự như một vòng lặp. Cả hai đều là thực thi một đoạn code lặp đi lặp lại nhiều lần, và cả hai đều yêu cầu điều kiện xác định để chạy (để tránh lặp vô tận, hoặc recursion vô tận). Ví dụ, vòng lặp sau đây... </p> + +<pre class="brush: js">var x = 0; +while (x < 10) { // "x < 10" là điều kiện lặp + // thực thi việc sau + x++; +} +</pre> + +<p>...có thể được chuyển đổi sang một hàm đệ quy:</p> + +<pre class="brush: js">function loop(x) { + if (x >= 10) // "x >= 10" là điều kiện thoát ra (tương đương với "!(x < 10)") + return; + // do stuff + loop(x + 1); // the recursive call +} +loop(0); +</pre> + +<p>Tuy nhiên, một số thuật toán không phải là các vòng lặp chỉ đơn giản là được lặp đi lặp lại. Ví dụ, việc lấy tất cả các nodes của một cấu trúc tree (như <a href="/en-US/docs/DOM">DOM</a>) sẽ được thực hiện dễ dàng hơn thông qua đệ quy:</p> + +<pre class="brush: js">function walkTree(node) { + if (node == null) // + return; + // do something with node + for (var i = 0; i < node.childNodes.length; i++) { + walkTree(node.childNodes[i]); + } +} +</pre> + +<p>So với hàm <code>loop</code>, mỗi một lần gọi đệ quy sẽ tạo ra nhiều lần gọi đệ quy tại đây.</p> + +<p>Bạn có thể chuyển đổi bất kỳ thuật toán đệ quy nào sang một dạng non-recursive, nhưng logic thường sẽ phức tạp hơn rất nhiều, và làm như vậy cũng đòi hỏi sử dụng một ngăn xếp (a stack).</p> + +<p>Thực tế, việc đệ quy bản thân nó khi đệ quy có sử dụng một ngăn xếp: gọi là ngăn xếp hàm (function stack). Lối thực thi dạng ngăn xếp này có thể được tìm thấy trong ví dụ dưới đây:</p> + +<pre class="brush: js">function foo(i) { + if (i < 0) + return; + console.log('begin:' + i); + foo(i - 1); + console.log('end:' + i); +} +foo(3); + +// Output: + +// begin:3 +// begin:2 +// begin:1 +// begin:0 +// end:0 +// end:1 +// end:2 +// end:3</pre> + +<h3 id="Hàm_lồng_nhau_và_các_closures">Hàm lồng nhau và các closures</h3> + +<p>Bạn có thể lồng một hàm bên trong một hàm khác. Hàm con (bên trong) được là private cho hàm chứa nó (hàm bao bên ngoài).</p> + +<p>Điều đó cũng định hình nên một <em>closure</em>. Một closure là một biểu thức (thường thì chính là một hàm) mà biểu thức đó có thể có các biến tự do kết hợp với môi trường trói buộc chúng (hay nói cách khác là môi trường giúp "close" biểu thức).</p> + +<p>Vì một hàm con là một closure, có nghĩa rằng hàm con có thể "thừa kế" các tham số và các biến của hàm cha. Nói cách khác, một hàm con sẽ chứa scope của hàm cha.</p> + +<p>Tóm tắt lại:</p> + +<ul> + <li>Hàm con chỉ có thể được truy cập từ các câu lệnh đặt bên trong hàm cha.</li> + <li>Hàm con sẽ định hình nên một closure: hàm con có thể sử dụng các đối số và các biến của hàm cha, trong khi hàm cha không thể sử dụng các đối số và các biến của hàm con.</li> +</ul> + +<p>Ví dụ sau chỉ ra các hàm được lồng nhau:</p> + +<pre class="brush: js">function addSquares(a,b) { + function square(x) { + return x * x; + } + return square(a) + square(b); +} +a = addSquares(2,3); // returns 13 +b = addSquares(3,4); // returns 25 +c = addSquares(4,5); // returns 41 +</pre> + +<p>Vì hàm con định hình nên một closure, bạn có thể gọi hàm cha đồng thời chỉ định các đối số cho cả hàm cha và hàm con.</p> + +<pre class="brush: js">function outside(x) { + function inside(y) { + return x + y; + } + return inside; +} +fn_inside = outside(3); // Kết quả trả về hàm inside(y) +result = fn_inside(5); // Trả về 8 + +result1 = outside(3)(5); // Trả về 8, các đối số được thêm đồng thời cùng lúc +</pre> + +<h3 id="Sự_bảo_tồn_của_các_biến">Sự bảo tồn của các biến</h3> + +<p>Để ý cách mà <code>x</code> được bảo tồn sau khi hàm <code>inside</code> returne. Một closure phải bảo tồn các đối số và các biến bên trong mọi scope mà nó tham chiếu. Vì mỗi lần gọi hàm mang đến các tham số đôi khi khác nhau, nên một closure mới sẽ được tạo ra cho mỗi lần gọi hàm <code>outside</code>. Bộ nhớ bảo tồn này chỉ có thể được giải phóng khi hàm <code>inside</code> được return không còn khả dụng.</p> + +<p>Điều này không khác gì so với lưu trữ các sự tham chiếu bên trong các object khác, nhưng điều này ít rõ ràng hơn vì nó không thiết lập các sự tham chiếu một cách trực tiếp và cũng không thể kiểm tra được chúng.</p> + +<h3 id="Các_hàm_lồng_nhau_nhiều_cấp">Các hàm lồng nhau nhiều cấp</h3> + +<p>Các hàm có thể được lồng nhau nhiều cấp. Ví dụ:</p> + +<ul> + <li>Một hàm (<code>A</code>) chứa một hàm (<code>B</code>), hàm (<code>B</code>) này chứa một hàm (<code>C</code>)</li> + <li>Ở đây, cả hai hàm <code>B</code> và <code>C</code> định hình nên các closures.Vì thế, <code>B</code> có thể truy cập đến <code>A</code>, và <code>C</code> có thể truy cập đến <code>B</code>.</li> + <li>Ngoài ra, vì <code>C</code> có thể truy cập đến <code>B</code> mà <code>B</code> truy cập được đến <code>A</code>, nên <code>C</code> cũng có thể truy cập đến <code>A</code>.</li> +</ul> + +<p>Do đó, các closures có thể chứa nhiều scope đa cấp; các closures sẽ bao gồm luôn cả phạm vi scope của các hàm chưa nó, việc bao gồm này có hình thức đệ quy. Đây gọi là <em>scope chaining.</em> (Lí do tại sao gọi là "chaining" sẽ giải thích sau).</p> + +<p>Cân nhắc ví dụ sau:</p> + +<pre class="brush: js">function A(x) { + function B(y) { + function C(z) { + console.log(x + y + z); + } + C(3); + } + B(2); +} +A(1); // logs 6 (1 + 2 + 3) +</pre> + +<p>Trong ví dụ này, <code>C</code> truy cập đến <code>y</code> của <code>B</code> và <code>x</code> của <code>A</code>. Điều này có thể đạt được bởi vì: </p> + +<ol> + <li><code>B</code> định hình một closure mà closure này bao gồm <code>A</code>, ví dụ <code>B</code> có thể truy cập đến các đối số và biến của <code>A</code>.</li> + <li><code>C</code> định hình nên một closure mà closure này bao gồm <code>B</code>.</li> + <li>Vì closure của <code>B</code> bao gồm <code>A</code>, closure của <code>C</code> bao gồm <code>A</code>, <code>C</code> có thể truy cập đến biến và đối số của cả hai hàm <code>A</code> và <code>B</code>. Nói cách khác, <code>C</code> <em>chains </em>the scopes của <code>B</code> và <code>A</code>, <em>theo đúng thứ tự đó</em>.</li> +</ol> + +<p>Tuy nhiên nếu chạy ngược lại thì không đúng. <code>A</code> không thể truy cập đến <code>C</code>, vì <code>A</code> không thể truy cập đén các đối số và biến của <code>B</code>, mà <code>C</code> chính là một biến của <code>B</code>. Vì vậy <code>C</code> duy trì quyền truy cập private chỉ riêng đối với <code>B</code>.</p> + +<h3 id="Xung_đột_tên_gọi">Xung đột tên gọi</h3> + +<p>Khi hai đối số hoặc biến trong một scope của một closure có tên giống nhau, sẽ xảy ra <em>xung đột tên gọi,</em> scope nào nằm ở trong sâu hơn thì được ưu tiên. Cho nên, scope trong cùng sẽ mang ưu tiên cao nhất, trong khi scope ngoài cùng ưu tiên thấp nhất. Đây chính là scope chain (chuỗi xích phạm vi). Mắc xích đầu tiên của chain là scope trong cùng, và mắc xích cuối cùng của chain là scope ngoài cùng. Xem xét ví dụ sau:</p> + +<pre class="brush: js">function outside() { + var x = 10; + function inside(x) { + return x; + } + return inside; +} +result = outside()(20); // returns 20 thay vì 10 +</pre> + +<p>Xung đột tên gọi xảy ra tại câu lệnh <code>return x</code> giữa tham số <code>x</code> của hàm <code>inside</code> và tham số <code>x</code> của hàm <code>outside</code>. Scope chain ở đây là {<code>inside</code>, <code>outside</code>, global object}. Vì vậy tham số <code>x</code> của <code>inside</code> được ưu tiên hơn <code>x</code> của <code>outside</code>, và 20 (giá trị <code>x</code> của <code>insisde</code>) được trả về thay vì 10.</p> + +<h2 id="Closures">Closures</h2> + +<p>Closures là một trong những chức năng quyền lực nhất của JavaScript. JavaScript cho phép lồng các function vào nhau, và cấp quyền cho function con, để function con có toàn quyền truy cập vào tất cả các biến và function được định nghĩa bên trong function cha (và tất cả biến và function mà function cha được cấp quyền truy cập đến).</p> + +<p>Tuy nhiên, function cha không có quyền truy cập đến các biến và function được định nghĩa bên trong function con. Điều này tạo nên một dạng bảo mật khép kín cho các biến của function con.</p> + +<p>Bên cạnh đó, vì function con có quyền truy cập đến scope của function cha, các biến và function được định nghĩa bên trong function cha sẽ vẫn tồn tại dù việc thực thi function cha đã kết thúc, nếu function con xoay sở để tồn tại lâu hơn thời gian sống của function cha. Một closure được tạo ra khi một function con bằng cách nào đó trở nên khả dụng với bất kỳ scope nào bên ngoài function cha.</p> + +<pre class="brush: js">var pet = function(name) { // Function cha định nghĩa một biến tên là "name" + var getName = function() { + return name; // Function con có quyền truy cập đến biến "name" của function cha + } + return getName; // Trả về function con, theo đó làm function con bị phơi bày ra phạm vi scope bên ngoài (không còn bị giới hạn bên trong function cha nữa) +}, +myPet = pet("Vivie"); + +myPet(); // Returns "Vivie" +</pre> + +<p>Thực tế sẽ phức tạp hơn nhiều so với đoạn code bên trên. Nó có thể trả về một object bao gồm các phương thức phục vụ cho việc điều khiển các biến bên trong một function cha.</p> + +<pre class="brush: js">var createPet = function(name) { + var sex; + + return { + setName: function(newName) { + name = newName; + }, + + getName: function() { + return name; + }, + + getSex: function() { + return sex; + }, + + setSex: function(newSex) { + if(typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) { + sex = newSex; + } + } + } +} + +var pet = createPet("Vivie"); +pet.getName(); // Vivie + +pet.setName("Oliver"); +pet.setSex("male"); +pet.getSex(); // male +pet.getName(); // Oliver +</pre> + +<p>Tron đoạn code trên, các function con có thể truy cập vào biến <code>name</code> của function cha, và không có cách nào khác để truy cập vào các biến của function con ngoại trừ thông qua function con. Các biến bên trong của function con đóng vai trò như kho lưu trữ an toàn cho các đối số và biến bên ngoài. Chúng giữ dữ liệu một cách kiên định, và nội bộ, để function con xử lý. Các functions thậm chí không cần phải gán vào bất kỳ biến nào, và cũng không cần tên.</p> + +<pre class="brush: js">var getCode = (function(){ + var secureCode = "0]Eal(eh&2"; // Đoạn code chúng ta không muốn những thứ bên ngoài có thể thay đổi nó... + + return function () { + return secureCode; + }; +})(); + +getCode(); // Returns the secureCode +</pre> + +<p><strong>Lưu ý</strong>: Có một vài cạm bẫy cần đề phòng khi sử dụng các closures!</p> + +<p>Nếu một function bị bọc kín định nghĩa một biến với tên trùng với tên của function bên ngoài, từ đó sẽ không có cách nào khác để tham chiếu đến biến của function bên ngoài nữa. (Lúc này biến của function bên trong đã ghi đè lên biến bên ngoài, cho đến khi chương trình thoát khỏi scope bên trong.)</p> + +<pre class="brush: js">var createPet = function(name) { // Outer function defines a variable called "name" + return { + setName: function(name) { // Enclosed function also defines a variable called "name" + name = name; // ??? How do we access the "name" defined by the outer function ??? + } + } +} +</pre> + +<p>The magical <code>this</code> variable is very tricky in closures. They have to be used carefully, as what <code>this</code> refers to depends completely on where the function was called, rather than where it was defined.</p> + +<h2 id="Sử_dụng_arguments_object">Sử dụng arguments object</h2> + +<p>Các đối số của một function được giữ dưới dạng một object dạng mảng. Trong phạm vi function, bạn có thể định vị các đối số được truyền vào function bằng cách sau:</p> + +<pre class="brush: js">arguments[i] +</pre> + +<p>trong đó <code>i</code> là số thứ tự của đối số, bắt đầu từ 0. Vì vậy, đối số đầu tiên được truyền vào một function sẽ là <code>arguments[0]</code>. Tổng số đối số được xác định bằng <code>arguments.length</code>.</p> + +<p>Sử dụng các <code>arguments</code> object, bạn có thể gọi một function với số đối số nhiều hơn số đối số được chấp nhận thông qua khai báo chính thức. Điều này sẽ hữu ích khi bạn không biết trước có bao nhiêu đối số sẽ được truyền vào function. Bạn có thể sử dụng <code>arguments.length</code> để xác định số lượng đối số thực tế được truyền vào function, và sau đó truy cập đến từng đối số bằng cách dùng <code>arguments</code> object. </p> + +<p>Ví dụ, xem xét một function có chức năng nối các string với nhau. Đối số chính thức duy nhất cho function là một string, và string này xác định những ký tự nào sẽ tách các phần tử ra để nối. Function được định nghĩa như sau:</p> + +<pre class="brush: js">function myConcat(separator) { + var result = "", // initialize list + i; + // iterate through arguments + for (i = 1; i < arguments.length; i++) { + result += arguments[i] + separator; + } + return result; +} +</pre> + +<p>Bạn có thể truyền vào bao nhiêu đối số vào function này cũng được, và nó sẽ nối từng đối số với nhau tạo thành một "list" có kiểu string.</p> + +<pre class="brush: js">// returns "red, orange, blue, " +myConcat(", ", "red", "orange", "blue"); + +// returns "elephant; giraffe; lion; cheetah; " +myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); + +// returns "sage. basil. oregano. pepper. parsley. " +myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); +</pre> + +<div class="note"> +<p><strong>Ghi chú:</strong> Biến <code>arguments</code> nhìn giống mảng, nhưng nó không phải là một mảng. Nó giống mảng ở chỗ bên trong nó có các index được đánh số và nó có một thuộc tính <code>length</code>. Tuy nhiên, nó <em>không</em> sở hữu bất kỳ phương thức nào để thao tác sử dụng mảng.</p> +</div> + +<p>Xem {{jsxref("Function")}} object trong JavaScript reference để biết thêm.</p> + +<h2 id="Các_tham_số_của_function">Các tham số của function</h2> + +<p>Kể từ ES6, xuất hiện 2 dạng tham số mới: <em>default parameters</em> và <em>rest parameters</em></p> + +<h3 id="Default_parameters">Default parameters</h3> + +<p>Trong JavaScript, các tham số của function được mặc định là <code>undefined</code>. Tuy nhiên, trong một số trường hợp nó có thể hữu ích để thiết lập một giá trị mặc định khác. Đây chính xác là điều mà default parameters sẽ làm.</p> + +<h4 id="Khi_không_có_default_parameters_trước_ES6">Khi không có default parameters (trước ES6)</h4> + +<p>Trong quá khứ, chiến thuật thông thường để thiết lập các giá trị mặc định là kiểm định giá trị của các tham số bên trong body của function và gán giá trị cho nó nếu nó là <code>undefined</code>.</p> + +<p>Trong ví dụ sau, nếu không có giá trị nào được truyền cho <code>b</code>, giá trị của nó sẽ là <code>undefined</code> khi thực hiện tính toán <code>a*b</code>, và việc gọi hàm <code>multiply</code> sẽ trả về <code>NaN</code>. Tuy nhiên, điều này bị ngăn chặn bởi dòng thứ 2 trong ví dụ này:</p> + +<pre class="brush: js">function multiply(a, b) { + b = typeof b !== 'undefined' ? b : 1; + + return a*b; +} + +multiply(5); // 5 +</pre> + +<h4 id="Khi_có_default_parameters_sau_ES6">Khi có default parameters (sau ES6)</h4> + +<p>Với <em>default parameters</em>, việc kiểm tra thủ công bên trong body của function không còn cần thiết. Bạn có thể đơn giản chỉ là đặt <code>1</code> vào làm giá trị mặc định cho <code>b</code> ngay tại head của function:</p> + +<pre class="brush: js">function multiply(a, b = 1) { + return a*b; +} + +multiply(5); // 5</pre> + +<p>Để chi tiết hơn, xem <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> trong phần tham khảo.</p> + +<h3 id="Rest_parameters">Rest parameters</h3> + +<p>Cú pháp <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameter</a> cho phép chúng ta dùng 1 mảng để đại diện cho số lượng vô hạn các đối số.</p> + +<p>Trong ví dụ sau, hàm <code>multiply</code> sử dụng <em>rest parameters</em> để thu thập các đối số kể từ đối số hứ hai trở về đến hết. Hàm này sau đó sẽ nhân những đối số này với đối số đầu tiên.</p> + +<pre class="brush: js">function multiply(multiplier, ...theArgs) { + return theArgs.map(x => multiplier * x); +} + +var arr = multiply(2, 1, 2, 3); +console.log(arr); // [2, 4, 6]</pre> + +<h2 id="Arrow_functions">Arrow functions</h2> + +<p>Một <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> (trước đây, và hiện tại được biết đến một cách không còn đúng là <strong>fat arrow function</strong>) có một cú pháp ngắn hơn function expressions và không có <code>this</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a>, or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a> của chính nó. Các arrow function luôn luôn là nặc danh. Xem "<a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">ES6 In Depth: Arrow functions</a>".</p> + +<p>Có 2 yếu tố dẫn đến việc giới thiệu arrow function: các <em>function ngắn hơn</em> và sự <em>non-binding</em> của <code>this</code> (lexical <code>this</code>).</p> + +<h3 id="Các_function_ngắn_hơn">Các function ngắn hơn</h3> + +<p>Trong một mẫu function, các function ngắn hơn được khuyến khích. So sánh:</p> + +<pre>var a = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +var a2 = a.map(function(s) { return s.length; }); + +console.log(a2); // logs [8, 6, 7, 9] + +var a3 = a.map(s => s.length); + +console.log(a3); // logs [8, 6, 7, 9]</pre> + +<h3 id="No_separate_this_Lexical_this">No separate <code>this</code> (Lexical <code>this</code>)</h3> + +<p>Trước khi có arrow functions, mọi function mới sẽ tự định nghĩa giá trị <code>this</code> của nó (a new object in the case of a constructor, undefined in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> function calls, the base object if the function is called as an "object method", etc.). Điều này đã được chứng minh là không lý tưởng đối với phong cách lập trình hướng đối tượng.</p> + +<pre class="brush: js">function Person() { + // Constructor của Person() tự định nghĩa `<code>this`</code>. + this.age = 0; + + setInterval(function growUp() { + // Trong nonstrict mode, hàm growUp() định nghĩa `this` + // như là một global object, và global object này khác với `this` + // được định nghĩa bởi Person() constructor. + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>Trong ECMAScript 3/5, vấn đề này được sửa chữa bằng cách gán giá trị bên trong <code>this</code> cho một biến mà biến đó có thể được đóng hoàn toàn.</p> + +<pre class="brush: js">function Person() { + var self = this; // Some choose `that` instead of `self`. + // Choose one and be consistent. + self.age = 0; + + setInterval(function growUp() { + // The callback refers to the `self` variable of which + // the value is the expected object. + self.age++; + }, 1000); +} + +var p = new Person(); +</pre> + +<h2 id="Predefined_functions">Predefined functions</h2> + +<p>JavaScript has several top-level, built-in functions:</p> + +<dl> + <dt>{{jsxref("Global_Objects/eval", "eval()")}}</dt> + <dd> + <p>The <code><strong>eval()</strong></code> method evaluates JavaScript code represented as a string.</p> + </dd> + <dt>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</dt> + <dd> + <p>The <code><strong>uneval()</strong></code> method creates a string representation of the source code of an {{jsxref("Object")}}.</p> + </dd> + <dt>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</dt> + <dd> + <p>The global <code><strong>isFinite()</strong></code> function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.</p> + </dd> + <dt>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</dt> + <dd> + <p>The <code><strong>isNaN()</strong></code> function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the <code>isNaN</code> function has <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description">interesting</a> rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 6, or you can use <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code> to determine if the value is Not-A-Number.</p> + </dd> + <dt>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</dt> + <dd> + <p>The <code><strong>parseFloat()</strong></code> function parses a string argument and returns a floating point number.</p> + </dd> + <dt>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</dt> + <dd> + <p>The <code><strong>parseInt()</strong></code> function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).</p> + </dd> + <dt>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</dt> + <dd> + <p>The <code><strong>decodeURI()</strong></code> function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.</p> + </dd> + <dt>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</dt> + <dd> + <p>The <code><strong>decodeURIComponent()</strong></code> method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.</p> + </dd> + <dt>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</dt> + <dd> + <p>The <code><strong>encodeURI()</strong></code> method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).</p> + </dd> + <dt>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</dt> + <dd> + <p>The <code><strong>encodeURIComponent()</strong></code> method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).</p> + </dd> + <dt>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</dt> + <dd> + <p>The deprecated <code><strong>escape()</strong></code> method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} instead.</p> + </dd> + <dt>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</dt> + <dd> + <p>The deprecated <code><strong>unescape()</strong></code> method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like {{jsxref("Global_Objects/escape", "escape")}}. Because <code>unescape()</code> is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.</p> + </dd> +</dl> + +<p>{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</p> diff --git a/files/vi/web/javascript/guide/gioi-thieu/index.html b/files/vi/web/javascript/guide/gioi-thieu/index.html new file mode 100644 index 0000000000..f8fddcf666 --- /dev/null +++ b/files/vi/web/javascript/guide/gioi-thieu/index.html @@ -0,0 +1,137 @@ +--- +title: Giới thiệu +slug: Web/JavaScript/Guide/Gioi-thieu +tags: + - Guide + - JavaScript +translation_of: Web/JavaScript/Guide/Introduction +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</div> + +<p class="summary">Trong phần này: giới thiệu về JavaScript và thảo luận về một số khái niệm cơ bản của JavaScript.</p> + +<h2 id="Kiến_thức_nền_tảng_cần_có">Kiến thức nền tảng cần có</h2> + +<p>Để đến với JavaScript, chúng tôi giả sử rằng bạn đã có một số hiểu biết nền tảng:</p> + +<ul> + <li>Có hiểu biết chung về Internet và World Wide Web ({{Glossary("WWW")}}).</li> + <li>Đã biết và có thể làm việc được với HyperText Markup Language ({{Glossary("HTML")}}).</li> + <li>Có một số kinh nghiệm về lập trình. Nếu bạn là một người mới tìm hiểu về lập trình, bạn nên đi theo những hướng dẫn có tại trang thông tin chính về <a href="/en-US/docs/Web/JavaScript" title="/en-US/docs/">JavaScript.</a></li> +</ul> + +<h2 id="Bạn_có_thể_tìm_thêm_thông_tin_về_JavaScript_ở_đâu">Bạn có thể tìm thêm thông tin về JavaScript ở đâu?</h2> + +<p>Tài liệu về JavaScript tại MDN bao gồm:</p> + +<ul> + <li><a href="/en-US/Learn">Learning the Web</a> cung cấp cho người mới bắt đầu thông tin và giới thiệu về các khái niệm cơ bản của lập trình và Internet.</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">JavaScript Guide</a> (là phần hướng dẫn này) cung cấp một cái nhìn tổng quát về ngôn ngữ JavaScript và các Object của nó.</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference" title="en/JavaScript/Reference">JavaScript Reference</a> cung cấp tài liệu chi tiết về JavaScript.</li> +</ul> + +<p>Nếu bạn mới tìm hiểu JavaScript, hãy bắt đầu bằng cách đọc các bài viết tại <a href="/en-US/Learn">learning area</a> và <a href="/en-US/docs/Web/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">JavaScript Guide</a>. Một khi bạn đã nắm vững các nền tảng cơ bản, bạn có thể sử dụng <a href="/en-US/docs/Web/JavaScript/Reference" title="en/JavaScript/Reference">JavaScript Reference</a> để lấy những thông tin chi tiết của từng object và các câu lệnh (statements).</p> + +<h2 id="JavaScript_là_gì">JavaScript là gì?</h2> + +<p>JavaScript là một ngôn ngữ lập trình đa nền tảng (<strong>cross-platform)</strong>, ngôn ngữ lập trình kịch bản, hướng đối tượng. JavaScript là một ngôn ngữ nhỏ và nhẹ (small and lightweight). Khi nằm bên trong một môi trường (host environment), JavaScript có thể kết nối tới các object của môi trường đó và cung cấp các cách quản lý chúng (object).</p> + +<p>JavaScript chứa các thư viện tiêu chuẩn cho các object, ví dụ như: <code>Array</code>, <code>Date</code>, và <code>Math</code>, và các yếu tố cốt lõi của ngôn ngữ lập trình như: toán tử (operators), cấu trúc điều khiển (control structures), và câu lệnh. JavaScript có thể được mở rộng cho nhiều mục đích bằng việc bổ sung thêm các object; ví dụ:</p> + +<ul> + <li><em>Client-side JavaScript</em> - JavaScript phía máy khách, JavaScript được mở rộng bằng cách cung cấp các object để quản lý trình duyệt và Document Object Model (DOM) của nó. Ví dụ, phần mở rộng phía máy khách cho phép một ứng dụng tác động tới các yếu tố trên một trang HTML và phản hồi giống các tác động của người dùng như click chuột, nhập form, và chuyển trang.</li> + <li><em>Server-side JavaScript </em>- JavaScript phía Server, JavaScript được mở rộng bằng cách cung cấp thêm các đối tượng cần thiết để để chạy JavaScript trên máy chủ. Ví dụ, phần mở rộng phía server này cho phép ứng dụng kết nối với cơ sở dữ liệu (database), cung cấp thông tin một cách liên tục từ một yêu cầu tới phần khác của ứng dụng, hoặc thực hiện thao tác với các tập tin trên máy chủ.</li> +</ul> + +<h2 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript và Java</h2> + +<p>JavaScript và Java thì giống nhau ở những cái này nhưng lại khác nhau ở cái khác. Ngôn ngữ JavaScript có lẽ giống giống với ngôn ngữ Java nhưng JavaScript không có khai báo static cũng như không có "tính mạnh về kiểu" (strong type checking) như Java. Cú pháp (syntax) lập trình, đặt tên công thức và xây dựng điều khiển lưu lượng (control-flow) cơ bản của JavaScript phần lớn dựa theo ngôn ngữ lập trình Java, đó cũng là lý do tại sao JavaScript được đổi tên từ LiveScript thành JavaScript.</p> + +<p>Ngược lại với hệ thống thời gian biên dịch (compile-time) Java của các lớp được xây dựng bởi các khai báo, JavaScript hỗ trợ nền tảng hệ thống thời gian chạy<span id="result_box" lang="vi"><span class="hps"> dựa</span> <span class="hps">trên</span> <span class="hps">một</span> <span class="hps">số lượng nhỏ các</span> <span class="hps">loại</span> <span class="hps">dữ liệu</span> <span class="hps">đại diện cho</span> <span class="hps">số, boolean và dữ liệu các chuỗi. JavaScript có một mô hình ít phổ biến hơn là mô hình đối tượng</span> <span class="hps">dựa trên nguyên mẫu</span> <span class="hps">(</span></span>prototype-based) <span lang="vi"><span class="hps">thay vì</span> <span class="hps">các</span> <span class="hps">mô hình đối tượng</span> <span class="hps">dựa trên lớp (</span></span>class-based)<span lang="vi">. </span><span id="result_box" lang="vi"><span class="hps">Các</span> <span class="hps">mô hình</span> <span class="hps">dựa trên nguyên mẫu</span> <span class="hps">cung cấp</span> khả năng <span class="hps">thừa kế</span> <span class="hps">năng động</span><span>;</span> <span class="hps">nghĩa là,</span> <span class="hps">những gì được</span><span class="hps"> kế thừa có thể</span> <span class="hps">khác nhau</span> <span class="hps">cho các đối tượng</span> <span class="hps">khác nhau.</span> <span class="hps">JavaScript</span> <span class="hps">cũng hỗ trợ</span> <span class="hps">các phương thức (function)</span> không khai báo bất cứ gì ở trỏng<span class="hps">.</span> <span class="hps">Phương thức có thể</span> <span class="hps">là một trong các thuộc tính (property) của</span> <span class="hps">các đối tượng,</span> <span class="hps">t</span><span>hực thi như là một phương thức đã được định kiểu (</span></span>loosely typed methods).</p> + +<p>JavaScript là một ngôn ngữ rất tự do so với Java. Bạn có thể không cần khai báo tất cả biến (variable), lớp (class) và cả phương thức (method). Bạn không cần quan tâm cho dù phương thức đó là public, private hoặc protected, và bạn không cần phải implement interfaces. Biến, tham số (parameters), và kiểu trả về của phương thức (function return) cũng không cần phải rõ ràng.</p> + +<p>Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.</p> + +<p>In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.</p> + +<table class="standard-table"> + <caption>JavaScript so sánh với Java</caption> + <thead> + <tr> + <th scope="col">JavaScript</th> + <th scope="col">Java</th> + </tr> + </thead> + <tbody> + <tr> + <td>Hướng đối tượng (Object-oriented). Không phân biệt giữa kiểu (type) của các đối tượng (object). Tính kế thừa thông qua cơ chế nguyên mẫu (prototype), và các thuộc tính (property) cũng như phương thức có thể thêm vào bất cứ đối tượng nào một cách năng động.</td> + <td>Class-based (nền tảng lớp.).Đối tượng được thành các lớp với tất cả kế thừa thông qua hệ thống phân cấp lớp. Các lớp không thể thêm vào các thuộc tính và phương thức mới một cách năng động.</td> + </tr> + <tr> + <td>Không khai báo kiểu dữ liệu cho biến (dynamic typing).</td> + <td>Phải khai báo kiểu dữ liệu cho biến (static typing).</td> + </tr> + <tr> + <td>Không thể tự động ghi vào ổ đĩa cứng.</td> + <td>Có thể tự động ghi dữ liệu vào đĩa cứng.</td> + </tr> + </tbody> +</table> + +<p>Thêm thông tin về sự khác nhau giữa JavaScript và Java, xem chương: <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model" title="JavaScript/Guide/Details of the Object Model">Details of the object model</a>.</p> + +<h2 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript và tiêu chuẩn ECMAScript</h2> + +<p>JavaScript được tiêu chuẩn hóa tại <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — the European association for standardizing information and communication systems, Liên kết Châu Âu cho các tiêu chuẩn hóa hệ thống thông tin và truyền thông (ECMA trước đây là viết tắt cho the European Computer Manufacturers Association) cung cấp một tiêu chuẩn hóa, nền tảng ngôn ngữ lập trình mở quốc tế lên JavaScript. Phiên bản đã tiêu chuẩn hóa của JavaScript được gọi là ECMAScript, làm việc giống với cái cách mà tất cả ứng dụng đã được hỗ trợ theo tiêu chuẩn. Các công ty có thể sử dụng tiêu chuẩn ngôn ngữ mở (open standard language) để phát triển các implementation của JavaScript riêng cho họ. Tiêu chuẩn ECMAScript là tài liệu nằm trong tiêu chuẩn ECMA-262 (ECMA-262 specification) . Xem <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript </a>để biết thêm về sự khác nhau giữa các phiên bản JavaScript cũng như sự khác nhau của phiên bản tiêu chuẩn ECMAScript (ECMAScript specification editions).</p> + +<p>Tiêu chuẩn ECMA-262 cũng đã được phê duyệt bởi <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) tại ISO-16262. Bạn cũng có thể tìm tiêu chuẩn trên <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. Tiêu chuẩn ECMAScript không bao gồm các mô tả cho Document Object Model (DOM), nó được tiêu chuẩn hóa bởi <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>. DOM định nghĩa cách mà các đối tượng trong HTML tiếp xúc với các đoạn script của bạn. <span id="result_box" lang="vi"><span class="hps">Để có được một</span> <span class="hps">cảm nhận tốt hơn</span> <span class="hps">về các công nghệ</span> <span class="hps">khác nhau được</span> <span class="hps">sử dụng khi</span> <span class="hps">lập trình với</span> <span class="hps">JavaScript</span><span>, hãy tham khảo</span> <span class="hps">bài viết</span> </span><a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">tổng quan về công nghệ JavaScript</a>.</p> + +<h3 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Tài liệu JavaScript và tiêu chuẩn ECMAScript</h3> + +<p>Tiêu chuẩn ECMAScript là một tập hợp yêu cầu các việc cần thực hiện khi triển khai ECMAScript; nó rất là hữu ích nếu bạn muốn tạo ra một trình biên dịch tiêu chuẩn các tính năng của ngôn ngữ trong ECMAScript implementation hoặc bộ máy biên dịch của bạn (giống như SpiderMonkey của Firefox, hoặc v8 của Chrome).</p> + +<p>Tài liệu ECMAScript được tạo ra không dự định hỗ trợ các lập trình viên script; sử dụng tài liệu JavaScript để lấy thông tin cho việc viết scripts của bạn.</p> + +<p>Tiêu chuẩn ECMAScript sử dụng các thuật ngữ và cú pháp có thể các lập trình viên JavaScript chưa được làm quen. Mặc dù sự mô tả của ngôn ngữ có lẽ khác nhau trong ECMAScript, nhưng bản thân ngôn ngữ vẫn giữ nguyên, không thay đổi. JavaScript hỗ trợ tất cả chức năng được nêu trong tiêu chuẩn ECMAScript.</p> + +<p>Tài liệu JavaScript mô tả các khía cạnh của ngôn ngữ lập trình JavaScript, thích hợp cho các lập trình viên JavaScript sử dụng.</p> + +<h2 id="Bắt_đầu_với_JavaScript">Bắt đầu với JavaScript</h2> + +<p>Bắt đầu với JavaScript rất đơn giản: tất cả những gì bạn cần là một trình duyệt Web hiện đại. Trong các bài hướng dẫn có kèm theo một số tính năng JavaScript, mà nó chỉ chạy được ở các phiên bản trình duyệt mới nhất của Firefox, hoặc... cách tốt nhất là sử dụng một số phiên bản trình duyệt gần đây nhất của Firefox..</p> + +<p>Có 2 công cụ được xây dựng trong Firefox, nó rất hữu ích để chạy các 'thí nghiệm' với JavaScript, đó là: <strong>Web Console</strong> và <strong>Scratchpad</strong>.</p> + +<h3 id="Web_Console">Web Console</h3> + +<p><a href="/en-US/docs/Tools/Web_Console">Web Console</a> cho phép bạn thấy thông tin về trang Web đang chạy, và kèm theo một <a href="/en-US/docs/Tools/Web_Console#The_command_line_interpreter">command line</a>, với nó bạn có thể sử dụng để chạy một đoạn lệnh JavaScript trên trang Web hiện tại.</p> + +<p>Mở Web Console bằng cách chọn "Web Console" từ menu "Web Developer" (Ctrl + Shift + I), "Web Developer" nằm trong Menu chính của Firefox, nó có hình cờ lê, tên: Developer (nếu vẫn không thấy nó, bạn có thể mở menu và nhấn Customize để kéo nó ra ngoài). Sau khi mở lên, nó sẽ là 1 bảng hiển thị nằm phía dưới của cửa sổ trình duyệt. Có 1 ô nhập chạy dài dưới cùng của cửa sổ Web Console (khoanh vùng màu đỏ trong mình), nó chính là command line, với nó bạn có thể nhập vào đoạn JavaScript mà bạu muốn thực thi, và sau khi Enter thì trình duyệt sẽ chạy và trả về kết quả lên bảng Web Console nằm trên nó:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7363/web-console-commandline.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Scratchpad">Scratchpad</h3> + +<p>Web Console có thể rất hiệu quả cho việc chạy đơn lẻ từng dòng lệnh của JavaScript, bạn cũng có thể chạy những đoạn lệnh nhiều dòng với nó (Ctrl + Enter)... Nhưng có vẻ nó không được tiện lợi cho lắm! Bạn không thể lưu lại code khi sử dụng Web Console. Với các 'thí nghiệm' dài và phức tạp thì <a href="/en-US/docs/Tools/Scratchpad">Scratchpad</a> là một công cụ hiệu quả.</p> + +<p>Để mở Scratchpad, chọn "Scratchpad" từ menu "Web Developer" (Ctrl + Shift + I), "Web Developer" nằm trong Menu chính của Firefox, nó có hình cờ lê, tên: Developer (nếu vẫn không thấy nó, bạn có thể mở menu và nhấn Customize để kéo nó ra ngoài). Nó sẽ mở lên trong một cửa sổ window riêng với trình duyệt và là một trình soạn thảo mà bạn có thể sử dụng để viết và chạy JavaScript trong trình duyệt. Bạn cũng có thế lưu lại hoặc mở lên các đoạn script đó lên từ ổ đĩa.</p> + +<p>Nếu bạn chọn "Inspect", đoạn code trong cửa sổ nãy sẽ chạy trong trình duyệt và xuất kết quả trở về bảng dưới dạng comment:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7365/scratchpad.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Hello_world">Hello world</h3> + +<p>Bắt đầu với JavaScript, mở Web Console hoặc Scarthpad và viết code JavaScript hiển thị "Hello world" đầu tiên của bạn:</p> + +<pre class="brush: js">function greetMe(user) { + return "Hi " + user; +} + +greetMe("Alice"); // "Hi Alice" +</pre> + +<p>Trong trang tiếp theo, chúng tôi sẽ giới thiệu cho bạn về cú pháp và các đặc tính của ngôn ngữ JavaScript, với nó, bạn sẽ có thể viết các ứng dụng phức tạp.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</p> diff --git a/files/vi/web/javascript/guide/index.html b/files/vi/web/javascript/guide/index.html new file mode 100644 index 0000000000..d81ff019a4 --- /dev/null +++ b/files/vi/web/javascript/guide/index.html @@ -0,0 +1,124 @@ +--- +title: JavaScript Guide +slug: Web/JavaScript/Guide +tags: + - Hướng dẫn + - JavaScript +translation_of: Web/JavaScript/Guide +--- +<p>{{jsSidebar("JavaScript Guide")}}</p> + +<div class="summary"> +<p><span class="seoSummary">Tài liệu về JavaScript cung cấp cho bạn cách sử dụng <a href="/vi/docs/Web/JavaScript">JavaScript</a> và đưa ra cái nhìn tổng quan về ngôn ngữ này. Nếu muốn bắt đầu ngay với Javascript hay lập trình nói chung, hãy tham khảo các bài viết tại <a href="/vi/Learn">learning area</a>. Nếu cần thông tin đầy đủ về tính năng của ngôn ngữ này, hãy tham khảo <a href="/vi/docs/Web/JavaScript/Reference">JavaScript reference</a>.</span></p> +</div> + +<ul class="card-grid"> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Introduction">Giới thiệu</a></span> + + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction#Where_to_find_JavaScript_information">Về hướng dẫn này</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction#What_is_JavaScript">Về Javascript</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_Java">JavaScript và Java</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_the_ECMAScript_Specification">ECMAScript</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction#Getting_started_with_JavaScript">Các công cụ</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction#Hello_world">Hello World</a></p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Grammar_and_types">Ngữ pháp và các kiểu dữ liệu</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Basics">Cú pháp cơ bản & bình luận</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">Khai báo</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope">Phạm vi biến</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting">Variable hoisting</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types">Cấu trúc dữ liệu và các kiểu</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Literals">Literals</a></p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Luồng điều khiển và xử lý lỗi</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement">Xử lý trường hợp <code>if...else</code></a><br> + <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement">switch</a></code><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Exception_handling_statements"><code>try</code>/<code>catch</code>/<code>throw</code></a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Utilizing_Error_objects">Error objects</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Promises">Promises</a></p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Loops_and_iteration">Các vòng lặp</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">for</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">while</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement">do...while</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement">break</a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement">continue</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement">for..in</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for..of</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Functions">Hàm</a></span> + + <p><a href="/vi/docs/Web/JavaScript/Guide/Functions#Defining_functions">Định nghĩa hàm</a><br> + <a href="/vi/docs/Web/JavaScript/Guide/Functions#Calling_functions">Gọi hàm</a><br> + <a href="/vi/docs/Web/JavaScript/Guide/Functions#Function_scope">Phạm vi hàm</a><br> + <a href="/vi/docs/Web/JavaScript/Guide/Functions#Closures">Closures</a><br> + <a href="/vi/docs/Web/JavaScript/Guide/Functions#Using_the_arguments_object">Đối số & tham số</a><br> + <a href="/vi/docs/Web/JavaScript/Guide/Functions#Arrow_functions">Arrow functions</a></p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Expressions_and_Operators">Biểu thức và các toán tử</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">Phép gán và So sánh</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators">Các toán tử toán học</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">Các toán tử Bitwise</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators">logic</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_(ternary)_operator">Toán tử 3 ngôi</a></p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Numbers_and_dates">Numbers and dates</a></span><a href="/vi/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers">Number literals</a> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object"><code>Number</code> object</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Math_object"><code>Math</code> object</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Date_object"><code>Date</code> object</a></p> + + <p> </p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Text_formatting">Text formatting</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_literals">String literals</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_objects">Đối tượng <code>String</code></a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting#Multi-line_template_literals">Template literals</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting#Internationalization">Internationalization</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Biểu thức chính quy</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a></span> + + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object">Mảng</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Typed_Arrays">Mảng được định sẵn kiểu</a></p> + + <p> </p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Keyed_collections_and_structured_data">Keyed collections and structured data</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Map_object">Maps</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object">WeakMaps</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Set_object">Set</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakSet_object">WeakSets</a><br> + JSON</p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Working_with_Objects">Working with objects</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">Objects và các thuộc tính</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">Tạo objects</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_methods">Định nghĩa các phương thức</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Getter và setter</a><br> + </p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">Details of the object model</a></span> + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Class-based_vs._prototype-based_languages">Prototype-based OOP</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Creating_the_hierarchy">Creating object hierarchies</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Property_inheritance_revisited">Inheritance</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators and generators</a></span> + + <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators">Iterators</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">Iterables</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">Generators</a></p> + </li> + <li><span><a href="/vi/docs/Web/JavaScript/Guide/Meta_programming">Meta programming</a></span> + <p><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Meta_programming#Proxies">Proxy</a></code><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Meta_programming#Handlers_and_traps">Handlers and traps</a><br> + <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Meta_programming#Revocable_Proxy">Revocable Proxy</a><br> + <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Meta_programming#Reflection">Reflect</a></code></p> + </li> +</ul> + +<p>{{Next("Web/JavaScript/Guide/Introduction")}}</p> diff --git a/files/vi/web/javascript/guide/iterators_and_generators/index.html b/files/vi/web/javascript/guide/iterators_and_generators/index.html new file mode 100644 index 0000000000..e283bbb21d --- /dev/null +++ b/files/vi/web/javascript/guide/iterators_and_generators/index.html @@ -0,0 +1,187 @@ +--- +title: Iterators and generators +slug: Web/JavaScript/Guide/Iterators_and_Generators +translation_of: Web/JavaScript/Guide/Iterators_and_Generators +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}</div> + +<p class="summary">Việc xử lý mỗi phần tử trong một tập hợp là thao tác rất phổ biến. JavaScript cung cấp một số cách để duyệt qua một tập hợp, từ đơn giản với lệnh lặp {{jsxref("Statements/for","for")}} đến {{jsxref("Global_Objects/Array/map","map()")}} và {{jsxref("Global_Objects/Array/filter","filter()")}}. Iterators và Generators đem đến khái niệm của iteration vào nhân của ngôn ngữ và cung cấp cách để tùy biến cơ chế của vòng lặp {{jsxref("Statements/for...of","for...of")}}.</p> + +<p>Tham khảo thêm:</p> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> + <li>{{jsxref("Statements/for...of","for...of")}}</li> + <li>{{jsxref("Statements/function*","function*")}} and {{jsxref("Generator")}}</li> + <li>{{jsxref("Operators/yield","yield")}} and {{jsxref("Operators/yield*","yield*")}}</li> +</ul> + +<h2 id="Iterators">Iterators</h2> + +<p>Trong JavaScript một <strong>iterator</strong> là một object mà nó định nghĩa một trình tự và giá trị có thể trả về tiếp theo trước khi kết thúc. Một cách cụ thể hơn một iterator là một object bất kỳ mà nó cài đặt giao thức <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol">Iterator</a> với việc cài đặt phương thức next() mà trả về một object với thuộc tính: <code>value</code>, giá trị kế tiếp in chuỗi giá trị; và <code>done</code>, mà là <code>true</code> nếu giá trị cuối cùng trong chuỗi giá trị đã được sử dụng. Nếu <code>value</code> trả về cùng với thuộc tính <code>done</code>, nó là giá trị trả về bởi lệnh return trong iterator đó.</p> + +<p>Mỗi lần được tạo, một iterator có thể được duyệt tường minh bởi việc gọi lại nhiều lần phương thức <code>next()</code>. Việc duyệt qua iterator được gọi là sử dụng iterator, bởi vì nó chỉ có thể làm một lần. Sau khi giá trị kết thúc được trả về thì lần gọi <code>next()</code> luôn trả về <code>{done: true}</code>.<br> + <br> + Iterator thông dụng nhất trong JavaScript là iterator mãng, mà đơn giản là trả về mỗi giá trị trong associated array theo thứ tự. Trong khi nó thì dễ dàng tưởng tượng rằng tất cả iterators được biểu diễn như mãng, điều này không đúng. Mảng phải được cấp phát toàn bộ, nhưng iterators được sử dụng chỉ khi cần thiết và vì vậy có thể biểu diễn một chuỗi không có giới hạn kích thước, như là một dãy các số nguyên từ 0 cho đến vô cực.<br> + <br> + Sau đây là một ví dụ minh họa cho điều đó. Bạn có thể tạo ra một iterator khoảng giá trị đơn giản mà nó định nghĩa một dãy các số nguyên từ <code>start</code> (đã bao gồm) đến <code>end</code> (không bao gồm) với bước nhảy <code>step</code>. Giá trị trả về cuối cùng là kích thước của dãy giá trị mà nó đã tạo, ghi nhận trong biến iterationCount.</p> + +<pre class="brush: js">function makeRangeIterator(start = 0, end = Infinity, step = 1) { + let nextIndex = start; + let iterationCount = 0; + + const rangeIterator = { + next: function() { + let result; + if (nextIndex <= end) { + result = { value: nextIndex, done: false } + nextIndex += step; + iterationCount++; + return result; + } + return { value: iterationCount, done: true } + } + }; + return rangeIterator; +}</pre> + +<p>Việc sử dụng iterator được minh họa như trong đoạn mã sau:</p> + +<pre class="brush: js">let it = makeRangeIterator(1, 10, 2); + +let result = it.next(); +while (!result.done) { + console.log(result.value); // 1 3 5 7 9 + result = it.next(); +} + +console.log("Iterated over sequence of size: ", result.value); // 5 + +</pre> + +<div class="note"> +<p>Bạn không biết chắc một đối tượng cụ thể là một iterator hay không. Nếu bạn cần làm điều này, thì hãy dùng <a href="#Iterables">Iterables</a>.</p> +</div> + +<h2 id="Generator_functions">Generator functions</h2> + +<p>Iterator tùy biến là công cụ hữu ích, tuy nhiên việc tạo chúng đòi hỏi sự cẩn thận vì chúng ta cần phải tự quản lý trạng thái của chúng. Hàm Generator cung cấp một cách thức tốt hơn để thay thế việc đó: chúng cho phép bạn định nghĩa giải thuật duyệt bằng cách viết một hàm đơn mà sự thực thi của nó không diễn ra liên tục. Hàm Generator được viết bằng cách sử dụng cú pháp {{jsxref("Statements/function*","function*")}}. Khi gọi lần đầu, hàm generator không thực thi bất kỳ đoạn mã nào bên trong, thay vào đó nó trả về kiểu của iterator được gọi là generator. Khi một giá trị được dùng để trả về bởi lời gọi phương thức <strong>next</strong>() của generator, hàm generator thực thi cho đến khi nó bắt gặp từ khóa <strong>yield</strong>.</p> + +<p>Hàm có thể được gọi bao nhiêu lần cũng được và nó trả về một generator cho mỗi lần gọi, tuy nhiên generator có thể chỉ được duyệt một lần.<br> + <br> + Chúng ta có thể điều chỉnh ví dụ trên. Chúng ta thấy đoạn mã sau cũng thực thi cùng chức năng, nhưng nó dễ viết và dễ đọc hơn.</p> + +<pre class="brush: js">function* makeRangeIterator(start = 0, end = Infinity, step = 1) { + let iterationCount = 0; + for (let i = start; i < end; i += step) { + iterationCount++; + yield i; + } + return iterationCount; +}</pre> + +<h2 id="Iterables">Iterables</h2> + +<p>Một đối tượng là khả duyệt nếu nó định nghĩa cơ chế duyệt của nó, chẳng hạn như giá trị gì được duyệt qua trong hàm dựng {{jsxref("Statements/for...of", "for...of")}}. Một vài kiểu dựng sẳn, như {{jsxref("Array")}} hoặc {{jsxref("Map")}}, có cơ chế duyệt mặc định, trong khi những kiểu khác (như là {{jsxref("Object")}}) thì không có.</p> + +<p>Để có thể khả duyệt, một object phải cái đặt phương thức của <strong>@@iterator</strong>, nghĩa là object (hoặc đối tượng cha trong chuỗi <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">prototype</a>) phải có một thuộc tính {{jsxref("Symbol.iterator")}}.<br> + It may be possible to iterate over an iterable more than once, or only once. It is up to the programmer to know which is the case. Iterables which can iterate only once (e.g. Generators) customarily return <strong>this</strong> from their <strong>@@iterator</strong> method, where those which can be iterated many times must return a new iterator on each invocation of <strong>@@iterator</strong>.<br> + Bạn có thể cho phép duyệt qua nhiều lần, hoặc chỉ một lần. Điều này phụ thuộc vào theo yêu cầu của mỗi ứng dụng. Đối tượng khả duyệt mà chỉ duyệt qua một lần (ví dụ Generators) đơn giản là nó chỉ trả về <strong>this</strong> từ phương thức <strong>@@iterator</strong>, trong khi để khả duyệt nhiều lần bạn phải trả về một iterator mới cho mỗi lần gọi <strong>@@iterator</strong>.</p> + +<h3 id="Tự_định_nghĩa_đối_tượng_khả_duyệt">Tự định nghĩa đối tượng khả duyệt</h3> + +<p>Chúng ta có thể tự tạo đối tượng khả duyệt như sau:</p> + +<pre class="brush: js">var myIterable = { + *[Symbol.iterator]() { + yield 1; + yield 2; + yield 3; + } +} + +for (let value of myIterable) { + console.log(value); +} +// 1 +// 2 +// 3 + +or + +[...myIterable]; // [1, 2, 3] +</pre> + +<h3 id="Những_iterable_tạo_sẵn">Những iterable tạo sẵn</h3> + +<p>{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} and {{jsxref("Set")}} là những iterable đã được tạo sẵn, bởi vì đối tượng prototype của chúng đã có phương thức {{jsxref("Symbol.iterator")}}.</p> + +<h3 id="Cú_pháp_đòi_hỏi_đối_tượng_khả_duyệt">Cú pháp đòi hỏi đối tượng khả duyệt</h3> + +<p>Một vài câu lệnh và biểu thức đòi hỏi toán hạng hoặc đối số phải là đối tượng khả duyệt, ví dụ lệnh lặp {{jsxref("Statements/for...of","for-of")}}, {{jsxref("Operators/yield*","yield*")}}</p> + +<pre class="brush: js">for (let value of ['a', 'b', 'c']) { + console.log(value); +} +// "a" +// "b" +// "c" + +[...'abc']; // ["a", "b", "c"] + +function* gen() { + yield* ['a', 'b', 'c']; +} + +gen().next(); // { value: "a", done: false } + +[a, b, c] = new Set(['a', 'b', 'c']); +a; // "a" + +</pre> + +<h2 id="Generator_Cao_Cấp">Generator Cao Cấp</h2> + +<p>Generator tính toán giá trị trả ra tùy biến theo nhu cầu, nó cho phép biển diễn chuỗi giá trị một cách hiệu quả mà tốn kém để tính toán, hoặc thậm chí cho phép chuỗi giá trị vô tận như đã minh họa ở trên.<br> + </p> + +<p>The {{jsxref("Global_Objects/Generator/next","next()")}} method also accepts a value which can be used to modify the internal state of the generator. A value passed to <code>next()</code> will be treated as the result of the last <code>yield</code> expression that paused the generator.<br> + Phương thức {{jsxref("Global_Objects/Generator/next","next()")}} cũng chấp nhận một đối số mà được sử dụng để thay đổi trạng thái bên trong của generator. Một giá trị được truyền vào <code>next()</code> sẽ được dùng như kết quả của biểu thức <code>yield</code> cuối cùng khi tạm dừng generator.</p> + +<p>Here is the fibonacci generator using <code>next(x)</code> to restart the sequence:</p> + +<pre class="brush: js">function* fibonacci() { + var fn1 = 0; + var fn2 = 1; + while (true) { + var current = fn1; + fn1 = fn2; + fn2 = current + fn1; + var reset = yield current; + if (reset) { + fn1 = 0; + fn2 = 1; + } + } +} + +var sequence = fibonacci(); +console.log(sequence.next().value); // 0 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 2 +console.log(sequence.next().value); // 3 +console.log(sequence.next().value); // 5 +console.log(sequence.next().value); // 8 +console.log(sequence.next(true).value); // 0 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 2</pre> + +<p>Bạn có thể ép một generator phát sinh lỗi bằng cách gọi phương thức {{jsxref("Global_Objects/Generator/throw","throw()")}} của generator và chỉ định giá trị lỗi mà nó cần phát sinh. Lỗi này sẽ được phát sinh từ ngữ cảnh hiện tại của generator, tạo điểm mà <code>yield</code> đang tam dừng, thay vì lệnh <code>throw <em>value</em></code> như cách thông thường.</p> + +<p>Nếu lỗi không được bắt từ bên trong generator, nó sẽ được đẩy lên cấp cao hơn thông qua lời gọi hàm <code>throw()</code>, khi đó lời gọi tiếp theo tới <code>next()</code> sẽ trả về <code>done</code> với giá trị <code>true</code>.</p> + +<p>Generator có một phương thức {{jsxref("Global_Objects/Generator/return","return(value)")}} mà giá trị được truyền vào và kết thúc chính nó.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}</p> diff --git a/files/vi/web/javascript/guide/keyed_collections/index.html b/files/vi/web/javascript/guide/keyed_collections/index.html new file mode 100644 index 0000000000..491efcf1da --- /dev/null +++ b/files/vi/web/javascript/guide/keyed_collections/index.html @@ -0,0 +1,153 @@ +--- +title: Keyed collections +slug: Web/JavaScript/Guide/Keyed_collections +translation_of: Web/JavaScript/Guide/Keyed_collections +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Indexed_Collections", "Web/JavaScript/Guide/Working_with_Objects")}}</div> + +<p class="summary">Chương này sẽ giới thiệu về bộ sưu tập dữ liệu được sắp xếp theo key; <code>Map</code> và <code>Set</code> objects chứa các phần tử có thể được lặp lại theo thứ tự được thêm vào.</p> + +<h2 id="Maps">Maps</h2> + +<h3 id="Map_object">Map object</h3> + +<p>ECMAScript 2015 giới thiệu một cấu trúc dữ liệu mới để ánh xạ giá trị thành giá trị. Một đối tượng {{jsxref("Map")}} là một ánh xạ đơn giản key/value và có thể lặp lại các phần tử theo thứ tự thêm vào.</p> + +<p>Đoạn code bên dưới sẽ thể hiện các thao tác cơ bản với <code>Map</code>. Xem thêm {{jsxref("Map")}} để có thêm nhiều ví dụ và toàn bộ API. Bạn có thể sử dụng một vòng lặp {{jsxref("Statements/for...of","for...of")}} để trả về một mảng của <code>[<var>key<var>, <var>value</var>]</var></var></code> trong mỗi lần lặp.</p> + +<pre class="brush: js">let sayings = new Map(); +sayings.set('dog', 'woof'); +sayings.set('cat', 'meow'); +sayings.set('elephant', 'toot'); +sayings.size; // 3 +sayings.get('fox'); // undefined +sayings.has('bird'); // false +sayings.delete('dog'); +sayings.has('dog'); // false + +for (let [key, value] of sayings) { + console.log(key + ' goes ' + value); +} +// "cat goes meow" +// "elephant goes toot" + +sayings.clear(); +sayings.size; // 0 +</pre> + +<h3 id="Object_and_Map_compared">Object and Map compared</h3> + +<p>Thông thường, {{jsxref("Object", "objects", "", 1)}} được sử dụng để ánh xạ string thành value. Objects cũng cho phép bạn đặt key thành values, truy xuất các value, xóa các key, và kiểm tra xe có dữ liệu nào được lưu trữ trong một key. Tuy nhiên <code>Map</code> objects có một vài lợi thế hơn giúp chúng tốt hơn trong việc ánh xạ.</p> + +<ul> + <li>Các key trong một <code>Object</code> là {{jsxref("Global_Objects/String","Strings")}} hoặc {{jsxref("Global_Objects/Symbol","Symbols")}}, trong khi chúng có thể là bất kỳ giá trị nào trong một <code>Map</code>.</li> + <li>Bạn có thể lấy được <code>size</code> của một <code>Map</code> dễ dàng, trong khi bạn sẽ phải xử lý thủ công để lấy được kích thước của một <code>Object</code>.</li> + <li>Vòng lặp của các ánh xạ sẽ theo thứ tự được thêm vào của các phần tử.</li> + <li>Một <code>Object</code> có một prototype, vì thế có các giá trị mặc định của key trong ánh xạ. (Điều này có thể bỏ qua bằng cách sử dụng <code>map = Object.create(null)</code>.)</li> +</ul> + +<p>Ba mẹo dưới đây có thể giúp bạn quyết định khi nào thì sử dụng <code>Map</code> hoặc <code>Object</code>:</p> + +<ul> + <li>Sử dụng các object khi các key không được xác định cho đến khi chạy, và khi tất cả các key có cùng kiểu và tất cả các value cũng cùng kiểu.</li> + <li>Sử dụng các map nếu cần lưu trữ các giá trị có kiểu nguyên thủy làm key vì các object coi mỗi key là một string cho dù nó là một giá trị số, boolean hoặc bất kỳ giá trị có kiểu nguyên thủy nào.</li> + <li>Sử dụng các object khi có logic hoạt động trên các yếu tố riêng lẻ.</li> +</ul> + +<h3 id="WeakMap_object">WeakMap object</h3> + +<p>Đối tượng <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap">{{jsxref("WeakMap")}}</a> là một bộ sưu tập của cặp key/value trong đó các key chỉ là các đối tượng và các value có thể là bất kỳ giá trị nào. Tham chiếu đối tượng trong các key được giữ<em> yếu ớt (weakly)</em>, có nghĩa là chúng là mục tiêu của garbage collection (GC) nếu không có tham chiếu nào khác đến đối tượng nữa. Các <code>WeakMap</code> API giống với các <code>Map</code> API.</p> + +<p>Một điểm khác biệt so với các <code>Map</code> objects là các key của <code>WeakMap</code> không đếm được (tức là không có phương thức nào cung cấp cho bạn danh sách các key). Nếu có, danh sách key sẽ phụ thuộc vào trạng thái của garbage collection, đưa ra tính không xác định.</p> + +<p>Một số thông tin và ví dụ khác, xem tại "Why <em>Weak</em>Map?" trong tài liệu tham khảo {{jsxref("WeakMap")}}.</p> + +<p>Một trường hợp sử dụng các <code>WeakMap</code> objec là lưu trữ dữ liệu riêng tư cho một đối tượng hoặc ấn chi tiết thực hiện. Ví dụ sau đây từ bài đăng trên blog của Nick Fitzgerald's <a href="http://fitzgeraldnick.com/weblog/53/">"Hiding Implementation Details with ECMAScript 6 WeakMaps"</a>. Các dữ liệu và phương thức riêng bên trong object sẽ được lưu trữ trong đối tượng <code><var>privates</var></code>. Tất cả các instance và prototype lộ ra được công khai; mọi thứ khác không thể truy cập từ bên ngoài bởi vì <code><var>privates</var></code> không được xuất từ mô-đun.</p> + +<pre class="brush: js">const privates = new WeakMap(); + +function Public() { + const me = { + // Private data goes here + }; + privates.set(this, me); +} + +Public.prototype.method = function () { + const me = privates.get(this); + // Do stuff with private data in `me`... +}; + +module.exports = Public;</pre> + +<h2 id="Sets">Sets</h2> + +<h3 id="Set_object">Set object</h3> + +<p>Các {{jsxref("Set")}} object là bộ sưu tập các giá trị. Bạn có thể lặp các phần tử theo thứ tự được thêm vào. Một giá trị trong một <code>Set</code> chỉ có thể xuất hiện một lần; nó là duy nhất trong <code>Set</code>.</p> + +<p>Đoạn code dưới đây là các thao tác cơ bản với <code>Set</code>. Xem thêm tại tài liệu tham khảo {{jsxref("Set")}} để có thêm nhiều ví dụ và toàn bộ các API.</p> + +<pre class="brush: js">let mySet = new Set(); +mySet.add(1); +mySet.add('some text'); +mySet.add('foo'); + +mySet.has(1); // true +mySet.delete('foo'); +mySet.size; // 2 + +for (let item of mySet) console.log(item); +// 1 +// "some text" +</pre> + +<h3 id="Converting_between_Array_and_Set">Converting between Array and Set</h3> + +<p>Bạn có thể tạo một {{jsxref("Array")}} từ một Set bằng cách sử dụng {{jsxref("Array.from")}} hoặc <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a>. Ngoài ra, hàm khởi tạo <code>Set</code> cho phép chuyển đổi một <code>Array</code> theo một hướng khác.</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> Hãy nhớ rằng các <code>Set</code> object lưu trữ các <em>giá trị duy nhất</em>—vì thế bất kỳ phần tử nào trùng lặp trong Array sẽ bị loại bỏ khi chuyển đổi!</p> +</div> + +<pre class="brush: js">Array.from(mySet); +[...mySet2]; + +mySet2 = new Set([1, 2, 3, 4]); +</pre> + +<h3 id="Array_and_Set_compared">Array and Set compared</h3> + +<p>Thông thường, một tập hợp các phần tử được lưu trữ trong mảng trong JavaScript trong nhiều tính huống. Tuy nhiên, <code>Set</code> object có một vài điểm lợi thế sau:</p> + +<ul> + <li>Xóa bỏ các phẩn tử trong mảng theo giá trị (<code>arr.splice(arr.indexOf(val), 1)</code>) rất chậm.</li> + <li><code>Set</code> object cho phép bạn xóa bỏ các phần tử theo giá trị của chúng. Trong khi đó một mảng, bạn sẽ phải dùng phương thức <code>splice</code> dựa theo index của phần tử.</li> + <li>Giá trị {{jsxref("NaN")}} không thể được tìm thất với <code>indexOf</code> trong một mảng.</li> + <li>Các <code>Set</code> object lưu trữ các giá trị duy nhất. Bạn không cần phải thao tác thủ công để theo dõi các giá trị bị trùng lặp.</li> +</ul> + +<h3 id="WeakSet_object">WeakSet object</h3> + +<p>Các <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap">{{jsxref("WeakSet")}}</a> object là bộ sưu tập các đối tượng. Một đối tượng trong <code>WeakSet</code> chỉ xuất hiện một lần. Nó là duy nhất trong bộ sưu tập <code>WeakSet</code>, và các đối tượng đó không thể đếm được.</p> + +<p>Những điểm khác biệt chính so với {{jsxref("Set")}} object:</p> + +<ul> + <li>Khác với <code>Sets</code>, <code>WeakSets</code> là <strong>bộ sưu tập các đối tượng</strong> và không phải bất kỳ giá trị của bất kỳ kiểu nào.<strong> </strong></li> + <li><code>WeakSet</code> là <em>yếu ớt (weak)</em>: Tham chiếu tới đối tượng trong bộ sưu tập được tổ chức <em>yếu ớt </em>(weakly). Nếu không có tham chiếu nào khác tới đối tượng được lưu trữ trong <code>WeakSet</code>, chúng có thể bị thu thập bởi garbage collected. Điều này có nghĩa là không có danh sách các đối tượng đang được lưu trữ trong bộ sưu tập. <code>WeakSets</code> không thể đếm được.</li> +</ul> + +<p>Các trường hợp sử dụng các <code>WeakSet</code> object bị hạn chế. Chúng sẽ không rò rỉ bộ nhớ, vì thế nó có thể an toàn khi sử dụng các phần tử DOM làm khóa và đánh dấu chúng cho mục đích theo dõi.</p> + +<h2 id="Key_and_value_equality_of_Map_and_Set">Key and value equality of Map and Set</h2> + +<p>So sánh bằng nhau của các key của các <code>Map</code> object và value của các <code>Set</code> object dựa trên "<a href="https://tc39.github.io/ecma262/#sec-samevaluezero">same-value-zero algorithm</a>":</p> + +<ul> + <li>So sánh bằng nhau làm việc giống như so sánh bằng toán tử <code>===</code>.</li> + <li><code>-0</code> và<code>+0</code> được coi là bằng nhau.</li> + <li>{{jsxref("NaN")}} được coi là bằng chính nó (trái với <code>===</code>).</li> +</ul> + +<p>{{PreviousNext("Web/JavaScript/Guide/Indexed_Collections", "Web/JavaScript/Guide/Working_with_Objects")}}</p> diff --git a/files/vi/web/javascript/guide/loops_and_iteration/index.html b/files/vi/web/javascript/guide/loops_and_iteration/index.html new file mode 100644 index 0000000000..5ad3581fba --- /dev/null +++ b/files/vi/web/javascript/guide/loops_and_iteration/index.html @@ -0,0 +1,348 @@ +--- +title: Loops and iteration +slug: Web/JavaScript/Guide/Loops_and_iteration +translation_of: Web/JavaScript/Guide/Loops_and_iteration +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}</div> + +<p class="summary">Vòng lặp giúp thực hiện một hành động nhiều lần một cách nhanh chóng và đơn giản. Chương <a href="/en-US/docs/Web/JavaScript/Guide">Hướng dẫn JavaScript</a> này giới thiệu về các câu lệnh lặp trong JavaScript.</p> + +<p>Hãy tưởng tượng vòng lặp giống như phiên bản vi tính của trò chơi mà bạn bảo một người đi X bước sang một hướng rồi đi Y bước sang một hướng khác; chẳng hạn, ý tưởng trò "Tiến 5 bước về phía Đông" có thể được biểu diễn dưới dạng vòng lặp như sau:</p> + +<pre class="brush: js">var step; +for (let step = 0; step < 5; step++) { + // Chạy 5 lần, với giá trị chạy từ 0 đến 4. + console.log('Walking east one step'); +} +</pre> + +<p>Có nhiều kiểu vòng lặp khác nhau, nhưng tất cả đều thực hiện cùng một việc: làm lại một hành động trong số lần nhất định (số lần đó có thể là 0). Mỗi vòng lặp có các cơ chế khác nhau, tương ứng với đó là sự khác nhau giữa cách xác định điểm bắt đầu và kết thúc của vòng lặp. Tuỳ theo trường hợp xác định mà lựa kiểu vòng lặp cho phù hợp..</p> + +<p>Các lệnh lặp trong JavaScript là:</p> + +<ul> + <li>{{anch("for statement")}}</li> + <li>{{anch("do...while statement")}}</li> + <li>{{anch("while statement")}}</li> + <li>{{anch("labeled statement")}}</li> + <li>{{anch("break statement")}}</li> + <li>{{anch("continue statement")}}</li> + <li>{{anch("for...in statement")}}</li> + <li>{{anch("for...of statement")}}</li> +</ul> + +<h2 id="Lệnh_for">Lệnh <code>for</code></h2> + +<p>Vòng lặp {{jsxref("statements/for","for")}} thực hiện liên tục cho tới khi điều kiện ban đầu trả về false. Vòng <code>for</code> trong JavaScript tương tự như vòng <code>for</code> trong Java hoặc C. Lệnh <code>for</code> có dạng như sau:</p> + +<pre class="syntaxbox">for ([biểu_thức_khởi_tạo]; [điều_kiện]; [biểu_thức_tăng_tiến]) + lệnh +</pre> + +<p>Vòng lặp <code>for</code> thực thi như sau:</p> + +<ol> + <li>Biểu thức khởi tạo (<code>biểu_thức_khởi_tạo</code>), nếu có, được thực thi. Biểu thức này thường khởi tạo một hoặc nhiều biến đếm cho vòng lặp, nhưng cú pháp của nó vẫn có thể tạo ra biểu thức có độ phức tạp. Biểu thức này còn có thể khai báo biến.</li> + <li>Biểu thức điều kiện (<code>điều_kiện</code>) được tính toán. Nếu giá trị của <code>điều_kiện</code> trả về true, các lệnh trong vòng lặp được thực thi. Nếu giá trị của <code>điều_kiện</code> trả về false, vòng lặp <code>for</code> bị dừng lại. Nếu biểu thức <code>điều_kiện</code> bị khuyết (bỏ qua không đặt), điều kiện sẽ được gán giả định là true.</li> + <li><code>lệnh</code> sẽ được thực thi. Để thực thi nhiều lệnh, dùng khối lệnh (<code>{ ... }</code>) để gom nhóm các lệnh này.</li> + <li>Nếu không có lỗi nào xảy ra sau khi thực thi lệnh, biểu thức cập nhật (<code>biểu_thức_tăng_tiến</code>) được thực thi.</li> + <li>Quay lại bước 2.</li> +</ol> + +<h3 id="Ví_dụ"><strong>Ví dụ</strong></h3> + +<p>Hàm dưới đây chứa lệnh <code>for</code> đếm số option được chọn trong danh sách cuộn (phần tử {{HTMLElement("select")}} cho phép chọn nhiều). Lệnh <code>for</code> khai báo biến <code>i</code> và khởi tạo cho nó là 0. Điều kiện kiểm tra <code>i</code> có nhỏ hơn số option mà phần tử <code><select></code> sở hữu hay không, nếu thoả mãn điều kiện, chương trình sẽ chạy vào lệnh <code>if</code>, và tăng <code>i</code> thêm một.</p> + +<pre class="brush: html"><form name="selectForm"> + <p> + <label for="musicTypes">Choose some music types, then click the button below:</label> + <select id="musicTypes" name="musicTypes" multiple="multiple"> + <option selected="selected">R&B</option> + <option>Jazz</option> + <option>Blues</option> + <option>New Age</option> + <option>Classical</option> + <option>Opera</option> + </select> + </p> + <p><input id="btn" type="button" value="How many are selected?" /></p> +</form> + +<script> +function howMany(selectObject) { + var numberSelected = 0; + for (var i = 0; i < selectObject.options.length; i++) { + if (selectObject.options[i].selected) { + numberSelected++; + } + } + return numberSelected; +} + +var btn = document.getElementById('btn'); +btn.addEventListener('click', function() { + alert('Number of options selected: ' + howMany(document.selectForm.musicTypes)); +}); +</script> + +</pre> + +<h2 id="Lệnh_do...while">Lệnh <code>do...while</code></h2> + +<p>Lệnh {{jsxref("statements/do...while", "do...while")}} thực hiện liên tục cho tới khi điều kiện xác định trả về false. Lệnh <code>do...while</code> có dạng như sau:</p> + +<pre class="syntaxbox">do + lệnh +while (điều_kiện); +</pre> + +<p><code>lệnh</code> luôn được thực thi một lần trước khi kiểm tra điều kiện (và rồi cứ thế cho tới khi điều kiện trả về false). Để thực thi nhiều lệnh, dùng khối lệnh (<code>{ ... }</code>) để gom nhóm các câu lệnh. Nếu <code>điều_kiện</code> trả về true, lệnh lại được thực thi một lần nữa. Sau mỗi lần thực thi, chương trình kiểm tra lại điều kiện. Khi điều kiện trả về false, chương trình dừng thực thi vòng lặp và truyền điều khiển xuống lệnh liền sau vòng <code>do...while</code>.</p> + +<h3 id="Ví_dụ_2"><strong>Ví dụ</strong></h3> + +<p>Trong ví dụ sau, lặp <code>do</code> lặp ít nhất một lần và tái duyệt cho tới khi <code>i</code> không nhỏ hơn 5.</p> + +<pre class="brush: js">var i = 0; +do { + i += 1; + console.log(i); +} while (i < 5);</pre> + +<h2 id="Lệnh_while">Lệnh <code>while</code></h2> + +<p>Lệnh {{jsxref("statements/while","while")}} thực thi các lệnh bên trong nó ngay khi điều kiện xác định trả về true. Lệnh <code>while</code> có dạng như sau:</p> + +<pre class="syntaxbox">while (điều_kiện) + lệnh +</pre> + +<p>Nếu điều kiện trả về false, chương trình sẽ ngừng thực thi <code>lệnh</code> bên trong vòng lặp và truyền điều khiển xuống lệnh liền sau vòng lặp.</p> + +<p>Chương trình kiểm tra điều kiện trước khi thực thi <code>lệnh</code> bên trong. Nếu điều kiện trả về true, <code>lệnh</code> sẽ được thực thi và kiểm tra lại điều kiện. Nếu điều kiện trả về false, ngừng thực thi và truyền điều khiển xuống lệnh liền sau vòng lặp <code>while</code>.</p> + +<p>Để thực thi nhiều lệnh, dùng khối lệnh ({ ... }) để gom nhóm các câu lệnh.</p> + +<h3 id="Ví_dụ_1"><strong>Ví dụ 1</strong></h3> + +<p>Vòng <code>while</code> lặp lại cho tới khi <code>n</code> nhỏ hơn 3:</p> + +<pre class="brush: js">var n = 0; +var x = 0; +while (n < 3) { + n++; + x += n; +} +</pre> + +<p>Ứng với mỗi lần lặp, tăng <code>n</code> thêm một và cộng giá trị đó vào <code>x</code>. Bởi vậy, <code>x</code> và <code>n</code> có giá trị như sau:</p> + +<ul> + <li>Sau lần lặp thứ nhất: <code>n</code> = 1 và <code>x</code> = 1</li> + <li>Sau lần lặp thứ hai: <code>n</code> = 2 và <code>x</code> = 3</li> + <li>Sau lần lặp thứ ba: <code>n</code> = 3 và <code>x</code> = 6</li> +</ul> + +<p>Sau khi hoàn thành lần lặp thứ ba, điều kiện <code>n < 3</code> không còn trả về true nữa nên vòng lặp bị kết thúc.</p> + +<h3 id="Ví_dụ_2_2"><strong>Ví dụ 2</strong></h3> + +<p>Hãy tránh lặp vô hạn. Hãy đảm bảo rằng điều kiện của vòng lặp sẽ dần trả về false; bằng không, vòng lặp sẽ không bao giờ kết thúc. Lệnh trong vòng lặp <code>while</code> dưới đây được thực thi mãi mãi vì điều kiện không bao giờ trả về false:</p> + +<pre class="brush: js">while (true) { + console.log('Hello, world!'); +}</pre> + +<h2 id="Lệnh_gán_nhãn">Lệnh gán nhãn</h2> + +<p>{{jsxref("statements/label","label")}} tạo ra một lệnh đi kèm với một định danh, thông qua định danh giúp bạn tham chiếu tới nó từ những nơi khác trong chương trình của bạn. Chẳng hạn, bạn có thể dùng nhãn để định danh một vòng lặp, rồi dùng lệnh <code>break</code> hoặc <code>continue</code> để chương trình xác định có nên dừng hay tiếp tục thực thi vòng lặp hay không.</p> + +<p>Cú pháp của lệnh gán nhãn có dạng như sau:</p> + +<pre class="syntaxbox">nhãn : + lệnh +</pre> + +<p>Giá trị của <code><em>nhãn</em></code> có thể là định danh JavaScript bất kỳ nhưng không phải từ dành riêng (tên biến, tên hàm hoặc nhãn khác). <code><em>lệnh</em></code> được gán với nhãn có thể là bất kỳ lệnh nào.</p> + +<h3 id="Ví_dụ_3"><strong>Ví dụ</strong></h3> + +<p>Trong ví dụ này, nhãn <code>markLoop</code> giúp định danh cho một vòng lặp <code>while</code>.</p> + +<pre class="brush: js">markLoop: +while (theMark == true) { + doSomething(); +}</pre> + +<h2 id="Lệnh_break">Lệnh <code>break</code></h2> + +<p>Dùng lệnh {{jsxref("statements/break","break")}} để kết thúc vòng lặp, kết thúc <code>switch</code>, hoặc liên hợp với một lệnh được gán nhãn.</p> + +<ul> + <li>Khi dùng <code>break</code> không kèm với nhãn, chương trình kết thúc ngay tức thì vòng <code>while</code>, <code>do-while</code>, <code>for</code>, hoặc <code>switch</code> trong cùng bọc lệnh <code>break</code> và truyền điều khiển xuống lệnh liền sau.</li> + <li>Khi dùng <code>break</code> kèm với nhãn, nó sẽ chấm dứt việc thực thi lệnh được gắn nhãn đó.</li> +</ul> + +<p>Cú pháp lệnh <code>break</code> có dạng như sau:</p> + +<pre class="syntaxbox">break; +break [<em>nhãn</em>]; +</pre> + +<p>Kiểu cú pháp đầu tiên kết thúc vòng lặp trong cục bao bọc hoặc <code>switch</code>; kiểu thứ hai kết thúc lệnh gắn với nhãn.</p> + +<h3 id="Ví_dụ_1_2"><strong>Ví dụ</strong> <strong>1</strong></h3> + +<p>Trong ví dụ sau, lệnh lặp sẽ lặp qua từng phần tử của mảng (thông qua chỉ mục của từng phần tử) cho tới khi gặp phần tử có giá trị bằng <code>theValue</code>:</p> + +<pre class="brush: js">for (var i = 0; i < a.length; i++) { + if (a[i] == theValue) { + break; + } +}</pre> + +<h3 id="Ví_dụ_2_Áp_dụng_break_cho_nhãn"><strong>Ví dụ 2: </strong>Áp dụng break cho nhãn</h3> + +<pre class="brush: js">var x = 0; +var z = 0; +labelCancelLoops: while (true) { + console.log('Outer loops: ' + x); + x += 1; + z = 1; + while (true) { + console.log('Inner loops: ' + z); + z += 1; + if (z === 10 && x === 10) { + break labelCancelLoops; + } else if (z === 10) { + break; + } + } +} +</pre> + +<h2 id="Lệnh_continue">Lệnh <code>continue</code></h2> + +<p>Lệnh {{jsxref("statements/continue","continue")}} có thể dùng để tái duyệt các vòng <code>while</code>, <code>do-while</code>, <code>for</code>, hoặc <code>label</code>.</p> + +<ul> + <li>Khi dùng <code>continue</code> không kèm theo label, chương trình ngừng thực thi lần lặp hiện tại của vòng <code>while</code>, <code>do-while</code>, hoặc <code>for</code> gần nhất bọc lệnh <code>continue</code> và tiếp tục thực thi lần lặp tiếp theo. Trái với lệnh <code>break</code>, <code>continue</code> không dừng vòng lặp hoàn toàn. Trong vòng lặp <code>while</code>, chương trình nhảy về đoạn xét điều kiện. Trong vọng lặp <code>for</code>, chương trình nhảy tới <code>biểu_thức_tăng_tiến</code>.</li> + <li>Khi dùng <code>continue</code> có kèm theo label, lệnh <code>continue</code> sẽ áp dụng cho vòng lặp được gán nhãn đó.</li> +</ul> + +<p>Cú pháp của lệnh <code>continue</code> có dạng như sau:</p> + +<pre class="syntaxbox">continue [<em>label</em>]; +</pre> + +<h3 id="Ví_dụ_1_3"><strong>Ví dụ 1</strong></h3> + +<p>Trong ví dụ sau, vòng <code>while</code> với lệnh <code>continue</code> thực thi khi giá trị của <code>i</code> bằng 3. Thế nên, <code>n</code> sẽ có giá trị là 1, 3, 7 và 12.</p> + +<pre class="brush: js">var i = 0; +var n = 0; +while (i < 5) { + i++; + if (i == 3) { + continue; + } + n += i; + console.log(n); +} +//1,3,7,12 + + +var i = 0; +var n = 0; +while (i < 5) { + i++; + if (i == 3) { + // continue; + } + n += i; + console.log(n); +} +// 1,3,6,10,15 +</pre> + +<h3 id="Ví_dụ_2_3"><strong>Ví dụ 2</strong></h3> + +<p>Lệnh nhãn <em><code>checkiandj</code> </em>chứa nhãn <em><code>checkj</code></em>. Nếu chương trình chạy tới <code>continue</code>, chương trình sẽ ngừng thực hiện lần lặp hiện tại của <em><code>checkj</code></em><em> </em>và bắt đầu thực hiện lần lặp kế tiếp. Mỗi khi chạy tới <code>continue</code>, <em><code>checkj</code> </em>tái duyệt cho tới khi biểu thức điều kiện của nó trả về <code>false</code>. Khi <code>false</code> được trả về, phần còn lại của lệnh <em><code>checkiandj</code></em><em> </em>được hoàn thành, và <em><code>checkiandj</code></em><em> </em>tái duyệt cho tới khi điều kiện của nó trả về <code>false</code>. Khi <code>false</code> được trả về, chương trình tiếp tục thực thi lệnh liền sau <em><code>checkiandj</code></em>.</p> + +<p>Nếu <code>continue</code> gắn với nhãn <em><code>checkiandj</code></em>, chương trình sẽ tiếp tục ở đầu lệnh <em><code>checkiandj</code></em><em> </em>.</p> + +<pre class="brush: js">var i = 0; +var j = 10; +checkiandj: + while (i < 4) { + console.log(i); + i += 1; + checkj: + while (j > 4) { + console.log(j); + j -= 1; + if ((j % 2) == 0) { + continue checkj; + } + console.log(j + ' is odd.'); + } + console.log('i = ' + i); + console.log('j = ' + j); + }</pre> + +<h2 id="Lệnh_for...in">Lệnh <code>for...in</code></h2> + +<p>Lệnh {{jsxref("statements/for...in","for...in")}} lặp một biến (variable) đã được xác định trước, qua mọi thuộc tính có thể đếm được (enumerable properties) của đối tượng (object). Với từng phần tử riêng biệt, JavaScript thực thi các câu lệnh mà bạn định sẵn. Lệnh <code>for...in</code> có dạng như sau:</p> + +<pre class="syntaxbox">for (variable in object) + statement +</pre> + +<h3 id="Ví_dụ_4"><strong>Ví dụ</strong></h3> + +<p>Hàm sau nhận vào tham số là một object và tên của object đó. Sau đó nó lặp qua mọi thuộc tính của object, với mỗi lần lặp nó trả về một chuỗi ký tự liệt kê các tên thuộc tính và giá trị của chúng.</p> + +<pre class="brush: js">function dump_props(obj, obj_name) { + var result = ''; + for (var i in obj) { + result += obj_name + '.' + i + ' = ' + obj[i] + '<br>'; + } + result += '<hr>'; + return result; +} +</pre> + +<p>Chẳng hạn với object <code>car</code> có thuộc tính là <code>make</code> và <code>model</code>, <code>result</code> sẽ là:</p> + +<pre class="brush: js">car.make = Ford +car.model = Mustang +</pre> + +<h3 id="Mảng"><strong>Mảng</strong></h3> + +<p>Mặc dù có thể dùng cách này để lặp qua từng phần tử của mảng {{jsxref("Array")}}, lệnh <code>for...in</code> sẽ trả về tên của thuộc tính mà người dùng tự định nghĩa kèm theo chỉ mục của mảng.</p> + +<p>Bởi vậy, tốt hơn hết hãy sử dụng cách truyền thống là dùng vòng lặp {{jsxref("statements/for","for")}} với chỉ mục dạng số để lặp qua từng phần tử của mảng, bởi lệnh <code>for...in</code> còn lặp qua cả thuộc tính mà người dùng tự định nghĩa (chẳng hạn như khi thêm một thuộc tính vào mảng, sẽ có ví dụ ở phía dưới).</p> + +<h2 id="for...of_statement"><code>for...of</code> statement</h2> + +<p>Lệnh {{jsxref("statements/for...of","for...of")}} tạo ra một vòng lặp, áp dụng với các <a href="/en-US/docs/Web/JavaScript/Guide/iterable">đối tượng khả duyệt</a> (iterable object) (bao gồm {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("functions/arguments","arguments")}} object, v.v...), và gọi lên một hook lặp tùy chỉnh (custom iteration hook) với các câu lệnh sẽ được thực thi cho <strong>giá trị</strong> của từng thuộc tính.</p> + +<pre class="syntaxbox">for (<em>variable</em> of <em>object</em>) + <em>statement</em> +</pre> + +<p>Ví dụ sau chỉ ra sự khác biệt giữa hai vòng lặp: <code>for...of</code> và {{jsxref("statements/for...in","for...in")}}. Trong khi <code>for...in</code> lặp qua tên thuộc tính, <code>for...of</code> lặp qua giá trị thuộc tính:</p> + +<pre class="brush:js">var arr = [3, 5, 7]; +arr.foo = 'hello'; + +for (var i in arr) { + console.log(i); // logs "0", "1", "2", "foo" +} + +for (var i of arr) { + console.log(i); // logs 3, 5, 7 +} +</pre> + +<p>{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}</p> diff --git a/files/vi/web/javascript/guide/numbers_and_dates/index.html b/files/vi/web/javascript/guide/numbers_and_dates/index.html new file mode 100644 index 0000000000..a48afbbb89 --- /dev/null +++ b/files/vi/web/javascript/guide/numbers_and_dates/index.html @@ -0,0 +1,385 @@ +--- +title: Numbers and dates +slug: Web/JavaScript/Guide/Numbers_and_dates +translation_of: Web/JavaScript/Guide/Numbers_and_dates +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</div> + +<p>Chương này giới thiệu những khái niệm, đối tượng và hàm được sử dụng để làm việc và tính toán với giá trị số và ngày tháng trong JavaScript. Nó bao gồm việc sử dụng những con số được viết dưới dạng những hệ cơ số khác nhau như là hệ thập phân, hệ nhị phân và hệ thập lục phân, cũng như việc sử dụng đối tượng toàn cục {{jsxref("Math")}} để thực hiện các phép toán số học.</p> + +<h2 id="Con_Số_Numbers">Con Số (Numbers)</h2> + +<p>Trong JavaScript, tất cả các con số được cài đặt theo <a class="external external-icon" href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">double-precision 64-bit binary format IEEE 754</a> (ví dụ: một số bắt đầu từ ±2<sup>−1022</sup> and ±2<sup>+1023</sup>, hoặc là khoảng ±10<sup>−308</sup> to ±10<sup>+308</sup>, với độ chính xác 53 bits sau dấu phẩy). Số nguyên lớn nhất có thể là ±2<sup>53 </sup>− 1. Để có thể biểu diễn số thực dấu chấm động, ta có thể dùng ba ký hiệu <code>+</code>{{jsxref("Infinity")}}, <code>-</code>{{jsxref("Infinity")}}, and {{jsxref("NaN")}} (not-a-number). Xem thêm trong <a href="/en-US/docs/Web/JavaScript/Data_structures">JavaScript data types and structures</a> về những kiểu sơ cấp trong JavaScript.</p> + +<div class="blockIndicator note"> +<p><strong>Lưu Ý:</strong> Không có kiểu cụ thể cho số nguyên trong JavaScript, mặc dù kiểu {{jsxref("BigInt")}} cho phép biểu diễn số nguyên mà có giá trị rất lớn. Nhưng cần cẩn thận khi dùng <code>BigInt</code>, ví dụ, bạn có không thể kết hợp giá trị <code>BigInt</code> và {{jsxref("Number")}} trong cùng một biểu thức, và bạn cũng không thể sử dụng {{jsxref("Math")}} với giá trị <code>BigInt</code>.</p> +</div> + +<p>Bạn có thể sử dụng bốn loại literal để tạo số: thập phân, nhị phân, bát phân và thập lục phân.</p> + +<h3 id="Số_thập_phân">Số thập phân</h3> + +<pre class="brush: js">1234567890 +42 + +// Cẩn thận với số bắt đầu bằng số không: + +0888 // 888 trong hệ thập phân +0777 // được xem như là số bát phân trong chế độ non-strict (và có giá trị là 511 trong hệ thập phân) +</pre> + +<p>Lưu ý literal thập phân có thể bắt đầu bằng số zero (0) được theo sau là những số thập phân, nhưng nếu mọi chữ số sau số 0 nhỏ hơn 8, thì nó hiểu nhầm như là hệ bát phân.</p> + +<h3 id="Số_nhị_phân">Số nhị phân</h3> + +<p>Cú pháp của hệ nhị phân bắt đầu bằng chữ số 0 theo sau là "B" hoặc "b" (<code>0b</code> or <code>0B</code>). Nếu các chữ số theo sau <code>0b</code> không phải là 0 hoặc 1, thì lỗi <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> sẽ phát sinh như sau "Missing binary digits after 0b".</p> + +<pre class="brush: js">var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 +var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040 +var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre> + +<h3 id="Số_bát_phân">Số bát phân</h3> + +<p>Số bát phân bắt đầu bằng số 0. Nếu chữ số theo sau số <code>0</code> không nắm trong khoảng từ 0 đến 7, thì số đó sẽ được hiểu là số thập phân.</p> + +<pre class="brush: js">var n = 0755; // 493 +var m = 0644; // 420 +</pre> + +<p>Trong chế độ strict trong ECMAScript 5 ngăn cấm cú pháp hệ bát phân. Cú pháp hệ bát phân không nằm trong đặc tả của ECMAScript 5, nhưng nó được hỗ trợ bởi tất cả các trình duyệt bằng cách đặt tiền tố 0: <code>0644 === 420</code> and<code>"\045" === "%"</code>. Trong ECMAScript 2015 (ES6), số bát phân được hỗ trợ nếu chúng bắt đầu bằng <code>0o</code>, ví dụ:</p> + +<pre class="brush: js">var a = 0o10; // ES2015: 8 +</pre> + +<h3 id="Số_thập_lục_phân">Số thập lục phân</h3> + +<p>Cú pháp của số thập lục phân được bắt đầu bằng 0 và theo sau là "x" hoặc "X" (<code>0x</code> or <code>0X)</code>. Nếu các chữ số theo sau 0x nằm ngoài khoảng giá trị (0123456789ABCDEF), Lỗi <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> sẽ phát sinh: "Identifier starts immediately after numeric literal".</p> + +<pre class="brush: js">0xFFFFFFFFFFFFFFFFF // 295147905179352830000 +0x123456789ABCDEF // 81985529216486900 +0XA // 10 +</pre> + +<h3 id="Số_mũ">Số mũ</h3> + +<pre class="brush: js">1E3 // 1000 +2e6 // 2000000 +0.1e2 // 10</pre> + +<h2 id="Number_object"><code>Number</code> object</h2> + +<p>{{jsxref("Number")}} object có những thuộc tính có giá trị là những hằng kiểu số, như giá trị lớn nhất, not-a-number, và vô cực. Bạn không thể thay đổi những giá trị của những thuộc tính này và bạn sử dụng nó như sau:</p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<p>Bạn luôn phải tham chiếu đến những thuộc tính được định nghĩa sẳn của <code>Number</code> object như trên, và không thể truy xuất qua giá trị số mà bạn tạo ra.</p> + +<p>Bảng sau tổng hợp những thuộc tính của <code>Number</code> object.</p> + +<table class="standard-table"> + <caption>Thuộc tính của <code>Number</code></caption> + <thead> + <tr> + <th scope="col">Thuộc tính</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.MAX_VALUE")}}</td> + <td>Số lớn nhất có thể gán (<code>±1.7976931348623157e+308</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.MIN_VALUE")}}</td> + <td>Số nhỏ nhất có thể gán (<code>±5e-324</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.NaN")}}</td> + <td>Special "not a number" value<br> + Giá trị đặc biệt để mô tả "không phải là số"</td> + </tr> + <tr> + <td>{{jsxref("Number.NEGATIVE_INFINITY")}}</td> + <td>Giá trị số âm vô định; được về khi vượt quá giá trị có thể tính toán</td> + </tr> + <tr> + <td>{{jsxref("Number.POSITIVE_INFINITY")}}</td> + <td>Giá trị số dương vô định; được về khi vượt quá giá trị có thể tính toán</td> + </tr> + <tr> + <td>{{jsxref("Number.EPSILON")}}</td> + <td>Sự khác nhau giữa <code>1</code> và giá trị nhỏ nhất lớn hơn <code>1</code> mà có thể được biểu diễn là một số<br> + {{jsxref("Number")}} (<code>2.220446049250313e-16</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.MIN_SAFE_INTEGER")}}</td> + <td>Số nguyên được an toàn nhỏ nhất trong JavaScript (−2<sup>53</sup> + 1, or <code>−9007199254740991</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.MAX_SAFE_INTEGER")}}</td> + <td>Số nguyên dương an toàn lớn nhất trong JavaScript (+2<sup>53</sup> − 1, or <code>+9007199254740991</code>)</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Phương thức của <code>Number</code></caption> + <thead> + <tr> + <th>Phương thức</th> + <th>Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.parseFloat()")}}</td> + <td>Phân tích giá trị chuỗi và trả vể một giá trị số thực.<br> + Giống như hàm toàn cục {{jsxref("parseFloat", "parseFloat()")}}.</td> + </tr> + <tr> + <td>{{jsxref("Number.parseInt()")}}</td> + <td>Phân tích giá trị kiểu chuỗi và trả về giá trị số nguyên dựa trên cơ số chỉ định.<br> + Cũng giống như hàm toàn cục {{jsxref("parseInt", "parseInt()")}} function.</td> + </tr> + <tr> + <td>{{jsxref("Number.isFinite()")}}</td> + <td>Xác định giá trị được truyền vào có phải là một số xác đinh.</td> + </tr> + <tr> + <td>{{jsxref("Number.isInteger()")}}</td> + <td>Xác định giá trị truyền vào có phải là một số nguyên.</td> + </tr> + <tr> + <td>{{jsxref("Number.isNaN()")}}</td> + <td>Xác định giá trị truyền vào là {{jsxref("Global_Objects/NaN", "NaN")}}. Đây là phiên bản cải tiến của {{jsxref("Global_Objects/isNaN", "isNaN()")}}.</td> + </tr> + <tr> + <td>{{jsxref("Number.isSafeInteger()")}}</td> + <td>Xác định giá trị truyền vào là một số nguyên an toàn.</td> + </tr> + </tbody> +</table> + +<p><code>Number</code> prototype cung cấp những phương thức để lấy thông tin từ những đối tượng <code>Number</code> dưới nhiều định dạng. Bảng sau đây tổng hợp những phương thức của <code>Number.prototype</code>.</p> + +<table class="standard-table"> + <caption>Những phương thức của <code>Number.prototype</code></caption> + <thead> + <tr> + <th scope="col">Phương thức</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.toExponential", "toExponential()")}}</td> + <td>Trả về một chuỗi biểu diễn một số theo dạng lũy thừa.</td> + </tr> + <tr> + <td>{{jsxref("Number.toFixed", "toFixed()")}}</td> + <td>Trả về một chuỗi biểu diễn một số theo dạng số thập phân, với phần thập phân cố định.</td> + </tr> + <tr> + <td>{{jsxref("Number.toPrecision", "toPrecision()")}}</td> + <td>Trả về một chuỗi biểu diễn một số thập phân với độ chính xác được chỉ định.</td> + </tr> + </tbody> +</table> + +<h2 id="Math_object"><code>Math</code> object</h2> + +<p>{{jsxref("Math")}} object cung cấp thuộc tính và những phương thức để lấy giá trị của các hằng số và những hàm toán học. Ví dụ, thuộc tính PI của <code>Math</code> có giá trị pi (3.141...), mà bạn có thể sử dụng trong ứng dụng như</p> + +<pre class="brush: js">Math.PI +</pre> + +<p>Tương tự, những hàm chuẩn của toán học là phương thức của <code>Math</code>. Bao gồm lượng giác, logarit, hàm mũ, và những hàm khác nữa. Ví dụ, nếu bạn muốn sử dụng hàm lượng giác sine, bạn có thể viết như sau</p> + +<pre class="brush: js">Math.sin(1.56) +</pre> + +<p>Lưu ý rằng phương thức lượng giác của <code>Math</code> nhận đổi số kiểu radians.</p> + +<p>Bảng sau tóm tắt những phương thức của đối tượng <code>Math</code>.</p> + +<table class="standard-table"> + <caption>Phương thức của <code>Math</code></caption> + <thead> + <tr> + <th scope="col">Phương thức</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Math.abs", "abs()")}}</td> + <td>Giá trị tuyệt đối</td> + </tr> + <tr> + <td>{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}</td> + <td>Những hàm lượng giác chuẩn, với đối số đơn vị radians.</td> + </tr> + <tr> + <td>{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}</td> + <td>Những hàm lượng giác ngược; trả về giá trị theo đơn vị radians.</td> + </tr> + <tr> + <td>{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}</td> + <td>Hàm Hyperbolic; đối số là giá trị theo đơn vị hyperbolic.<br> + </td> + </tr> + <tr> + <td>{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}</td> + <td>Nghịch đảo của hàm hyperbolic; đối số là giá trị theo đơn vị hyperbolic.</td> + </tr> + <tr> + <td> + <p>{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}</p> + </td> + <td>Hàm mũ và hàm logarit</td> + </tr> + <tr> + <td>{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}</td> + <td>Trả về số nguyên lớn nhất và nhỏ nhất mà nhỏ hơn hoặc lớn hơn hoặc bằng đối số truyền vào.</td> + </tr> + <tr> + <td>{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}</td> + <td>Trả về giá trị lớn nhất hoặc nhỏ nhất trong dãy các giá trị truyền vào.</td> + </tr> + <tr> + <td>{{jsxref("Math.random", "random()")}}</td> + <td>Trả về số ngẫu nhiên trong khoảng 0 và 1.</td> + </tr> + <tr> + <td>{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},</td> + <td>Những hàm làm tròn hoặc cắt bớt.</td> + </tr> + <tr> + <td>{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}</td> + <td> + <p>Căn bậc hai, cube root, căn bậc hai của tổng đối số bình phương.</p> + </td> + </tr> + <tr> + <td>{{jsxref("Math.sign", "sign()")}}</td> + <td>Xác dịnh số âm hay số dương hay số không</td> + </tr> + <tr> + <td>{{jsxref("Math.clz32", "clz32()")}},<br> + {{jsxref("Math.imul", "imul()")}}</td> + <td>Số bit 0 ở đầu trong số nhị phân 32 bit. Kết quả của phép nhân 32 bit.</td> + </tr> + </tbody> +</table> + +<p>Không giống như những object khác, bạn không bao giờ tạo <code>Math</code> riêng. Bạn luôn dùng đối tượng <code>Math</code> có sẳn</p> + +<h2 id="Date_object"><code>Date</code> object</h2> + +<p>JavaScript không có kiểu dữ liệu ngày tháng. Tuy nhiên, bạn có thể sử dụng {{jsxref("Date")}} object và phương thức của nó để làm việc với ngày giờ trong ứng dụng của mình. <code>Date</code> object cung cấp nhiều phương thức trực tiếp để thao tác trên trên giá trị ngày giờ. Nó không có bất kỳ thuộc tính nào.</p> + +<p>JavaScript xử lý ngày giờ tương tự Java. Hai ngôn ngữ có nhiều tên phương thức giống nhau, và cả hai ngôn ngữ đều lưu trữ ngày giờ như là một số theo mili giây tính từ ngày 1 tháng 1 năm 1970, 00:00:00, với một Unix Timestamp là một số theo giây tính từ ngày 1 tháng 1, 1970, 00:00:00.</p> + +<p>Dãy giá trị của <code>Date</code> object là -100,000,000 ngày đến 100,000,000 ngày so với 01 tháng 1, 1970 UTC.</p> + +<p>Để tạo một <code>Date</code> object:</p> + +<pre class="brush: js">var dateObjectName = new Date([parameters]); + +</pre> + +<p><code>dateObjectName</code> là biến lưu trữ <code>Date</code> object được tạo;</p> + +<p>Nếu chúng ta bỏ qua từ khóa <code>new</code>, giá trị nhận được là một chuỗi biểu diễn giá trị kiểu ngày giờ.</p> + +<p><code>parameters</code> trong cú pháp trên có thể là một trong những giá trị sau:</p> + +<ul> + <li>Không truyền gì vào: tạo ngày giờ hiện hành. Ví dụ: <code>today = new Date();</code>.</li> + <li>Một chuỗi biểu diễn ngày giờ theo định dạng: "Tháng ngày, năm giờ:phút:giây". Ví dụ: <code>var Xmas95 = new Date("December 25, 1995 13:30:00")</code>. Nếu bạn bỏ sót giờ, phút, giây, giá trị mặc định sẽ là 0.</li> + <li>Một tập các số nguyên cho năm, tháng, và ngày. Ví dụ, <code>var Xmas95 = new Date(1995, 11, 25)</code>.</li> + <li>Một tập các số nguyên cho năm, tháng, ngày, giờ, phút, và giây. Ví dụ <code>var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);</code>.</li> +</ul> + +<h3 id="Những_phương_thức_của_Date_object">Những phương thức của <code>Date</code> object</h3> + +<p>Những phương thức của <code>Date</code> object để xử lý thuộc một trong những loại sau:</p> + +<ul> + <li>phương thức "set", để gán giá trị ngày giờ cho <code>Date</code> objects.</li> + <li>phương thức "get", để nhận giá trị ngày giờ từ <code>Date</code> objects.</li> + <li>phương thức "to", để nhận về giá trị kiểu chuỗi cho <code>Date</code> objects.</li> + <li>phương thức phân giải (parse) và UTC, để phân giải chuỗi <code>Date</code> .</li> +</ul> + +<p>Với phương thức "get" và "set" bạn có thể nhận và gán giây, phút, giờ và ngày của tháng, ngày của tuần, tháng, và năm. Phương thức <code>getDay</code> trả về ngày của tuần, tháng, nhưng không có phương thức <code>setDay</code> tương ứng, bởi vì ngày của tuần được xác định tự động. Những phương thức này sử dụng số nguyên để biểu diễn những giá trị sau:</p> + +<ul> + <li>Giây và phúc: 0 đến 59</li> + <li>Giờ: 0 đến 23</li> + <li>Thứ: 0 (Chủ nhật) đến 6 (Thứ bảy)</li> + <li>Ngày: 1 đến 31 (ngày của tháng)</li> + <li>Tháng: 0 (Tháng 1) to 11 (Tháng 12)</li> + <li>Năm: năm tính từ 1900</li> +</ul> + +<p>Ví dụ, giả sử bạn định nghĩa giá trị ngày như sau:</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995'); +</pre> + +<p>Phương thức <code>Xmas95.getMonth()</code> trả về 11, và <code>Xmas95.getFullYear()</code> trả về 1995.</p> + +<p>Phương thức <code>getTime</code> và <code>setTime</code> dùng để so sánh hai giá trị ngày. Phương thức <code>getTime</code> trả về số milli giây tính từ 0 giờ 0 phút 0 giây ngày 1 tháng 1 năm 1970.</p> + +<p>Ví dụ đoạn mã sau hiển thị số ngày còn lại trong năm hiện tại:</p> + +<pre class="brush: js">var today = new Date(); +var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month +endYear.setFullYear(today.getFullYear()); // Set year to this year +var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day +var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; +var daysLeft = Math.round(daysLeft); //returns days left in the year +</pre> + +<p>Đầu tiên một <code>Date</code> object được tạo ra với tên là <code>today</code> chứ giá trị là ngày hiện tại. Sau đó, một <code>Date</code> object nữa được tạo ra với tên là <code>endYear</code> và được gán giá trị của ngày cuối cùng của năm 1995. Nhưng sau đó <code>endYear</code> được gán lại với năm hiện tại cho đồng nhất về năm. Rồi ta tính toán độ chênh lệch theo ngày giữa <code>endYear</code> và <code>today</code> giá trị phải được làm tròn.</p> + +<p>Phương thức <code>parse</code> dùng để chuyển đổi chuỗi kiểu <code>Date</code> thành <code>Date</code> object. Ví dụ, Đoạn mã sau sử dụng <code>parse</code> và <code>setTime</code> để gán giá trị ngày cho biến <code>IPOdate</code>:</p> + +<pre class="brush: js">var IPOdate = new Date(); +IPOdate.setTime(Date.parse('Aug 9, 1995')); +</pre> + +<h3 id="Ví_dụ">Ví dụ</h3> + +<p>Trong ví dụ sau, hàm <code>JSClock()</code> trả về thời gian trong định dạng của đồng hồ số.</p> + +<pre class="brush: js">function JSClock() { + var time = new Date(); + var hour = time.getHours(); + var minute = time.getMinutes(); + var second = time.getSeconds(); + var temp = '' + ((hour > 12) ? hour - 12 : hour); + if (hour == 0) + temp = '12'; + temp += ((minute < 10) ? ':0' : ':') + minute; + temp += ((second < 10) ? ':0' : ':') + second; + temp += (hour >= 12) ? ' P.M.' : ' A.M.'; + return temp; +} +</pre> + +<p>Hàm <code>JSClock</code> đầu tiên tạo ra <code>Date</code> object với tên <code>time</code>; vì không có đối số được cung cấp, <code>time</code> được tạo ra có giá trị là ngày giờ hiện tại. Sau đó các hàm <code>getHours</code>, <code>getMinutes</code>, và <code>getSeconds</code> để gán giá trị giờ, phút, giây hiện tai cho các biến <code>hour</code>, <code>minute</code>, và <code>second</code>.</p> + +<p>Bốn câu lệnh kế tiếp tạo giá trị chuỗi từ thời gian. Câu lệnh đầu tiên tạo một biến <code>temp</code>, dùng biểu thức điều kiện để gán 1 giá trị cho temp; nếu <code>hour</code> lớn hơn 12, thì gán (<code>hour - 12</code>), ngược lại thì gán giá trị của <code>hour</code>. Nếu giá trị của <code>hour</code> là 0, thì giá trị 12 cho temp.</p> + +<p>Câu lệnh tiếp theo chèn gía trị <code>minute</code> cho <code>temp</code>. Nếu giá trị của <code>minute</code> kém hơn 10, ta thêm ':0' vào trước giá trị chuỗi; ngược lại ta chỉ thêm ':'. Sau đó chèn giá trị giây vào <code>temp</code> với cùng cách trên.</p> + +<p>Cuối cùng, chèn "P.M" vào <code>temp</code> nếu <code>hour</code> lớn hơn 12, ngược lại ta chèn "A.M.".</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</p> diff --git a/files/vi/web/javascript/guide/regular_expressions/index.html b/files/vi/web/javascript/guide/regular_expressions/index.html new file mode 100644 index 0000000000..acddfd5184 --- /dev/null +++ b/files/vi/web/javascript/guide/regular_expressions/index.html @@ -0,0 +1,666 @@ +--- +title: Biểu thức chính quy +slug: Web/JavaScript/Guide/Regular_Expressions +tags: + - Guide + - Intermediate + - JavaScript + - Regular Expression +translation_of: Web/JavaScript/Guide/Regular_Expressions +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}</div> + +<p>Biểu thức chính quy (regular expressions ) là các mẫu dùng để tìm kiếm các bộ kí tự được kết hợp với nhau trong các chuỗi kí tự. Trong JavaScript thì biểu thức chính quy cũng đồng thời là các đối tượng, tức là khi bạn tạo ra một biểu thức chính quy là bạn có một đối tượng tương ứng. Các mẫu này được sử dụng khá nhiều trong JavaScript như phương thức <a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec" title="exec"><code>exec</code></a> và <a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test" title="test"><code>test</code></a> của<a href="/vi/docs/JavaScript/Reference/Global_Objects/RegExp" title="RegExp"> <code>RegExp</code></a>, hay phương thức <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/match" title="match"><code>match</code></a>, <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/replace" title="en-US/docs/JavaScript/Reference/Global_Objects/String/replace"><code>replace</code></a>,<a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/search" title="search"> <code>search</code></a>, và <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/split" title="split"><code>split</code></a> của <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String" title="String"><code>String</code></a>. Trong chương này, ta cùng tìm hiểu chi tiết hơn về biểu thức chính quy trong JavaScript.</p> + +<h2 id="Tạo_một_biểu_thức_chính_quy">Tạo một biểu thức chính quy</h2> + +<p>Bạn có thể tạo ra một biểu thức chính quy bằng 1 trong 2 cách sau:</p> + +<ul> + <li>Sử dụng cách mô tả chính quy thuần (regular expression literal) như sau: + <pre class="brush: js">var re = /ab+c/; +</pre> + + <p>Các đoạn mã chứa các mô tả chính quy thuần sau khi được nạp vào bộ nhớ sẽ dịch các đoạn mô tả đó thành các biểu thức chính quy. Các biểu thức chính quy được dịch ra này sẽ được coi như các hằng số, tức là không phải tạo lại nhiều lần, điều này giúp cho hiệu năng thực hiện tốt hơn.</p> + </li> + <li>Tạo một đối tượng <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp" title="en-US/docs/JavaScript/Reference/Global Objects/RegExp">RegExp</a></code> như sau: + <pre class="brush: js">var re = new RegExp("ab+c"); +</pre> + + <p>Với cách này, các biểu thức chính quy sẽ được dịch ra lúc thực thi chương trình nên hiệu năng không đạt được như với việc sử dụng cách mô tả chính quy thuần. Nhưng ưu điểm là nó có thể thay đổi được, nên ta thường sử dụng chúng khi ta muốn nó có thể thay đổi được, hoặc khi ta chưa chắc chắn về các mẫu chính quy (pattern) như nhập từ bàn phím chẳng hạn.</p> + </li> +</ul> + +<h2 id="Cách_viết_một_mẫu_biểu_thức_chính_quy">Cách viết một mẫu biểu thức chính quy</h2> + +<p>Một mẫu biểu thức chính quy là một tập các kí tự thường, như <code>/abc/</code>, hay một tập kết hợp cả kí tự thường và kí tự đặc biệt như <code>/ab*c/</code> hoặc <code>/Chapter (\d+)\.\d*/</code>. Trong ví dụ cuối, ta thấy rằng nó chứa cả các dấu ngoặc đơn( () )được sử dụng như các thiết bị nhớ, tức là các mẫu trong phần () này sau khi được tìm kiếm có thể được nhớ lại để sử dụng cho các lần sau. Bạn có thể xem chi tiết hơn tại: <a href="#Sử dụng nhiều dấu ngoặc tròn">Sử dụng dấu ngoặc đơn tìm xâu con</a>.</p> + +<h3 id="Sử_dụng_mẫu_đơn_giản">Sử dụng mẫu đơn giản</h3> + +<p>Các mẫu đơn giản là các mẫu có thể được xây dựng từ các kí tự có thể thể tìm kiếm một cách trực tiếp. Ví dụ, mẫu <code>/abc/</code> sẽ tìm các các đoạn 'abc' theo đúng thứ tự đó trong các chuỗi. Mẫu này sẽ khớp được với "Hi, do you know your abc's?" và "The latest airplane designs evolved from slabcraft.", vì cả 2 chuỗi này đều chứa đoạn 'abc'. Còn với chuỗi 'Grab crab', nó sẽ không khớp vì chuỗi này không chứa 'abc' theo đúng thứ tự, mà chỉ chứa 'ab c'.</p> + +<h3 id="Sử_dụng_các_kí_tự_đặc_biệt">Sử dụng các kí tự đặc biệt</h3> + +<p>Các mẫu có thể chứa các kí tự đặc biệt cho các mục đích tìm kiếm nâng cao mà tìm kiếm trực tiếp sẽ khó khăn như tìm một đoạn chứa một hoặc nhiều hơn một kí tự b, hay tìm một hoặc nhiều kí tự dấu cách (while space). Ví dụ, mẫu <code>/ab*c/</code> có thể tìm các đoạn có chứa: một kí tự 'a', theo sau là không có hoặc có một hoặc có nhiều kí tự 'b', cuối cùng là một kí tự 'c' như chuỗi "cbbabbbbcdebc," sẽ được khớp với xâu con 'abbbbc'.</p> + +<p>Bảng dưới đây mô tả đầy đủ các kí tự đặc biệt có thể dùng với biểu thức chính quy.</p> + +<table class="fullwidth-table"> + <caption>Bảng 4.1 Các kí tự đặc biệt trong biểu thức chính quy.</caption> + <thead> + <tr> + <th scope="col">Kí tự (kí hiệu, cờ)</th> + <th scope="col">Ý nghĩa</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="#special-backslash" id="special-backslash" name="special-backslash"><code>\</code></a></td> + <td> + <p>Tìm với luật dưới đây:<br> + <br> + Một dấu gạch chéo ngược sẽ biến một kí tự thường liền kế phía sau thành một kí tự đặc biệt, tức là nó không được sử dụng để tìm kiếm thông thường nữa. Ví dụ, trường hợp kí tự '<code>b</code>' không có dấu gạch chéo ngược này sẽ được khớp với các kí tự 'b' in thường, nhưng khi nó có thêm dấu gạch chéo ngược, '<code>\b</code>' thì nó sẽ không khớp với bất kì kí tự nào nữa, lúc này nó trở thành kí tự đặc biệt. Xem thêm phần <a href="#special-word-boundary" title="#special-word-boundary">word boundary character</a> để biết thêm chi tiết.<br> + <br> + Tuy nhiên nếu đứng trước một kí tự đặc biệt thì nó sẽ biến kí tự này thành một kí tự thường, tức là bạn có thể tìm kiếm kí tự đặc biệt này trong xâu chuỗi của bạn như các kí tự thường khác. Ví dụ, mẫu <code>/a*/</code> có '*' là kí tự đặc biệt và mẫu này sẽ bị phụ thuộc vào kí tự này, nên được hiểu là sẽ tìm khớp với 0 hoặc nhiều kí tự a. Nhưng, với mẫu <code>/a\*/</code> thì kí tự '<code>*</code>' lúc này được hiểu là kí tự thường nên mẫu này sẽ tìm kiếm xâu con là 'a*'.</p> + + <p>Đừng quên \ cũng là một kí tự đặc biệt, khi cần so khớp chính nó ta cũng phải đánh dấu nó là kí tự đặc biệt bằng cách đặt \ ở trước (\\).</p> + </td> + </tr> + <tr> + <td><a href="#special-caret" id="special-caret" name="special-caret"><code>^</code></a></td> + <td> + <p>Khớp các kí tự đứng đầu một chuỗi. Nếu có nhiều cờ này thì nó còn khớp được cả các kí tự đứng đầu của mỗi dòng (sau kí tự xuống dòng).<br> + <br> + Ví dụ, <code>/^A/</code> sẽ không khớp được với 'A' trong "an A" vì 'A' lúc này không đứng đầu chuỗi, nhưng nó sẽ khớp "An E" vì lúc này 'A' đã đứng đầu chuỗi.</p> + + <p>Ý nghĩa của '^' sẽ thay đổi khi nó xuất hiện như một kí tự đầu tiên trong một lớp kí tự, xem phần <a href="#special-negated-character-set" title="#special-negated-character-set">complemented character sets</a> để biết thêm chi tiết.</p> + </td> + </tr> + <tr> + <td><a href="#special-dollar" id="special-dollar" name="special-dollar"><code>$</code></a></td> + <td> + <p>So khớp ở cuối chuỗi. Nếu gắn cờ multiline (đa dòng), nó sẽ khớp ngay trước kí tự xuống dòng.</p> + + <p>Ví dụ, /t$/ không khớp với 't' trong chuỗi "eater" nhưng lại khớp trong chuỗi "eat".</p> + </td> + </tr> + <tr> + <td><a href="#special-asterisk" id="special-asterisk" name="special-asterisk"><code>*</code></a></td> + <td> + <p>Cho phép kí tự trước nó lặp lại 0 lần hoặc nhiều lần. Tương đương với cách viết {0,}.</p> + + <p>Ví dụ, /bo*/ khớp với 'boooo' trong chuỗi "A ghost booooed" nhưng không khớp trong chuỗi "A birth warbled".</p> + </td> + </tr> + <tr> + <td><a href="#special-plus" id="special-plus" name="special-plus"><code>+</code></a></td> + <td> + <p>Cho phép kí tự trước nó lặp lại 1 lần hoặc nhiều lần. Tương đương với cách viết {1,}.</p> + + <p>Ví dụ, /a+/ khớp với 'a' trong chuỗi "candy" và khớp với tất cả kí tự a liền nhau trong chuỗi "caaaaaaandy".</p> + </td> + </tr> + <tr> + <td><a href="#special-questionmark" id="special-questionmark" name="special-questionmark"><code>?</code></a></td> + <td> + <p>Cho phép kí tự trước nó lặp lại 0 lần hoặc 1 lần duy nhất. Tương đương với cách viết {0,1}.</p> + + <p>Ví dụ, /e?le?/ khớp với 'el' trong chuỗi "angel" và 'le' trong chuỗi "angle" hay 'l' trong "oslo".</p> + + <p>Nếu sử dụng kí tự này ngay sau bất kì kí tự định lượng nào trong số *,+,? hay {}, đều làm bộ định lượng "chán ăn" (dừng so khớp sau ngay khi tìm được kí tự phù hợp), trái ngược với đức tính "tham lam" vốn sẵn của chúng (khớp tất cả kí tự chúng tìm thấy). Ví dụ, áp dụng biểu mẫu /\d+/ cho "123abc" ta được "123". Nhưng áp /\d+?/ cho chính chuỗi trên ta chỉ nhận được kết quả là "1".</p> + + <p>Bạn có thể đọc thêm trong mục x(?=y) và x(?!y) của bảng này.</p> + </td> + </tr> + <tr> + <td><a href="#special-dot" id="special-dot" name="special-dot"><code>.</code></a></td> + <td> + <p>Dấu . khớp với bất kì kí tự đơn nào ngoại trừ kí tự xuống dòng.</p> + + <p>Ví dụ, /.n/ khớp với 'an' và 'on' trong chuỗi "no, an apple is on the tree", nhưng không khớp với 'no'.</p> + </td> + </tr> + <tr> + <td><a href="#special-capturing-parentheses" id="special-capturing-parentheses" name="special-capturing-parentheses"><code>(x)</code></a></td> + <td> + <p>Khớp 'x' và nhớ kết quả so khớp này, như ví dụ ở dưới. Các dấu ngoặc tròn được gọi là các dấu ngoặc có nhớ.</p> + + <p>Biểu mẫu <code>/(foo) (bar) \1 \2/ khớp với 'foo' và 'bar'</code> trong chuỗi "foo bar foo bar". <code>\1</code> và <code>\2</code> trong mẫu khớp với 2 từ cuối.</p> + + <p>Chú ý rằng <code>\1</code>, <code>\2</code>, <code>\n</code> được sử dụng để so khớp các phần trong regex, nó đại diện cho nhóm so khớp đằng trước. Ví dụ: <code>/(foo) (bar) \1 \2/ tương đương với biểu thức /(foo) (bar) foo bar/.</code> </p> + + <p>Cú pháp <code>$1, $2, $n còn</code> được sử dụng trong việc thay thế các phần của một regex. Ví dụ: <code>'bar foo'.replace(/(...) (...)/, '$2 $1') </code>sẽ đảo vị trí 2 từ 'bar' và 'foo' cho nhau.</p> + </td> + </tr> + <tr> + <td><a href="#special-non-capturing-parentheses" id="special-non-capturing-parentheses" name="special-non-capturing-parentheses"><code>(?:x)</code></a></td> + <td> + <p>Khớp 'x' nhưng không nhớ kết quả so khớp. Những dấu ngoặc tròn được gọi là những dấu ngoặc không nhớ, nó cho phép bạn định nghĩa những biểu thức con cho những toán tử so khớp. Xem xét biểu thức đơn giản <code>/(?:foo){1,2}/. </code>Nếu biểu thức này được viết là <code>/foo{1,2}/</code>, <code>{1,2}</code> sẽ chỉ áp dụng cho kí tự 'o' ở cuối chuỗi 'foo'. Với những dấu ngoặc không nhớ, <code>{1,2} </code>sẽ áp dụng cho cả cụm 'foo'.</p> + </td> + </tr> + <tr> + <td><a href="#special-lookahead" id="special-lookahead" name="special-lookahead"><code>x(?=y)</code></a></td> + <td> + <p>Chỉ khớp 'x' nếu 'x' theo sau bởi 'y'.</p> + + <p>Ví dụ, <code>/Jack(?=Sprat)/ </code>chỉ<code> </code>khớp với 'Jack' nếu đằng sau nó là 'Sprat'. <code>/Jack(?=Sprat|Frost)/ </code>chỉ khớp 'Jack' nếu theo sau nó là 'Sprat' hoặc 'Frost'. Tuy nhiên, cả 'Sprat' và 'Frost' đều không phải là một phần của kết quả so khớp trả về.</p> + </td> + </tr> + <tr> + <td><a href="#special-negated-look-ahead" id="special-negated-look-ahead" name="special-negated-look-ahead"><code>x(?!y)</code></a></td> + <td> + <p>Chỉ khớp 'x' nếu 'x' <strong>không</strong> được theo sau bởi 'y'.</p> + + <p>Ví dụ: <code>/\d+(?!\.)/</code> chỉ khớp với số không có dấu <code>.</code> đằng sau. Biểu thức <code>/\d+(?!\.)/.exec("3.141") </code>cho kết quả là '141' mà không phải '3.141'.</p> + </td> + </tr> + <tr> + <td><a href="#special-or" id="special-or" name="special-or"><code>x|y</code></a></td> + <td> + <p>Khớp 'x' hoặc 'y'</p> + + <p>Ví dụ, <code>/green|red/ </code>khớp với 'green' trong chuỗi "green apple" và 'red' trong chuỗi "red apple".</p> + </td> + </tr> + <tr> + <td><a href="#special-quantifier" id="special-quantifier" name="special-quantifier"><code>{n}</code></a></td> + <td> + <p>Kí tự đứng trước phải xuất hiện n lần. n phải là một số nguyên dương.</p> + + <p>Ví dụ, <code>/a{2}/ </code>không khớp với 'a' trong "candy", nhưng nó khớp với tất cả kí tự 'a' trong "caandy", và khớp với 2 kí tự 'a' đầu tiên trong "caaandy".</p> + </td> + </tr> + <tr> + <td><a href="#special-quantifier-range" id="special-quantifier-range" name="special-quantifier-range"><code>{n,m}</code></a></td> + <td> + <p>Kí tự đứng trước phải xuất hiện từ n đến m lần. n và m là số nguyên dương và n <= m. Nếu m bị bỏ qua, nó tương đương như ∞.</p> + + <p>Ví dụ, <code>/a{1,3}/ không </code>khớp bất kì kí tự nào trong "cndy", kí tự 'a' trong "candy", 2 kí tự 'a' đầu tiên trong "caandy", và 3 kí tự 'a' đầu tiên trong "caaaaaaandy". Lưu ý là "caaaaaaandy" chỉ khớp với 3 kí tự 'a' đầu tiên mặc dù chuỗi đó chứa 7 kí tự 'a'.</p> + </td> + </tr> + <tr> + <td><a href="#special-character-set" id="special-character-set" name="special-character-set"><code>[xyz]</code></a></td> + <td> + <p>Lớp kí tự. Loại mẫu này dùng để so khớp với một kí tự bất kì trong dấu ngoặc vuông, bao gồm cả <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences">escape sequences</a>. Trong lớp kí tự, dấu chấm (.) và dấu hoa thị (*) không còn là kí tự đặc biệt nên ta không cần kí tự thoát đứng trước nó. Bạn có thể chỉ định một khoảng kí tự bằng cách sử dụng một kí tự gạch nối (-) như trong ví dụ dưới đây:</p> + + <p>Mẫu <code>[a-d] </code>so khớp tương tự như mẫu <code>[abcd]</code>, khớp với 'b' trong "brisket" và 'c' trong "city". Mẫu <code>/[a-z.]+/ và /[\w.]+/ </code>khớp với toàn chuỗi "test.i.ng".</p> + </td> + </tr> + <tr> + <td><a href="#special-negated-character-set" id="special-negated-character-set" name="special-negated-character-set"><code>[^xyz]</code></a></td> + <td> + <p>Lớp kí tự phủ định. Khi kí tự ^ đứng đầu tiên trong dấu ngoặc vuông, nó phủ định mẫu này.</p> + + <p>Ví dụ, <code>[^abc] </code>tương tự như <code>[^a-c], khớp với 'r' trong "brisket" và 'h' trong "chop" là kí tự đầu tiên không thuộc khoảng a đến c.</code></p> + </td> + </tr> + <tr> + <td><a href="#special-backspace" id="special-backspace" name="special-backspace"><code>[\b]</code></a></td> + <td> + <p>Khớp với kí tự dịch lùi - backspace (U+0008). Bạn phải đặt trong dấu ngoặc vuông nếu muốn so khớp một kí tự dịch lùi. (Đừng nhầm lẫn với mẫu \b).</p> + </td> + </tr> + <tr> + <td><a href="#special-word-boundary" id="special-word-boundary" name="special-word-boundary"><code>\b</code></a></td> + <td> + <p>Khớp với kí tự biên. Kí tự biên là một kí tự giả, nó khớp với vị trí mà một kí tự không được theo sau hoặc đứng trước bởi một kí tự khác. Tương đương với mẫu <code>(^\w|\w$|\W\w|\w\W).</code> Lưu ý rằng một kí tự biên được khớp sẽ không bao gồm trong kết quả so khớp. Nói cách khác, độ dài của một kí tự biên là 0. (Đừng nhầm lẫn với mẫu [\b])</p> + + <p>Ví dụ:<br> + <code>/\bm/ </code>khớp với 'm' trong chuỗi "moon";<br> + <code>/oo\b/ </code>không khớp 'oo' trong chuỗi "moon", bởi vì 'oo' được theo sau bởi kí tự 'n';<br> + <code>/oon\b/ </code>khớp với 'oon' trong chuỗi "moon", bởi vì 'oon' ở cuối chuỗi nên nó không được theo sau bởi một kí tự; <br> + <code>/\w\b\w/ </code>sẽ không khớp với bất kì thứ gì, bởi vì một kí tự không thể theo sau một kí tự biên và một kí tự thường.</p> + + <div class="note"> + <p><strong>Chú ý:</strong> Engine biên dịch biểu thức chính quy trong Javascript định nghĩa một <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.6">lớp kí tự</a> là những kí tự thường. Bất kỳ kí tự nào không thuộc lớp kí tự bị xem như một kí tự ngắt. Lớp kí tự này khá hạn chế: nó bao gồm bộ kí tự La-tinh cả hoa và thường, số thập phân và kí tự gạch dưới. Kí tự có dấu, như "é" hay "ü", không may, bị đối xử như một kí tự ngắt.</p> + </div> + </td> + </tr> + <tr> + <td><a href="#special-non-word-boundary" id="special-non-word-boundary" name="special-non-word-boundary"><code>\B</code></a></td> + <td> + <p>Khớp với kí tự không phải kí tự biên. Mẫu này khớp tại vị trí mà kí tự trước và kí tự sau nó cùng kiểu: hoặc cả hai là kí tự hoặc cả hai không phải là kí tự. Bắt đầu và kết thúc chuỗi không được xem là những kí tự.</p> + + <p>Ví dụ, <code>/\B../ </code>khớp với 'oo' trong "noonday", và<code> /y\B./ </code>khớp với 'ye' trong "possibly yesterday."</p> + </td> + </tr> + <tr> + <td><a href="#special-control" id="special-control" name="special-control"><code>\c<em>X</em></code></a></td> + <td> + <p>X là một kí tự trong khoảng A tới Z. Mẫu này khớp với một kí tự điều khiển trong một chuỗi.</p> + + <p>Ví dụ: <code>/\cM/</code> khớp với control-M (U+000D) trong chuỗi.</p> + </td> + </tr> + <tr> + <td><a href="#special-digit" id="special-digit" name="special-digit"><code>\d</code></a></td> + <td> + <p>Khớp với một kí tự số. Tương đương với mẫu [0-9].</p> + + <p>Ví dụ: <code>/\d/</code> hoặc <code>/[0-9]/ </code>khớp với '2' trong chuỗi "B2 is the suite number."</p> + </td> + </tr> + <tr> + <td><a href="#special-non-digit" id="special-non-digit" name="special-non-digit"><code>\D</code></a></td> + <td> + <p>Khớp với một kí tự không phải là kí tự số. Tương đương với mẫu [^0-9].</p> + + <p>Ví dụ; <code>/\D/</code> hoặc <code>/[^0-9]/</code> khớp với 'B' trong "B2 is the suite number."</p> + </td> + </tr> + <tr> + <td><a href="#special-form-feed" id="special-form-feed" name="special-form-feed"><code>\f</code></a></td> + <td>Khớp với kí tự phân trang - form feed (U+000C).</td> + </tr> + <tr> + <td><a href="#special-line-feed" id="special-line-feed" name="special-line-feed"><code>\n</code></a></td> + <td>Khớp với kí tự xuống dòng - line feed (U+000A).</td> + </tr> + <tr> + <td><a href="#special-carriage-return" id="special-carriage-return" name="special-carriage-return"><code>\r</code></a></td> + <td>Khớp với kí tự quay đầu dòng - carriage return (U+000D).</td> + </tr> + <tr> + <td><a href="#special-white-space" id="special-white-space" name="special-white-space"><code>\s</code></a></td> + <td> + <p>Khớp với một kí tự khoảng trắng, bao gồm trống - space, tab, phân trang - form feed, phân dòng - line feed. Tương đương với <code>[ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]</code>.</p> + + <p>Ví dụ: <code>/\s\w*/</code> khớp với ' bar' trong "foo bar."</p> + </td> + </tr> + <tr> + <td><a href="#special-non-white-space" id="special-non-white-space" name="special-non-white-space"><code>\S</code></a></td> + <td> + <p>Khớp với một kí tự không phải khoảng trắng. Tương đương với <code>[^ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]</code>.</p> + + <p>Ví dụ: <code>/\S\w*/</code> khớp với 'foo' trong chuỗi "foo bar."</p> + </td> + </tr> + <tr> + <td><a href="#special-tab" id="special-tab" name="special-tab"><code>\t</code></a></td> + <td>Khớp với kí tự tab (U+0009).</td> + </tr> + <tr> + <td><a href="#special-vertical-tab" id="special-vertical-tab" name="special-vertical-tab"><code>\v</code></a></td> + <td>Khớp với kí tự vertical tab (U+000B).</td> + </tr> + <tr> + <td><a href="#special-word" id="special-word" name="special-word"><code>\w</code></a></td> + <td> + <p>Khớp với tất cả kí tự là chữ, số và gạch dưới. Tương đương với mẫu <code>[A-Za-z0-9_]</code>.</p> + + <p>ví dụ, <code>/\w/</code> khớp với 'a' trong "apple," '5' trong "$5.28," và '3' trong "3D."</p> + </td> + </tr> + <tr> + <td><a href="#special-non-word" id="special-non-word" name="special-non-word"><code>\W</code></a></td> + <td> + <p>Khớp với tất cả kí tự không phải là chữ. Tương đương với mẫu <code>[^A-Za-z0-9_]</code>.</p> + + <p>ví dụ, <code>/\W/</code> hoặc <code>/[^A-Za-z0-9_]/</code> khớp với '%' trong "50%."</p> + </td> + </tr> + <tr> + <td><a href="#special-backreference" id="special-backreference" name="special-backreference"><code>\<em>n</em></code></a></td> + <td> + <p>Trong đó, n là một số nguyên dương, một tham chiếu ngược tới chuỗi khớp thứ n trong biểu thức (đếm từ trái sang, bắt đầu bằng 1).</p> + + <p>ví dụ, <code>/apple(,)\sorange\1/ </code>hay <code>/apple(,)\sorange,/</code> khớp với 'apple, orange,' trong chuỗi "apple, orange, cherry, peach."</p> + </td> + </tr> + <tr> + <td><a href="#special-null" id="special-null" name="special-null"><code>\0</code></a></td> + <td>Khớp với kí tự NULL (U+0000). Lưu ý: không được thêm bất kì một kí tự số nào sau 0, vì <code>\0<các-kí-tự-số></code> là một biểu diễn hệ bát phân <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences">escape sequence</a>.</td> + </tr> + <tr> + <td><a href="#special-hex-escape" id="special-hex-escape" name="special-hex-escape"><code>\xhh</code></a></td> + <td>Khớp với kí tự với mã code là hh (2 số trong hệ thập lục phân)</td> + </tr> + <tr> + <td><a href="#special-unicode-escape" id="special-unicode-escape" name="special-unicode-escape"><code>\uhhhh</code></a></td> + <td>Khớp với kí tự có mã hhhh (4 số trong hệ thập lục phân).</td> + </tr> + </tbody> +</table> + +<p>Mã hóa escapse chuỗi người dùng nhập vào bằng một hàm thay thế đơn giản sử dụng biểu thức chính quy:</p> + +<pre class="brush: js">function escapeRegExp(string){ + return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +}</pre> + +<h3 id="Sử_dụng_ngoặc_tròn">Sử dụng ngoặc tròn</h3> + +<p>Ngoặc tròn bao quanh bất kỳ phần nào của biểu thức chính quy sẽ khiến phần kết quả so khớp được nhớ. Mỗi lần nhớ, chuỗi con có thể được gọi lại để sử dụng, mô tả trong <span style="line-height: 1.5;"><a href="#Using_Parenthesized_Substring_Matches">Using Parenthesized Substring Matches</a>.</span></p> + +<p><span style="line-height: 1.5;">Ví dụ, mẫu </span><code>/Chapter (\d+)\.\d*/ </code>khớp đúng với 'Chapter ' theo sau bởi một hoặc nhiều kí tự số, sau nữa là một dấu chấm thập phân, cuối cùng có thể là 0 hoặc nhiều kí tự số. Bên cạnh đó, dấu ngoặc tròn được sử dụng để nhớ một hoặc nhiều kí tự số đầu tiên được khớp.</p> + +<p>Mẫu này được tìm thấy trong chuỗi "Open Chapter 4.3, paragraph 6", nhớ '4' nhưng không được tìm thấy trong chuỗi "Chapter 3 and 4", bởi vì chuỗi đó không có dấu chấm sau kí tự số '3'.</p> + +<p>Để so khớp một chuỗi con không nhớ, đặt ?: ở vị trí đầu tiên trong ngoặc. Ví dụ, <code>(?:\d+)</code> khớp với một hoặc nhiều kí tự số nhưng không nhớ kết quả so khớp.</p> + +<h2 id="Làm_việc_với_biểu_thức_chính_quy">Làm việc với biểu thức chính quy</h2> + +<p>Biểu thức chính quy được sử dụng với phương thức test và exec của lớp RegExp hoặc phương thức match, replace, search và split của chuỗi. Những phương thức này được giải thích chi tiết trong <a href="/en-US/docs/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">JavaScript Reference</a>.</p> + +<table class="standard-table"> + <caption>Bảng 4.2 Những phương thức được sử dụng trong biểu thức chính quy</caption> + <thead> + <tr> + <th scope="col">Phương thức</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec" title="en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec">exec</a></code></td> + <td>Một phương thức của RegExp dùng để tìm kiếm chuỗi phù hợp với mẫu so khớp. Nó trả về một mảng chứa kết quả tìm kiếm.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test" title="en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test">test</a></code></td> + <td>Một phương thức của RegExp dùng để kiểm tra mẫu có khớp với chuỗi hay không. Nó trả về giá trị true hoặc false.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/match" title="en-US/docs/JavaScript/Reference/Global_Objects/String/match">match</a></code></td> + <td>Một phương thức của chuỗi dùng để tìm kiếm chuỗi phù hợp với mẫu so khớp. Nó trả về một mảng chứa kết quả tìm kiếm hoặc null nếu không tìm thấy.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/search" title="en-US/docs/JavaScript/Reference/Global_Objects/String/search">search</a></code></td> + <td>Một phương thức của chuỗi dùng để tìm kiếm chuỗi phù hợp với mẫu so khớp và trả về vị trí của chuỗi đó hoặc -1 nếu không tìm thấy.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/replace" title="en-US/docs/JavaScript/Reference/Global_Objects/String/replace">replace</a></code></td> + <td>Một phương thức của chuỗi dùng để tìm kiếm một chuỗi theo mẫu so khớp và thay thế chuỗi con được khớp với một chuỗi thay thế.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/split" title="en-US/docs/JavaScript/Reference/Global_Objects/String/split">split</a></code></td> + <td>Một phương thức của chuỗi dùng một biểu mẫu chính quy hoặc một chuỗi bất biến để ngắt chuỗi đó thành một mảng các chuỗi con.</td> + </tr> + </tbody> +</table> + +<p>Khi bạn muốn biết một mẫu có được tìm thấy trong chuỗi hay không, sử dụng phương thức test hoặc search; để lấy nhiều thông tin hơn (nhưng chậm hơn) sử dụng phương thức exec hoặc match.</p> + +<p>Như ví dụ dưới đây, phương thức exec được dùng để tìm chuỗi phù hợp theo mẫu so khớp.</p> + +<pre class="brush: js">var myRe = /d(b+)d/g; +var myArray = myRe.exec("cdbbdbsbz"); +</pre> + +<p>Nếu bạn không cần truy cập những thuộc tính khác của biểu thức chính quy, sử dụng cách sau:</p> + +<pre class="brush: js">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); +</pre> + +<p>Nếu bạn muốn khởi tạo một biểu thức chính quy từ một chuỗi:</p> + +<pre class="brush: js">var myRe = new RegExp("d(b+)d", "g"); +var myArray = myRe.exec("cdbbdbsbz"); +</pre> + +<p>Với những mã này, so khớp thành công và trả về một mảng kết quả với những thuộc tính được liệt kê trong bảng dưới đây.</p> + +<table class="fullwidth-table"> + <caption>Bảng 4.3 Kết quả so khớp</caption> + <thead> + <tr> + <th scope="col">Đối tượng</th> + <th scope="col">Thuộc tính hoặc chỉ số</th> + <th scope="col">Mô tả</th> + <th scope="col">Trong vd này</th> + </tr> + </thead> + <tbody> + <tr> + <td rowspan="4"><code>myArray</code></td> + <td> </td> + <td>Chuỗi kết quả so khớp và toàn bộ chuỗi con được nhớ.</td> + <td><code>["dbbd", "bb"]</code></td> + </tr> + <tr> + <td><code>index</code></td> + <td>Vị trí của chuỗi tìm thấy, đếm từ 0</td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>input</code></td> + <td>Chuỗi gốc được nhập vào</td> + <td><code>"cdbbdbsbz"</code></td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>Những kí tự cuối cùng được khớp.</td> + <td><code>"dbbd"</code></td> + </tr> + <tr> + <td rowspan="2"><code>myRe</code></td> + <td><code>lastIndex</code></td> + <td>Vị trí nơi mà bắt đầu so khớp lần sau. (Thuộc tính này chỉ được gán nếu biểu thức chính quy sử dụng lựa chọn g, được mô tả trong <a href="#Advanced_Searching_With_Flags">Advanced Searching With Flags</a> ).</td> + <td><code>5</code></td> + </tr> + <tr> + <td><code>source</code></td> + <td>Chuỗi biểu thức chính quy, được cập nhật tại thời điểm biểu thức được tạo, không phải tại lúc thực thi.</td> + <td><code>"d(b+)d"</code></td> + </tr> + </tbody> +</table> + +<p>Như dạng thứ 2 của ví dụ trên, bạn có thể dùng một biểu thức chính quy được khởi tạo mà không gán nó tới một biến. Tuy nhiên, nếu bạn làm thế, mỗi lần xuất hiện là một biểu thức chính quy mới. Vì lí do này, nếu bạn không gán nó vào một biến, bạn sẽ không thể truy cập các thuộc tính của biểu thức chính quy đó nữa. Ví dụ bạn có đoạn script sau:</p> + +<pre class="brush: js">var myRe = /d(b+)d/g; +var myArray = myRe.exec("cdbbdbsbz"); +console.log("The value of lastIndex is " + myRe.lastIndex); +</pre> + +<p>Kết quả hiển thị là:</p> + +<pre>The value of lastIndex is 5 +</pre> + +<p>Tuy nhiên nếu bạn chạy:</p> + +<pre class="brush: js">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); +console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex); +</pre> + +<p>Thì kết quả hiển thị sẽ là:</p> + +<pre>The value of lastIndex is 0 +</pre> + +<p>Sự xuất hiện của <code>/d(b+)d/g </code>trong 2 lệnh trên là những đối tượng biểu thức chính quy khác nhau và vì thế có những giá trị khác nhau cho thuộc tính lastIndex. Nếu bạn cần truy cập những thuộc tính của một biểu thức chính quy, bạn nên gán nó tới một biến.</p> + +<h3 id="Sử_dụng_nhiều_dấu_ngoặc_tròn"><a id="Sử dụng nhiều dấu ngoặc tròn" name="Sử dụng nhiều dấu ngoặc tròn">Sử dụng nhiều dấu ngoặc tròn</a></h3> + +<p>Sử dụng nhiều ngoặc tròn trong một biểu thức chính quy cho ta nhiều kết quả so khớp tương ứng được nhớ. Cho ví dụ, <code>/a(b)c/</code> khớp với 'abc' và nhớ 'b'. Để gọi lại những kết quả so khớp, sử dụng những phần tử của mảng [1]..., [n].</p> + +<p>Số lượng các chuỗi con trong những ngoặc tròn là không giới hạn. Mảng trả về giữ lại tất cả mọi thứ được tìm thấy.</p> + +<h4 id="Ví_dụ">Ví dụ</h4> + +<p>Đoạn mã JavaScript dưới đây sử dụng phương thức <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/replace" title="en-US/docs/JavaScript/Reference/Global Objects/String/replace">replace()</a> </code>để giao hoán các từ trong chuỗi. Trong chuỗi thay thế, ta dùng $1 và $2 để chỉ các chuỗi khớp với mẫu trong ngoặc ở vị trí thứ 1 và 2.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = "John Smith"; +var newstr = str.replace(re, "$2, $1"); +console.log(newstr); +</pre> + +<p>Kết quả hiển thị là: "Smith, John".</p> + +<h3 id="Tìm_kiếm_nâng_cao_với_cờ">Tìm kiếm nâng cao với cờ</h3> + +<p>Biểu thức chính quy có 4 cờ cho phép tìm kiếm toàn cục và hoa thường. Những cờ này có thể được đứng riêng hoặc đứng gần nhau, và được coi như một phần của biểu thức chính quy.</p> + +<table class="standard-table"> + <caption>Bảng 4.4 Cờ của biểu thức chính quy</caption> + <thead> + <tr> + <th scope="col">Cờ</th> + <th scope="col">Mô tả</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>g</code></td> + <td>Tìm kiếm toàn cục.</td> + </tr> + <tr> + <td>i</td> + <td>Tìm kiếm không phân biệt hoa thường.</td> + </tr> + <tr> + <td>m</td> + <td>Tìm đa dòng.</td> + </tr> + <tr> + <td>y</td> + <td>Thực thi một tìm kiếm "dính" - so khớp được bắt đầu ở vị trí hiện tại trong chuỗi mục tiêu.</td> + </tr> + </tbody> +</table> + +<p>{{ Fx_minversion_note(3, "Từ Firefox 3 đã hỗ trợ cờ y. Cờ y thất bại nếu so khớp không thành công ở vị trí hiện tại trong chuỗi mục tiêu.") }}</p> + +<p>Để sử dụng cờ trong biểu thức chính quy, dùng cú pháp này:</p> + +<pre class="brush: js">var re = /pattern/flags; +</pre> + +<p>hoặc</p> + +<pre class="brush: js">var re = new RegExp("pattern", "flags"); +</pre> + +<p>Lưu ý rằng cờ là một phần hợp thành một biểu thức chính quy. Chúng không thể được thêm hoặc gỡ bỏ sau đó.</p> + +<p>Ví dụ, <code>re = /\w+\s/g </code>tạo một biểu thức chính quy dùng để tìm kiếm một hoặc nhiều kí tự theo sau bởi một khoảng trắng, và nó tìm kiếm tổ hợp này xuyên suốt chuỗi mục tiêu.</p> + +<pre class="brush: js">var re = /\w+\s/g; +var str = "fee fi fo fum"; +var myArray = str.match(re); +console.log(myArray); +</pre> + +<p>Kết quả hiển thị là ["fee ", "fi ", "fo "].</p> + +<p>Trong ví dụ này, bạn cũng có thể thay thế dòng này:</p> + +<pre class="brush: js">var re = /\w+\s/g; +</pre> + +<p>bằng:</p> + +<pre class="brush: js">var re = new RegExp("\\w+\\s", "g"); +</pre> + +<p>và nhận được cùng một kết quả giống nhau.</p> + +<p>Cờ m được sử dụng để xác định rằng một chuỗi đầu vào nên được đối xử như nhiều dòng. Nếu dùng cờ này, so khớp ^ và $ ở đầu và cuối ở mọi dòng trong chuỗi đầu vào thay vì ở đầu và cuỗi của toàn bộ chuỗi.</p> + +<h2 id="Ví_dụ_minh_họa">Ví dụ minh họa</h2> + +<p>Các ví dụ sau đây cho thấy một số cách sử dụng các biểu thức chính quy.</p> + +<h3 id="Thay_đổi_thứ_tự_trong_một_chuỗi">Thay đổi thứ tự trong một chuỗi</h3> + +<p>Ví dụ sau đây minh họa sự cấu thành các biểu thức chính quy và việc sử dụng các phương thức<code> string.split()</code> và <code>string.Replace().</code> Nó làm sạch một chuỗi đầu vào được định dạng có chứa tên (first name ở vị trí đầu tiên) cách nhau bởi khoảng trống, các tab và chỉ một dấu chấm phẩy duy nhất. Cuối cùng, nó đảo ngược thứ tự tên (last name ở vị trí đầu tiên) và sắp xếp lại danh sách.</p> + +<pre class="brush: js">// The name string contains multiple spaces and tabs, +// and may have multiple spaces between first and last names. +var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand "; + +var output = ["---------- Original String\n", names + "\n"]; + +// Prepare two regular expression patterns and array storage. +// Split the string into array elements. + +// pattern: possible white space then semicolon then possible white space +var pattern = /\s*;\s*/; + +// Break the string into pieces separated by the pattern above and +// store the pieces in an array called nameList +var nameList = names.split(pattern); + +// new pattern: one or more characters then spaces then characters. +// Use parentheses to "memorize" portions of the pattern. +// The memorized portions are referred to later. +pattern = /(\w+)\s+(\w+)/; + +// New array for holding names being processed. +var bySurnameList = []; + +// Display the name array and populate the new array +// with comma-separated names, last first. +// +// The replace method removes anything matching the pattern +// and replaces it with the memorized string—second memorized portion +// followed by comma space followed by first memorized portion. +// +// The variables $1 and $2 refer to the portions +// memorized while matching the pattern. + +output.push("---------- After Split by Regular Expression"); + +var i, len; +for (i = 0, len = nameList.length; i < len; i++){ + output.push(nameList[i]); + bySurnameList[i] = nameList[i].replace(pattern, "$2, $1"); +} + +// Display the new array. +output.push("---------- Names Reversed"); +for (i = 0, len = bySurnameList.length; i < len; i++){ + output.push(bySurnameList[i]); +} + +// Sort by last name, then display the sorted array. +bySurnameList.sort(); +output.push("---------- Sorted"); +for (i = 0, len = bySurnameList.length; i < len; i++){ + output.push(bySurnameList[i]); +} + +output.push("---------- End"); + +console.log(output.join("\n")); +</pre> + +<h3 id="Sử_dụng_những_kí_tự_đặc_biệt_để_xác_thực_đầu_vào">Sử dụng những kí tự đặc biệt để xác thực đầu vào</h3> + +<p>Trong ví dụ dưới đây, ta mong chờ người dùng nhập một số điện thoại. Khi người dùng ấn nút "Check", đoạn script sẽ kiểm tra tính xác thực của số vừa nhập. Nếu số đó hợp lệ (khớp với chuỗi kí tự được xác định bởi biểu thức chính quy), website sẽ hiển thị một tin nhắn cảm ơn người dùng và xác nhận số đó. Nếu số đó không hợp lệ, website sẽ thông báo người dùng rằng số điện thoại vừa nhập không hợp lệ.</p> + +<p><code>var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;</code></p> + +<p>Trong mẫu ngoặc tròn không nhớ (<code>?:</code>, biểu thức chính quy tìm 3 kí tự số <code>\d{3}</code> hoặc <code>|</code> 3 kí tự số trong cặp ngoặc tròn, (kết thúc mẫu ngoặc tròn không nhớ), sau đó là một kí tự gạch ngang, dấu chéo ngược, hoặc dấu chấm thập phân, và khi tìm thấy, nhớ kí tự vừa tìm được, tìm tiếp 3 kí tự số, theo sau là một so khớp được nhớ ở lần đầu tiên <code>([-\/\.]), </code>cuối cùng là 4 kí tự số.</p> + +<p>Sự kiện change được kích hoạt khi người dùng nhấp Enter.</p> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> + <meta http-equiv="Content-Script-Type" content="text/javascript"> + <script type="text/javascript"> + var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; + function testInfo(phoneInput){ + var OK = re.exec(phoneInput.value); + if (!OK) + window.alert(OK.input + " isn't a phone number with area code!"); + else + window.alert("Thanks, your phone number is " + OK[0]); + } + </script> + </head> + <body> + <p>Enter your phone number (with area code) and then click "Check". + <br>The expected format is like ###-###-####.</p> + <form action="#"> + <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button> + </form> + </body> +</html> +</pre> + +<div>{{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}</div> diff --git a/files/vi/web/javascript/guide/text_formatting/index.html b/files/vi/web/javascript/guide/text_formatting/index.html new file mode 100644 index 0000000000..c3a09c6617 --- /dev/null +++ b/files/vi/web/javascript/guide/text_formatting/index.html @@ -0,0 +1,250 @@ +--- +title: Text formatting +slug: Web/JavaScript/Guide/Text_formatting +translation_of: Web/JavaScript/Guide/Text_formatting +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}</div> +<p class="summary">Chương này giới thiệu cách làm việc với các chuỗi và văn bản trong JavaScript.</p> + +<h2 id="Dây">Dây</h2> + +<p>Kiểu <a href="/en-US/docs/Glossary/String">chuỗi</a> của JavaScript được sử dụng để thể hiện dữ liệu văn bản. Nó là một tập hợp các "phần tử" của các giá trị nguyên không dấu 16 bit (đơn vị mã UTF-16). Mỗi phần tử trong Chuỗi chiếm một vị trí trong Chuỗi. Phần tử đầu tiên là ở chỉ số 0, phần tử tiếp theo ở chỉ số 1, v.v. Độ dài của Chuỗi là số phần tử trong đó. Bạn có thể tạo chuỗi bằng cách sử dụng chuỗi ký tự hoặc chuỗi đối tượng.</p> + +<div class="hidden">THẬN TRỌNG: nếu bạn chỉnh sửa trang này, không bao gồm bất kỳ ký tự nào trên U + FFFF, cho đến khi lỗi MDN 857438 được khắc phục ( <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=857438">https://ormszilla.mozilla.org/show_orms.cgi?id=857438</a> ).</div> + +<h3 id="Chuỗi_ký_tự">Chuỗi ký tự</h3> + +<p>Bạn có thể tạo các chuỗi đơn giản bằng cách sử dụng dấu ngoặc đơn hoặc dấu ngoặc kép:</p> + +<pre class="brush: js notranslate">'foo' +"quán ba"</pre> + +<p>Các chuỗi nâng cao hơn có thể được tạo bằng các chuỗi thoát:</p> + +<h4 id="Trình_tự_thoát_thập_lục_phân">Trình tự thoát thập lục phân</h4> + +<p>The number after \x is interpreted as a <a href="https://en.wikipedia.org/wiki/Hexadecimal">hexadecimal</a> number.</p> + +<pre class="brush: js notranslate">'\xA9' // "©" +</pre> + +<h4 id="Unicode_escape_sequences">Unicode escape sequences</h4> + +<p>The Unicode escape sequences require at least four hexadecimal digits following <code>\u</code>.</p> + +<pre class="brush: js notranslate">'\u00A9' // "©"</pre> + +<h4 id="Unicode_code_point_escapes">Unicode code point escapes</h4> + +<p>New in ECMAScript 2015. With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to <code>0x10FFFF</code>. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.</p> + +<p>See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.</p> + +<pre class="brush: js notranslate">'\u{2F804}' + +// the same with simple Unicode escapes +'\uD87E\uDC04'</pre> + +<h3 id="String_objects">String objects</h3> + +<p>The {{jsxref("String")}} object is a wrapper around the string primitive data type.</p> + +<pre class="brush: js notranslate">const foo = new String('foo'); // Creates a String object +console.log(foo); // Displays: <span><span>[String: 'foo']</span></span> +typeof foo; // Returns 'object' +</pre> + +<p>You can call any of the methods of the <code>String</code> object on a string literal value—JavaScript automatically converts the string literal to a temporary <code>String</code> object, calls the method, then discards the temporary <code>String</code> object. You can also use the <code>String.length</code> property with a string literal.</p> + +<p>You should use string literals unless you specifically need to use a <code>String</code> object, because <code>String</code> objects can have counterintuitive behavior. For example:</p> + +<pre class="brush: js notranslate">const firstString = '2 + 2'; // Creates a string literal value +const secondString = new String('2 + 2'); // Creates a String object +eval(firstString); // Returns the number 4 +eval(secondString); // Returns the string "2 + 2"</pre> + +<p>A <code>String</code> object has one property, <code>length</code>, that indicates the number of UTF-16 code units in the string. For example, the following code assigns <code>helloLength</code> the value 13, because "Hello, World!" has 13 characters, each represented by one UTF-16 code unit. You can access each code unit using an array bracket style. You can't change individual characters because strings are immutable array-like objects:</p> + +<pre class="brush: js notranslate">const hello = 'Hello, World!'; +const helloLength = hello.length; +hello[0] = 'L'; // This has no effect, because strings are immutable +hello[0]; // This returns "H" +</pre> + +<p>Characters whose Unicode scalar values are greater than U+FFFF (such as some rare Chinese/Japanese/Korean/Vietnamese characters and some emoji) are stored in UTF-16 with two surrogate code units each. For example, a string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.</p> + +<p>A <code>String</code> object has a variety of methods: for example those that return a variation on the string itself, such as <code>substring</code> and <code>toUpperCase</code>.</p> + +<p>The following table summarizes the methods of {{jsxref("String")}} objects.</p> + +<table class="standard-table"> + <caption> + <h4 id="Methods_of_String">Methods of <code>String</code></h4> + </caption> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("String.charAt", "charAt")}}, {{jsxref("String.charCodeAt", "charCodeAt")}}, {{jsxref("String.codePointAt", "codePointAt")}}</td> + <td>Return the character or character code at the specified position in string.</td> + </tr> + <tr> + <td>{{jsxref("String.indexOf", "indexOf")}}, {{jsxref("String.lastIndexOf", "lastIndexOf")}}</td> + <td>Return the position of specified substring in the string or last position of specified substring, respectively.</td> + </tr> + <tr> + <td>{{jsxref("String.startsWith", "startsWith")}}, {{jsxref("String.endsWith", "endsWith")}}, {{jsxref("String.includes", "includes")}}</td> + <td>Returns whether or not the string starts, ends or contains a specified string.</td> + </tr> + <tr> + <td>{{jsxref("String.concat", "concat")}}</td> + <td>Combines the text of two strings and returns a new string.</td> + </tr> + <tr> + <td>{{jsxref("String.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}}</td> + <td>Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.</td> + </tr> + <tr> + <td>{{jsxref("String.split", "split")}}</td> + <td>Splits a <code>String</code> object into an array of strings by separating the string into substrings.</td> + </tr> + <tr> + <td>{{jsxref("String.slice", "slice")}}</td> + <td>Extracts a section of a string and returns a new string.</td> + </tr> + <tr> + <td>{{jsxref("String.substring", "substring")}}, {{jsxref("String.substr", "substr")}}</td> + <td>Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length.</td> + </tr> + <tr> + <td>{{jsxref("String.match", "match")}}, {{jsxref("String.matchAll", "matchAll")}}, {{jsxref("String.replace", "replace")}}, {{jsxref("String.search", "search")}}</td> + <td>Work with regular expressions.</td> + </tr> + <tr> + <td>{{jsxref("String.toLowerCase", "toLowerCase")}}, {{jsxref("String.toUpperCase", "toUpperCase")}}</td> + <td> + <p>Return the string in all lowercase or all uppercase, respectively.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.normalize", "normalize")}}</td> + <td>Returns the Unicode Normalization Form of the calling string value.</td> + </tr> + <tr> + <td>{{jsxref("String.repeat", "repeat")}}</td> + <td>Returns a string consisting of the elements of the object repeated the given times.</td> + </tr> + <tr> + <td>{{jsxref("String.trim", "trim")}}</td> + <td>Trims whitespace from the beginning and end of the string.</td> + </tr> + </tbody> +</table> + +<h3 id="Multi-line_template_literals">Multi-line template literals</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a> are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.</p> + +<p>Template literals are enclosed by the back-tick (` `) (<a class="external external-icon" href="https://en.wikipedia.org/wiki/Grave_accent">grave accent</a>) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (<code>${expression}</code>).</p> + +<h4 id="Multi-lines">Multi-lines</h4> + +<p>Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:</p> + +<pre class="brush: js notranslate">console.log('string text line 1\n\ +string text line 2'); +// "string text line 1 +// string text line 2"</pre> + +<p>To get the same effect with multi-line strings, you can now write:</p> + +<pre class="brush: js notranslate">console.log(`string text line 1 +string text line 2`); +// "string text line 1 +// string text line 2"</pre> + +<h4 id="Embedded_expressions">Embedded expressions</h4> + +<p>In order to embed expressions within normal strings, you would use the following syntax:</p> + +<pre class="brush: js notranslate">const five = 5; +const ten = 10; +console.log('Fifteen is ' + (five + ten) + ' and not ' + (2 * five + ten) + '.'); +// "Fifteen is 15 and not 20."</pre> + +<p>Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:</p> + +<pre class="brush: js notranslate">const five = 5; +const ten = 10; +console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`); +// "Fifteen is 15 and not 20."</pre> + +<p>For more information, read about <a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a> in the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a>.</p> + +<h2 id="Internationalization">Internationalization</h2> + +<p>The {{jsxref("Intl")}} object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} objects are properties of the <code>Intl</code> object.</p> + +<h3 id="Date_and_time_formatting">Date and time formatting</h3> + +<p>The {{jsxref("DateTimeFormat")}} object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.)</p> + +<pre class="brush: js notranslate">const msPerDay = 24 * 60 * 60 * 1000; + +// July 17, 2014 00:00:00 UTC. +const july172014 = new Date(msPerDay * (44 * 365 + 11 + 197)); + +const options = { year: '2-digit', month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', timeZoneName: 'short' }; +const americanDateTime = new Intl.DateTimeFormat('en-US', options).format; + +console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT +</pre> + +<h3 id="Number_formatting">Number formatting</h3> + +<p>The {{jsxref("NumberFormat")}} object is useful for formatting numbers, for example currencies.</p> + +<pre class="brush: js notranslate">const gasPrice = new Intl.NumberFormat('en-US', + { style: 'currency', currency: 'USD', + minimumFractionDigits: 3 }); + +console.log(gasPrice.format(5.259)); // $5.259 + +const hanDecimalRMBInChina = new Intl.NumberFormat('zh-CN-u-nu-hanidec', + { style: 'currency', currency: 'CNY' }); + +console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五 +</pre> + +<h3 id="Collation">Collation</h3> + +<p>The {{jsxref("Collator")}} object is useful for comparing and sorting strings.</p> + +<p>For example, there are actually two different sort orders in German, <em>phonebook</em> and <em>dictionary</em>. Phonebook sort emphasizes sound, and it’s as if “ä”, “ö”, and so on were expanded to “ae”, “oe”, and so on prior to sorting.</p> + +<pre class="brush: js notranslate">const names = ['Hochberg', 'Hönigswald', 'Holzman']; + +const germanPhonebook = new Intl.Collator('de-DE-u-co-phonebk'); + +// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]: +console.log(names.sort(germanPhonebook.compare).join(', ')); +// logs "Hochberg, Hönigswald, Holzman" +</pre> + +<p>Some German words conjugate with extra umlauts, so in dictionaries it’s sensible to order ignoring umlauts (except when ordering words differing <em>only</em> by umlauts: <em>schon</em> before <em>schön</em>).</p> + +<pre class="brush: js notranslate">const germanDictionary = new Intl.Collator('de-DE-u-co-dict'); + +// as if sorting ["Hochberg", "Honigswald", "Holzman"]: +console.log(names.sort(germanDictionary.compare).join(', ')); +// logs "Hochberg, Holzman, Hönigswald" +</pre> + +<p>For more information about the {{jsxref("Intl")}} API, see also <a href="https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/">Introducing the JavaScript Internationalization API</a>.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}</div> diff --git a/files/vi/web/javascript/guide/using_promises/index.html b/files/vi/web/javascript/guide/using_promises/index.html new file mode 100644 index 0000000000..8ed6befe37 --- /dev/null +++ b/files/vi/web/javascript/guide/using_promises/index.html @@ -0,0 +1,329 @@ +--- +title: Sử dụng Promise +slug: Web/JavaScript/Guide/Using_promises +tags: + - Hướng dẫn + - JavaScript + - Promise + - bất đồng bộ + - trình độ trung cấp +translation_of: Web/JavaScript/Guide/Using_promises +--- +<div>{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<p class="summary">{{jsxref("Promise")}} là một đối tượng thể hiện cho sự hoàn thành hoặc thất bại của một tiến trình bất đồng bộ. Vì đa số chúng ta là người sử dụng Promise được tạo sẵn, bài viết này sẽ hướng dẫn cách sử dụng Promise trước khi hướng dẫn cách tạo ra chúng.</p> + +<p>Về cơ bản, một promise là một đối tượng trả về mà bạn gắn callback vào nó thay vì truyền callback vào trong một hàm.</p> + +<p>Giả sử chúng ta có một hàm, <code>createAudioFileAsync()</code>, mà nó sẽ tạo ra một file âm thanh từ config object và hai hàm callback một cách bất đồng bộ, một hàm sẽ được gọi khi file âm thanh được tạo thành công, và một hàm được gọi khi có lỗi xảy ra.</p> + +<p>Sau đây là code ví dụ sử dụng <code>createAudioFileAsync()</code>:</p> + +<pre class="brush: js line-numbers language-js">function successCallback(result) { + console.log("Audio file ready at URL: " + result); +} + +function failureCallback(error) { + console.log("Error generating audio file: " + error); +} + +createAudioFileAsync(audioSettings, successCallback, failureCallback); +</pre> + +<p>Thay vì như trên, các hàm bất đồng bộ hiện đại sẽ trả về đối tượng promise mà bạn sẽ gắn callback vào nó:</p> + +<p>Nếu hàm <code>createAudioFileAsync()</code> được viết lại sử dụng promise, thì việc sử dụng nó sẽ chỉ đơn giản như sau:</p> + +<pre class="brush: js">createAudioFileAsync(audioSettings).then(successCallback, failureCallback);</pre> + +<p>Nếu viết dài dòng hơn thì sẽ là:</p> + +<pre class="brush: js line-numbers language-js">const promise = createAudioFileAsync(audioSettings); +promise.then(successCallback, failureCallback);</pre> + +<p>Chúng ta gọi đây là <em>một lời gọi hàm bất đồng bộ</em> (<em>asynchronous function call)</em>. Cách tiếp cận này có nhiều ưu điểm, mà chúng ta sẽ lần lượt xem xét bên dưới.</p> + +<h2 id="Sự_đảm_bảo">Sự đảm bảo</h2> + +<p>Không như cách truyền callback kiểu cũ, một promise có những đảm bảo như sau:</p> + +<ul> + <li>Callback sẽ không bao giờ được gọi trước khi <a href="/en-US/docs/Web/JavaScript/EventLoop#Run-to-completion">hoàn tất lượt chạy</a> của một <em>JavaScript event loop</em>.</li> + <li>Callback được thêm vào <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code> <em>sau khi</em> tiến trình bất đồng bộ đã hoàn thành vẫn được gọi, và theo nguyên tắc ở trên.</li> + <li>Nhiều callback có thể được thêm vào bằng cách gọi <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code> nhiều lần. Mỗi callback sẽ được gọi lần lượt, theo thứ tự mà chúng được thêm vào.</li> +</ul> + +<p>Một trong những đặc tính tuyệt vời của promise là <strong>chaining</strong> (gọi nối).</p> + +<h2 id="Chaining_(gọi_nối)">Chaining (gọi nối)</h2> + +<p>Có một nhu cầu phổ biến đó là thực thi hai hay nhiều tiến trình bất đồng độ liên tiến nhau, cái sau bắt đầu ngay khi cái trước hoàn tất, với giá trị truyền vào là kết quả từ bước trước đó. Mục tiêu này có thể đạt được với một <em>chuỗi promise</em> (<strong>promise chain</strong>).</p> + +<p>Sau đây là cách nó hoạt động: hàm <code>then()</code> trả về một <strong>promise mới</strong>, khác với hàm ban đầu:</p> + +<pre class="brush: js">const promise = doSomething(); +const promise2 = promise.then(successCallback, failureCallback); +</pre> + +<p>hoặc</p> + +<pre class="brush: js">const promise2 = doSomething().then(successCallback, failureCallback); +</pre> + +<p>Promise thứ hai (<code>promise2</code>) không chỉ đại diện cho việc hoàn thành <code>doSomething()</code> mà còn cho cả <code>successCallback</code> hoặc <code>failureCallback</code> mà bạn đưa vào, mà chúng có thể là những hàm bất đồng bộ khác trả về promise. Trong trường hợp đó, bất kỳ callback nào được thêm vào cho <code>promise2</code> cũng sẽ được xếp phía sau promise trả về bởi một trong hai <code>successCallback</code> hoặc <code>failureCallback</code>.</p> + +<p>Tóm lại, mỗi promise đại diện cho việc hoàn tất của một bước bất đồng bộ trong chuỗi.</p> + +<p>Trước khi có promise, kết quả của việc thực hiện một chuỗi các thao tác bất đồng bộ theo cách cũ là một "thảm họa" kim tự tháp callback:</p> + +<pre class="brush: js">doSomething(function(result) { + doSomethingElse(result, function(newResult) { + doThirdThing(newResult, function(finalResult) { + console.log('Got the final result: ' + finalResult); + }, failureCallback); + }, failureCallback); +}, failureCallback); +</pre> + +<p>Thay vào đó, với cách tiếp cận hiện đại, chúng ta sẽ gắn các callback vào các promise trả về, tạo thành một chuỗi promise:</p> + +<pre class="brush: js">doSomething().then(function(result) { + return doSomethingElse(result); +}) +.then(function(newResult) { + return doThirdThing(newResult); +}) +.then(function(finalResult) { + console.log('Got the final result: ' + finalResult); +}) +.catch(failureCallback); +</pre> + +<p>Tham số cho <code>then</code> là không bắt buộc, và <code>catch(failureCallback)</code> là cách viết gọn của <code>then(null, failureCallback)</code>. Bạn có thể thấy chuỗi promise dùng với <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a> như sau:</p> + +<pre class="brush: js">doSomething() +.then(result => doSomethingElse(result)) +.then(newResult => doThirdThing(newResult)) +.then(finalResult => { + console.log(`Got the final result: ${finalResult}`); +}) +.catch(failureCallback); +</pre> + +<p><strong>Quan trọng:</strong> hãy nhớ luôn trả về kết quả, nếu không, callback sẽ không nhận được kết quả từ promise trước đó (với arrow functions <code>() => x</code> được rút gọn từ <code>() => { return x; }</code>)</p> + +<h3 id="Gọi_nối_sau_hàm_catch">Gọi nối sau hàm catch</h3> + +<p>Bạn có thể tiếp tục gọi chuỗi <code>then</code> sau một hàm bắt lỗi <code>catch</code>. Điều này cho phép code của bạn luôn thực hiện một thao tác nào đó cho dù đã có lỗi xảy ra ở một bước nào đó trong chuỗi. Hãy xem ví dụ sau:</p> + +<pre class="brush: js">new Promise((resolve, reject) => { + console.log('Initial'); + + resolve(); +}) +.then(() => { + throw new Error('Something failed'); + + console.log('Do this'); +}) +.catch(() => { + console.log('Do that'); +}) +.then(() => { + console.log('Do this, no matter what happened before'); +}); +</pre> + +<p>Đoạn code này sẽ log ra những dòng sau:</p> + +<pre>Initial +Do that +Do this, no matter what happened before +</pre> + +<p><strong>Ghi chú:</strong> Dòng text <q>Do this</q> không hiển thị bởi vì Error <q>Something failed</q> đã xảy ra trước và gây lỗi trong chuỗi promise.</p> + +<h2 id="Xử_lý_lỗi_tập_trung">Xử lý lỗi tập trung</h2> + +<p>Bạn hãy nhớ lại đoạn code kim tự tháp thảm họa ở trên, có đến 3 lần hàm <code>failureCallback</code> được sử dụng. Trong khi đó, bạn chỉ cần khai báo một lần vào cuối chuỗi promise:</p> + +<pre class="brush: js">doSomething() +.then(result => doSomethingElse(result)) +.then(newResult => doThirdThing(newResult)) +.then(finalResult => console.log(`Got the final result: ${finalResult}`)) +.catch(failureCallback); +</pre> + +<p>Về căn bản, một chuỗi promise sẽ dừng lại nếu có lỗi xảy ra, và nó sẽ truy xuống dưới cuối chuỗi để tìm và gọi hàm xử lý lỗi <code>catch</code>. Cách hoạt động này khá giống với cách thức hoạt động của <code>try catch</code> của code đồng bộ:</p> + +<pre class="brush: js">try { + const result = syncDoSomething(); + const newResult = syncDoSomethingElse(result); + const finalResult = syncDoThirdThing(newResult); + console.log(`Got the final result: ${finalResult}`); +} catch(error) { + failureCallback(error); +} +</pre> + +<p>Và vì lý do trên, <code>try catch</code> cũng được sử dụng để bắt lỗi cho code bất đồng bộ khi viết với cú pháp <a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a> của ECMAScript 2017.</p> + +<pre class="brush: js">async function foo() { + try { + const result = await doSomething(); + const newResult = await doSomethingElse(result); + const finalResult = await doThirdThing(newResult); + console.log(`Got the final result: ${finalResult}`); + } catch(error) { + failureCallback(error); + } +} +</pre> + +<p>Cú pháp trên được xây dựng từ Promise, VD: <code>doSomething()</code> chính là hàm được viết với Promise ở trên. Bạn có thể đọc thêm về cú pháp đó <a href="https://developers.google.com/web/fundamentals/getting-started/primers/async-functions">ở đây</a>.</p> + +<p>Promise giúp giải quyết một hạn chế cơ bản của kim tự tháp callback, đó là cho phép bắt được tất cả các loại lỗi, từ những lỗi <em>throw Error</em> cho đến lỗi về cú pháp lập trình. Điều này rất cần thiết cho việc phối hợp các hàm xử lý bất đồng bộ.</p> + +<h2 id="Tạo_Promise_từ_API_có_kiểu_callback_cũ">Tạo Promise từ API có kiểu callback cũ</h2> + +<p>Một {{jsxref("Promise")}} có thể được tạo mới từ đầu bằng cách sử dụng hàm constructor. Tuy nhiên cách này thường chỉ dùng để bọc lại API kiểu cũ.</p> + +<p>Trong môi trường lý tưởng, tất cả các hàm bất đồng bộ đều trả về promise. Tuy nhiên vẫn còn nhiều API yêu cầu hàm callback được truyền vào theo kiểu cũ. Ví dụ điển hình nhất chính là hàm {{domxref("WindowTimers.setTimeout", "setTimeout()")}}:</p> + +<pre class="brush: js">setTimeout(() => saySomething("10 seconds passed"), 10000); +</pre> + +<p>Trộn lẫn callback và promise có nhiều vấn đề tiềm ẩn. Nếu hàm <code>saySomething()</code> xảy ra lỗi bên trong nó, sẽ không có gì bắt được lỗi này. <code>setTimeout</code> là để đổ lỗi cho điều này.</p> + +<p>May mắn là chúng ta có thể bọc <code>setTimeout</code> lại với promise. Cách làm tốt nhất là bọc hàm có vấn đề ở cấp thấp nhất, để rồi sau đó chúng ta không phải gọi nó trực tiếp nữa:</p> + +<pre class="brush: js">const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); + +wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback); +</pre> + +<p>Về căn bản, constructor của Promise nhận vào một hàm thực thi với hai tham số hàm resolve và reject để chúng ta có thể giải quyết hoặc từ chối promise một cách thủ công. Bởi vì hàm <code>setTimeout()</code> không bao giờ gây ra lỗi, chúng ta bỏ qua reject trong trường hợp này.</p> + +<h2 id="Phối_hợp_các_Promise">Phối hợp các Promise</h2> + +<p>{{jsxref("Promise.resolve()")}} và {{jsxref("Promise.reject()")}} là những phương thức để lấy nhanh một promise đã được giải quyết hoặc từ chối sẵn. Những phương thức này có thể hữu dụng trong một số trường hợp.</p> + +<p>{{jsxref("Promise.all()")}} và {{jsxref("Promise.race()")}} là hai hàm tiện ích dùng để phối hợp các thao tác bất đồng bộ chạy song song.</p> + +<p>Chúng ta có thể cho các tiến trình bất đồng bộ bắt đầu song song và chờ cho đến khi tất cả đều hoàn tất như sau:</p> + +<pre class="brush: js">Promise.all([func1(), func2(), func3()]) +.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ }); +</pre> + +<p>Việc phối hợp các tiến trình bất đồng bộ diễn ra tuần tự không có sẵn tiện ích nhưng có thể viết mẹo với <code>reduce</code> như sau:</p> + +<pre class="brush: js">[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve()) +.then(result3 => { /* use result3 */ }); +</pre> + +<p>Về cơ bản, chúng ta đang rút gọn (<em>reduce</em>, tạm dịch) một mảng các hàm bất đồng bộ thành một chuỗi promise: <code>Promise.resolve().then(func1).then(func2).then(func3);</code></p> + +<p>Thao tác trên có thể được viết thành một hàm dùng lại được, như cách chúng ta hay làm trong <em>functional programming</em>:</p> + +<pre class="brush: js">const applyAsync = (acc,val) => acc.then(val); +const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));</pre> + +<p>Hàm <code>composeAsync()</code> sẽ nhận vào tham số là các hàm xử lý bất đồng bộ với số lượng bất kỳ, và trả và một hàm mới mà khi gọi, nó nhận vào một giá trị ban đầu mà giá trị này sẽ được truyền vào tuần tự qua các hàm xử lý bất đồng bộ:</p> + +<pre class="brush: js">const transformData = composeAsync(func1, func2, func3); +const result3 = transformData(data); +</pre> + +<p>Trong ECMAScript 2017, việc phối hợp tuần tự các promise có thể thực hiện đơn giản hơn với async/await:</p> + +<pre class="brush: js">let result; +for (const f of [func1, func2, func3]) { + result = await f(result); +} +/* use last result (i.e. result3) */ +</pre> + +<h2 id="Thời_điểm_thực_thi">Thời điểm thực thi</h2> + +<p>Để nhất quán và tránh những bất ngờ, các hàm truyền vào cho <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code> sẽ không bao giờ được thực thi đồng bộ, ngay với cả những promíe đã được giải quyết:</p> + +<pre class="brush: js">Promise.resolve().then(() => console.log(2)); +console.log(1); // 1, 2 +</pre> + +<p>Thay vì chạy ngay lập tức, promise callback được đặt vào hàng đợi <strong>microtask</strong>, điều này có nghĩa là nó sẽ chỉ được thực thi khi hàng đợi được làm rỗng ( các promise đều được giải quy) cuối event loop hiện tại của JavaScript:</p> + +<pre class="brush: js">const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); + +wait().then(() => console.log(4)); +Promise.resolve().then(() => console.log(2)).then(() => console.log(3)); +console.log(1); // 1, 2, 3, 4 +</pre> + +<h2 id="Lồng_cấp">Lồng cấp</h2> + +<p>Chuỗi Promise đơn giản chỉ nên có một cấp và không lồng vào nhau, vì lồng cấp sẽ dẫn đến những tổ hợp phức tạp dễ gây ra lỗi. Xem <a href="#Một_số_sai_lầm_phổ_biến">các sai lầm thường gặp</a>.</p> + +<p>Lồng nhau là một cấu trúc kiểm soát để giới hạn phạm vi của các câu lệnh <code>catch</code>. Cụ thể, một câu lệnh <code>catch</code> lồng bên trong chỉ có thể bắt được những lỗi trong phạm vi của nó và bên dưới, không phải là lỗi phía bên trên của chuỗi bên ngoài phạm vi lồng nhau. Khi được sử dụng một cách hợp lý, nó mang lại độ chính xác cao hơn trong việc khôi phục lỗi:</p> + +<pre class="brush: js">doSomethingCritical() +.then(result => doSomethingOptional() + .then(optionalResult => doSomethingExtraNice(optionalResult)) + .catch(e => {})) // Ignore if optional stuff fails; proceed. +.then(() => moreCriticalStuff()) +.catch(e => console.log("Critical failure: " + e.message)); +</pre> + +<p>Lưu ý rằng các bước tuỳ chọn ở đây được lồng vào trong, không phải từ việc thụt đầu dòng, mà từ vị trí đặt dấu <code>(</code> và <code>)</code> xung quanh chúng.</p> + +<p>Câu lệnh <code>catch</code> bên trong chỉ bắt lỗi từ <code>doSomethingOptional()</code> và <code>doSomethingExtraNice()</code>, sau đó nó sẽ tiếp tục với <code>moreCriticalStuff()</code>. Điều quan trọng là nếu <code>doSomethingCritical()</code> thất bại, lỗi của nó chỉ bị bắt bởi <code>catch</code> cuối cùng (bên ngoài).</p> + +<h2 id="Một_số_sai_lầm_phổ_biến">Một số sai lầm phổ biến</h2> + +<p>Dưới đây là một số lỗi phổ biến cần chú ý khi sử dụng chuỗi promise. Một số trong những sai lầm này biểu hiện trong ví dụ sau:</p> + +<pre class="brush: js example-bad">// Một ví dụ có đến 3 sai lầm! +doSomething().then(function(result) { + doSomethingElse(result) // Quên trả về promise từ chuỗi lồng bên trong + lồng nhau không cần thiết + .then(newResult => doThirdThing(newResult)); +}).then(() => doFourthThing()); +// Quên kết thúc chuỗi bằng một hàm catch! +</pre> + +<p>Sai lầm đầu tiên là không kết nối mọi thứ với nhau đúng cách. Điều này xảy ra khi chúng ta tạo ra một promise mới nhưng quên trả lại. Hậu quả là chuỗi bị hỏng, hay đúng hơn, chúng ta có hai chuỗi độc lập cùng chạy. Có nghĩa là <code>doFourthThing()</code> sẽ không đợi <code>doSomethingElse()</code> hoặc <code>doThirdThing()</code> kết thúc và sẽ chạy song song với chúng, có khả năng ngoài ý muốn. Các chuỗi riêng biệt cũng sẽ xử lý lỗi riêng biệt, dẫn đến khả năng lỗi không được xử lý.</p> + +<p>Sai lầm thứ hai là làm lồng nhau không cần thiết, cho phép sai lầm đầu tiên. Lồng nhau cũng giới hạn phạm vi của các trình xử lý lỗi bên trong, điều mà nếu không cố ý thì có thể dẫn đến các lỗi chưa được xử lý. Một biến thể của điều này là <a href="https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it">promise constructor anti-pattern</a>, kết hợp lồng với việc sử dụng dự phòng của promise constructor để bọc mã đã sử dụng promise.</p> + +<p>Sai lầm thứ ba là quên chấm dứt chuỗi với <code>catch</code>. Chuỗi promise không kết thúc bằng <code>catch</code>, khi bị reject sẽ gây ra lỗi "uncaught promise rejection" trong hầu hết các trình duyệt.</p> + +<p>Một nguyên tắc tốt là luôn luôn trả lại hoặc chấm dứt chuỗi promise, và ngay khi bạn nhận được một promise mới, hãy trả lại ngay lập tức:</p> + +<pre class="brush: js example-good">doSomething() +.then(function(result) { + return doSomethingElse(result); +}) +.then(newResult => doThirdThing(newResult)) +.then(() => doFourthThing()) +.catch(error => console.log(error)); +</pre> + +<p>Lưu ý rằng <code>() => x</code> được rút gọn từ <code>() => { return x; }</code>.</p> + +<p>Bây giờ chúng ta có một chuỗi xác định duy nhất với xử lý lỗi thích hợp.</p> + +<p>Sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a> sẽ khắc phục hầu hết, nếu không muốn nói là tất cả các vấn đề trên đây — với một hạn chế cũng là một lỗi thường gặp với cú pháp này đó là việc quên từ khoá <a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>await</code></a>.</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Promise.then()")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a> </li> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> + <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> + <li><a href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c#.dzlqh6ski">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li> + <li><a href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li> + <li><a href="http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li> +</ul> + +<p>{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}</p> diff --git a/files/vi/web/javascript/guide/working_with_objects/index.html b/files/vi/web/javascript/guide/working_with_objects/index.html new file mode 100644 index 0000000000..6fdc2dba69 --- /dev/null +++ b/files/vi/web/javascript/guide/working_with_objects/index.html @@ -0,0 +1,500 @@ +--- +title: Working with objects +slug: Web/JavaScript/Guide/Working_with_Objects +translation_of: Web/JavaScript/Guide/Working_with_Objects +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}</div> + +<p class="summary">JavaScript được thiết kế trên mô hình đối tượng đơn giản. Một object là một tập hợp các thuộc tính, và một thuộc tính là sự liên kết giữa một cái tên và giá trị. Giá trị của một thuộc tính có thể là một hàm. Ngoài những đối tượng được định nghĩa trước trong trình duyệt, bạn có thể định nghĩa những đối tượng của riêng bạn. Chương này mô tả cách sử dụng những đối tượng, những thuộc tính, những hàm, và phương thức, cũng như cách thức để tạo đối tượng riêng của mình.</p> + +<h2 id="Tổng_quan_về_Objects">Tổng quan về Objects</h2> + +<p>Objects trong JavaScript, cũng tương tự như những ngôn ngữ khác, có thể so sánh như đối tượng trong đời thường. Khái niệm của objects trong JavaScript có thể được hiểu như những đối tượng thực tế trong đời thực.</p> + +<p>Trong JavaScript, một object là một thực thể độc lập, với thuộc tính và kiểu. Lấy cái tách làm ví dụ. Cái tách là một object có những thuộc tính của riêng nó. Một cái tách có màu sắc, thiết kế, trọng lượng, chất liệu tạo ra nó, vân vân... Tương tự như vậy, JavaScript objects có thể có những thuộc tính định nghĩa nên đặc tính của nó.</p> + +<h2 id="Objects_and_thuộc_tính">Objects and thuộc tính</h2> + +<p>Một JavaScript object có những thuộc tính liên kết với nó. Một thuộc tính của một object có thể được giải thích như là một biến mà được gắn vào object đó. Những thuộc tính của object cơ bản cũng là những biến JavaScript bình thường, chỉ đặc biệt là được gắn lên object. Thuộc tính của object định nghĩa đặc tính của object. Chúng ta truy xuất thuộc tính của object với ký hiệu ".":</p> + +<pre class="brush: js">objectName.propertyName +</pre> + +<p>Giống như những biến JavaScript, cả tên của object (có thể được xem như là 1 biến thông thường) và tên thuộc tính thì cũng phân biệt hoa thường. Bạn có thể định nghĩa một thuộc tính bằng cách gán giá trị cho nó. Ví dụ hãy tạo đối tượng myCar và gắn thuộc tính cho nó như <code>make</code>, <code>model</code>, and <code>year</code> như sau:</p> + +<pre class="brush: js">var myCar = new Object(); +myCar.make = 'Ford'; +myCar.model = 'Mustang'; +myCar.year = 1969; +</pre> + +<p>Những thuộc tính không được gán giá trị sẽ có giá trị {{jsxref("undefined")}} (lưu ý nó là không {{jsxref("null")}}).</p> + +<pre class="brush: js">myCar.color; // undefined</pre> + +<p>Thuộc tính của JavaScript object có thể được truy xuất hoặc thiết lập bằng cách dùng dấu ngoặc vuông (xem <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessors</a> để tham khảo chi tiết). Objects thỉnh thoảng cũng được gọi là <em>mảng liên kết, </em>vì mỗi thuộc tính được liên kết với một giá trị kiểu chuỗi mà có thể được dùng để truy xuất thuộc tính đó. Ví dụ bạn có thể truy xuất những thuộc tính của <code>myCar</code> object như sau:</p> + +<pre class="brush: js">myCar['make'] = 'Ford'; +myCar['model'] = 'Mustang'; +myCar['year'] = 1969; +</pre> + +<p>Tên thuộc tính của một object có thế là chuỗi ký tự hợp lệ bất kỳ, hoặc bất kỳ thứ gì có thể chuyển đổi được thành chuỗi, bao gồm cả chuỗi rỗng. Tuy nhiên, bất kỳ tên thuộc tính nào mà không phải là 1 định danh hợp lệ trong JavaScript (ví dụ, một thuộc tính mà tên có khoảng trắng hoặc gạch ngang, hoặc bắt đầu bằng số) chỉ có thể truy xuất bằng cách dùng dấu ngoặc vuông []. Ký pháp này cũng rất hữu dụng khi tên thuộc tính được xác định động (khi tên thuộc tính chỉ được xác định lúc thực thi). Như trong ví dụ sau:</p> + +<pre class="brush: js">// Khởi tạo 4 biến và gán giá trị cho chúng trên cùng một dòng lệnh +// phân cách bởi dấu "," +var myObj = new Object(), + str = 'myString', + rand = Math.random(), + obj = new Object(); + +myObj.type = 'Dot syntax'; +myObj['date created'] = 'String with space'; +myObj[str] = 'String value'; +myObj[rand] = 'Random Number'; +myObj[obj] = 'Object'; +myObj[''] = 'Even an empty string'; + +console.log(myObj); +</pre> + +<p>Chú ý tất cả biểu thức được làm khóa trong dấu ngoặc vuông đều được chuyển đổi thành kiểu chuỗi, bởi vì objects trong JavaScript chỉ chấp nhận khóa là kiểu chuỗi. Ví dụ trong đoạn mã trên khi khóa <code>obj</code> được thêm vào <code>myObj</code>, JavaScript sẻ gọi phương thức <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString">obj.toString()</a>, và lấy kết quả đó làm khóa.</p> + +<p>Bạn cũng có thể truy xuất thuộc tính bằng cách dùng giá trị chuỗi mà nó được lưu trong một biến:</p> + +<pre class="brush: js">var propertyName = 'make'; +myCar[propertyName] = 'Ford'; + +propertyName = 'model'; +myCar[propertyName] = 'Mustang'; +</pre> + +<p>Bạn có thể sử dụng dấu ngoặc vuông với <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code> để duyệt qua tất cả thuộc tính có thể đếm của object. Để minh họa cách nó hoạt động, hãy xem xét hàm sau đây, nó sẽ hiển thị những thuộc tính của đối tượng dựa vào 2 đối số gồm đối tượng (<code>obj</code>) và tên (<code>objName</code>) của đối tượng truyền vào cho hàm:</p> + +<pre class="brush: js">function showProps(obj, objName) { + var result = ''; + for (var i in obj) { + // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain + if (obj.hasOwnProperty(i)) { + result += objName + '.' + i + ' = ' + obj[i] + '\n'; + } + } + return result; +} +</pre> + +<p>Như vậy, khi ta gọi <code>showProps(myCar, "myCar")</code> thì kết quả được trả về như sau:</p> + +<pre class="brush: js">myCar.make = Ford +myCar.model = Mustang +myCar.year = 1969</pre> + +<h2 id="Liệt_kê_những_thuộc_tính_của_một_object">Liệt kê những thuộc tính của một object</h2> + +<p>Bắt đầu từ <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla" title="en-US/docs/JavaScript/ECMAScript 5 support in Mozilla">ECMAScript 5</a>, có 3 cách để liệt kê/duyệt danh sách thuộc tính của object:</p> + +<ul> + <li>Câu lệnh lặp <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in" title="en-US/docs/JavaScript/Reference/Statements/for...in">for...in</a></code><br> + Cách này duyệt qua tất cả thuộc tính có thể duyệt của một object và chuỗi prototype của nó</li> + <li>{{jsxref("Object.keys", "Object.keys(o)")}}<br> + Phương thức này trả về một mảng tất cả tên những thuộc tính có thể liệt kê mà gắn trực tiếp trên object <code>o</code> (không phải từ chuỗi prototype)</li> + <li>{{jsxref("Object.getOwnPropertyNames", "Object.getOwnPropertyNames(o)")}}<br> + Phương thức này trả về một mảng tất cả tên những thuộc tính (có thể liệt kê hoặc không) mà gắn trực tiếp trên object <code>o</code> (không phải từ chuỗi prototype)</li> +</ul> + +<p>Trước ECMAScript 5, không có cách thức có sẵn để liệt kê tất cả thuộc tính của một object. Tuy nhiên, chúng ta có thực hiện việc đó bằng hàm sau:</p> + +<pre class="brush: js">function listAllProperties(o) { + var objectToInspect; + var result = []; + + for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) { + result = result.concat(Object.getOwnPropertyNames(objectToInspect)); + } + + return result; +} +</pre> + +<p>Cách này rất hữu ích khi chúng ta muốn hiển thị những thuộc tính ẩn (những thuộc tính trong chuỗi prototype mà không thể truy xuất thông qua object, bởi vì một thuộc tính khác có cùng tên ở lớp trước của chuỗi prototype đã đè lên nó). Việc liệt kê những thuộc tính có thể truy xuất chỉ có thể dễ dàng hoàn thành bằng cách xóa bỏ trùng lặp trong mảng.</p> + +<h2 id="Tạo_những_object_mới">Tạo những object mới</h2> + +<p>JavaScript có một số object được định nghĩa sẵn. Ngoài ra, bạn có thể tạo định nghĩa những object mới. Bạn có thể tạo một object sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">bộ khởi tạo object (object initializer).</a> Cách khác, bạn có thể tạo hàm dựng và rồi khởi tạo đối tượng bằng cách gọi hàm đó với toán tử <code>new</code> đặt trước.</p> + +<h3 id="Sử_dụng_bộ_khởi_tạo_object"><a id="Object_initializers" name="Object_initializers">Sử dụng bộ khởi tạo object</a></h3> + +<p>Ngoài việc khởi tạo object bằng cách dùng hàm dựng, bạn có thể tạo object bằng cách sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">bộ khởi tạo (object initializer)</a>. Sử dụng bộ khởi tạo thỉnh thoảng cũng được hiểu là cách khởi tạo bằng cách dùng literal. "Bộ khởi tạo" ("Object initializer") thì đồng nhất với thuật ngữ được sử dụng trong C++.</p> + +<p>Cú pháp cho việc tạo một object bằng bộ khởi tạo la:</p> + +<pre class="brush: js">var obj = { property_1: value_1, // property_# may be an identifier... + 2: value_2, // or a number... + // ..., + 'property n': value_n }; // or a string +</pre> + +<p>Trong đó <code>obj</code> là tên của object mới, mỗi <code>property_<em>i</em></code> là một định danh (hoặc là một tên, một số, hoặc một chuỗi dạng literal), và mỗi <code>value_<em>i</em></code> là một biểu thức mà giá trị được gán cho <code>property_<em>i</em></code> . <code>obj</code> và phép gán là không bắt buộc; nếu bạn không cần tham chiếu đến object đó ở chổ khác, bạn không cần assign nó cho một biến. (lưu ý bạn có thể cần bao object literal lại bằng dấu ngoặc nếu nó xuất hiện ở chổ cần như là một câu lệnh, làm như vậy để tránh gây nhầm lẩn với câu lệnh khối.)</p> + +<p>Bộ khởi tạo object là những biểu thức, và mỗi bộ khởi tạo object sẽ tạo ra object mỗi khi biểu thức đó được tính toán. Bộ khởi tạo object tạo ra những đối tượng riêng biệt và chúng không bằng nhau khi so sánh bằng <code>==</code>. Những đối tượng được tạo ra bằng cách <code>new Object()</code> cũng như những đối tượng được tạo ra bằng object literal đều là thực thể (instance) của <code>Object</code>.</p> + +<p>Câu lệnh sau tạo một đối tượng và gán nó cho biến <code>x</code> khi và chỉ khi biểu thức <code>cond</code> là true:</p> + +<pre class="brush: js">if (cond) var x = {greeting: 'hi there'}; +</pre> + +<p>Đoạn mã sau tạo đối tượng <code>myHonda</code> với ba thuộc tính. Lưu ý thuộc tính <code>engine</code> cũng là một object và nó có những thuộc tính riêng của nó.</p> + +<pre class="brush: js">var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}; +</pre> + +<p>Bạn cũng có thể dùng bộ khởi tạo object để tạo mảng. Tham khảo <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Array_literals">array literals.</a></p> + +<h3 id="Sử_dụng_hàm_dựng">Sử dụng hàm dựng</h3> + +<p>Ngoài ra, bạn có thể tạo một object với hai bước sau đây:</p> + +<ol> + <li>Định nghĩa kiểu cho object bằng cách khai báo một hàm dựng. Bạn nên đặt tên hàm với chữ hoa cho ký tự đầu tiên.</li> + <li>Tạo một thực thể của đối tượng với toán tử <code>new</code>.</li> +</ol> + +<p>Để định nghĩa một kiểu dữ liệu object, tạo một hàm cho kiểu dữ liệu đó rồi chỉ định tên, những thuộc tính và phương thưc. Ví dụ, giả sử bạn muốn tạo một kiểu dữ liệu cho cars. Bạn đặt tên cho kiểu dữ liệu đó là <code>Car</code>, và bạn muốn nó có những thuộc tính như make, model, và year. Để làm được điểu này, bạn sẽ viết hàm sau:</p> + +<pre class="brush: js">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> + +<p>Lưu ý cách sử dụng <code>this</code> để gán trị giá trị cho những thuộc tính của object dựa vào giá trị được truyền vào cho hàm.</p> + +<p>Bây giờ bạn có thể tạo một object tên <code>mycar</code> như sau:</p> + +<pre class="brush: js">var mycar = new Car('Eagle', 'Talon TSi', 1993); +</pre> + +<p>Câu lệnh này tạo <code>mycar</code> gán những giá trị cụ thể cho những thuộc tính của nó. Giá trị của <code>mycar.make</code> là chuỗi "Eagle", <code>mycar.year</code> là số 1993, và tiếp tuc như thế.</p> + +<p>Bạn có thể tạo bao nhiêu <code>Car</code> object đều được bằng toán tử <code>new</code>. Như ví dụ sau:</p> + +<pre class="brush: js">var kenscar = new Car('Nissan', '300ZX', 1992); +var vpgscar = new Car('Mazda', 'Miata', 1990); +</pre> + +<p>Một object có thể có một thuộc tính mà giá trị là một object khác. Ví dụ như, giả sử bạn định nghĩa một object tên <code>person</code> như sau:</p> + +<pre class="brush: js">function Person(name, age, sex) { + this.name = name; + this.age = age; + this.sex = sex; +} +</pre> + +<p>và sau đó khởi tạo hai object <code>person</code> mới như sau:</p> + +<pre class="brush: js">var rand = new Person('Rand McKinnon', 33, 'M'); +var ken = new Person('Ken Jones', 39, 'M'); +</pre> + +<p>Và rồi, bạn có thể viết lại định nghĩa của <code>Car</code> để thêm thuộc tính <code>owner</code> mà nhận giá trị là một đối tượng kiểu <code>person</code>, như sau:</p> + +<pre class="brush: js">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} +</pre> + +<p>Để khởi tạo object mới, bạn viết những câu lệnh sau:</p> + +<pre class="brush: js">var car1 = new Car('Eagle', 'Talon TSi', 1993, rand); +var car2 = new Car('Nissan', '300ZX', 1992, ken); +</pre> + +<p>Lưu ý rằng thay vì truyền vào một hằng chuỗi hoặc giá trị số khi tạo những object mới, câu lệnh trên truyền vào những đối tượng <code>rand</code> và <code>ken</code> như là đối số cho <code>owner</code>. Sau đó nếu bạn muốn tìm tên của <code>owner</code> của car2, bạn có thể truy xuất như sau:</p> + +<pre class="brush: js">car2.owner.name +</pre> + +<p>Lưu ý rằng bạn có thể luôn luôn thêm một thuộc tính mới vào những object đã được tạo ra. Như ví dụ câu lệnh sau:</p> + +<pre class="brush: js">car1.color = 'black'; +</pre> + +<p>thêm vào thuộc tính <code>color</code> cho car1, và gán giá trị cho nó là "black". Tuy nhiên, việc này không ảnh hưởng lên những object khác. Để thêm thuộc tính cho tất cả object của cùng một kiểu, bạn phải thêm thuộc tính đó khi định nghĩa kiểu đối tượng <code>Car</code>.<br> + </p> + +<h3 id="Sử_dụng_Object.create">Sử dụng <code>Object.create</code></h3> + +<p>Những object có thể được tạo ra bằng phương thức {{jsxref("Object.create()")}}. Phương thức này có thể rất hữu ích, bởi vì nó cho phép bạn chọn prototype cho object bạn muốn tạo ra, mà không cần phải định nghĩa hàm dựng.</p> + +<pre class="brush: js">// Animal properties and method encapsulation +var Animal = { + type: 'Invertebrates', // Default value of properties + displayType: function() { // Method which will display type of Animal + console.log(this.type); + } +}; + +// Create new animal type called animal1 +var animal1 = Object.create(Animal); +animal1.displayType(); // Output:Invertebrates + +// Create new animal type called Fishes +var fish = Object.create(Animal); +fish.type = 'Fishes'; +fish.displayType(); // Output:Fishes</pre> + +<h2 id="Sự_Kế_Thừa">Sự Kế Thừa</h2> + +<p>Tất cả object trong JavaScript kế thừa từ ít nhất một object khác. Object mà được kế thừa từ nó thì được xem như là prototype, và những thuộc tính được kế thừa có thể được tìm thấy trong đối tượng <code>prototype</code> của hàm dựng. Xem thêm <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a></p> + +<h2 id="Đánh_chỉ_mục_thuộc_tính_object">Đánh chỉ mục thuộc tính object</h2> + +<p>Bạn có thể tham chiếu tới một object hoặc là bằng tên thuộc tính hoặc là bằng chỉ mục. Nếu bạn định nghĩa thuộc tính bằng tên, thì sau đó bạn phải dùng tên để truy xuất thuộc tính đó, còn nếu bạn định nghĩa thuộc tính bằng chỉ mục (một số), bạn phải dùng chỉ mục để truy xuất.</p> + +<p>Giới hạn này áp dụng khi bạn tạo một object và thuộc tính của nó với hàm dựng (như chúng ta đã làm với kiểu <code>Car</code>) và khi bạn định nghĩa những thuộc tính riêng lẻ một cách tường minh (ví dụ như , <code>myCar.color = "red"</code>). Nếu bạn định nghĩa thuộc tính với một chỉ mục, chẳng hạn như <code>myCar[5] = "25 mpg"</code>, thì bạn phải tham chiếu đến thuộc tính đó với chỉ mục <code>myCar[5]</code>.</p> + +<p>Ngoại trừ nếu đó là object giống mảng (array-like), ví dụ như những object tạo ra từ HTML như <code>forms</code> object. Bạn có thể tham chiếu đến những object đó bằng cách hoặc là dùng số (dựa vào thứ tự nó xuất hiện trong document) hoặc là tên (nếu được định nghĩa). Ví dụ, nếu thẻ <code><FORM></code> thứ hai trong document có thuộc tính <code>NAME</code> là "myForm", bạn có thể tham chiếu đến form bằng cách <code>document.forms[1]</code> hoặc <code>document.forms["myForm"]</code> hoặc <code>document.forms.myForm</code>.</p> + +<h2 id="Định_nghĩa_những_thuộc_tính_cho_kiểu_dữ_liệu_object">Định nghĩa những thuộc tính cho kiểu dữ liệu object</h2> + +<p>Bạn có thể thêm một thuộc tính cho một object đã định nghĩa trước đó bằng cách sử dụng thuộc tính <code>prototype</code>. Điều này định nghĩa một thuộc tính mà sẽ được chia sẻ bởi tất các các thuộc tính của cùng kiểu dữ liệu đó, không riêng cho một thực thể nào của kiểu đó. Đoạn mã sau sẽ thêm thuộc tính <code>color</code> cho tất cả các object của kiểu <code>Car</code>, và rồi gán giá trị cho thuộc tính <code>color</code> của object <code>car1</code>.</p> + +<pre class="brush: js">Car.prototype.color = null; +car1.color = 'black'; +</pre> + +<p>Xem thêm <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype" title="en-US/docs/JavaScript/Reference/Global Objects/Function/prototype"><code>prototype</code> property</a> của object <code>Function</code> trong <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a>.</p> + +<h2 id="Định_nghĩa_phương_thức">Định nghĩa phương thức</h2> + +<p>Một phương thức là một hàm liên kết với một object, hoặc, có thể nói phương thức là một thuộc tính của object có giá trị là một hàm. Phương thức được định nghĩa giống như cách định nghĩa hàm, ngoài trừ việc chúng phải được gán như là thuộc tính của một object. Xem thêm <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>. Ví dụ:</p> + +<pre class="brush: js">objectName.methodname = functionName; + +var myObj = { + myMethod: function(params) { + // ...do something + } + + // OR THIS WORKS TOO + + myOtherMethod(params) { + // ...do something else + } +}; +</pre> + +<p><code>objectName</code> là một object đã được tạo trước đó, <code>methodname</code> là tên mà bạn đang gán cho phương thức, và <code>functionName</code> là tên của hàm.</p> + +<p>Sau đó bạn có thể gọi hàm trong ngữ cảnh của object như sau:</p> + +<pre class="brush: js">object.methodname(params); +</pre> + +<p>Bạn có thể định nghĩa phương thức của một kiểu object bằng cách thêm định nghĩa phương thức vào trong hàm dựng. Bạn có thể định nghĩa một hàm mà sẽ định dạng và hiển thị những thuộc tính của những đối tượng kiểu <code>Car</code> đã được định nghĩa trước, ví dụ:</p> + +<pre class="brush: js">function displayCar() { + var result = 'A Beautiful ' + this.year + ' ' + this.make + + ' ' + this.model; + pretty_print(result); +} +</pre> + +<p>trong đó <code>pretty_print</code> được giả định là một hàm đã được định nghĩa trước để hiển thị đường kẻ ngang và chuỗi kết quả. Lưu ý tham chiếu <code>this</code> đang trỏ đến đối tượng mà phương thức đang gắn trên đó.</p> + +<p>Bạn có thể tạo hàm này thành phương thức của lớp <code>Car</code> bằng câu lệnh sau:</p> + +<pre class="brush: js">this.displayCar = displayCar; +</pre> + +<p>khi định nghĩa kiểu object <code>Car</code>. Cài đặt đầy đủ của <code>Car</code> bây giờ sẽ là:</p> + +<pre class="brush: js">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; + this.displayCar = displayCar; +} +</pre> + +<p>Rồi sau đó bạn có thể gọi phương thức <code>displayCar</code> trên mỗi đối tượng như sau:</p> + +<pre class="brush: js">car1.displayCar(); +car2.displayCar(); +</pre> + +<h2 id="Sử_dụng_this_để_tham_chiếu_đối_tượng">Sử dụng <code>this</code> để tham chiếu đối tượng</h2> + +<p>JavaScript có từ khóa đặc biệt, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, mà bạn có thể sử dụng bên trong phương thức để tham chiếu đến object hiện tại. Ví dụ, giả sử bạn có một hàm tên là <code>validate</code> để kiểm tra giá trị của thuộc tính của một object là giá trị cao hay thấp:</p> + +<pre class="brush: js">function validate(obj, lowval, hival) { + if ((obj.value < lowval) || (obj.value > hival)) { + alert('Invalid Value!'); + } +} +</pre> + +<p>Sau đó, bên trong hàm handler của event <code>onchange</code> của mỗi phần tử của form bạn có thể gọi hàm <code>validate</code> như ví dụ sau:</p> + +<pre class="brush: html"><input type="text" name="age" size="3" + onChange="validate(this, 18, 99)"> +</pre> + +<p>Nói chúng, <code>this</code> trỏ đến object đang gọi bên trong hàm.</p> + +<p>Khi kết hợp với thuộc tính <code>form</code>, <code>this</code> có thể tham chiếu đến form cha của object hiện tại. Trong ví dụ sau, form <code>myForm</code> chứa đối tượng <code>Text</code> và một nút. Khi user nhấp lên cái nút, giá trị của đối tượng <code>Text</code> được gán bằng tên của form. Hàm thực thi của sự kiện <code>onclick</code> của cái nút sử dụng <code>this.form</code> để tham chiếu đến form cha, <code>myForm</code>.</p> + +<pre class="brush: html"><form name="myForm"> +<p><label>Form name:<input type="text" name="text1" value="Beluga"></label> +<p><input name="button1" type="button" value="Show Form Name" + onclick="this.form.text1.value = this.form.name"> +</p> +</form></pre> + +<h2 id="Định_nghĩa_getters_và_setters">Định nghĩa getters và setters</h2> + +<p>Một <a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a> là một phương thức mà nhận giá trị của một thuộc tính cụ thể. Một <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a> là một phương thức thiết lập giá trị cho một thuộc tính cụ thể. Bạn có thể định nghĩa getters và setters cho bất kỳ object nào có thể là do runtime tạo sẵn hoặc do người dùng định nghĩa. Chúng ta dùng cú pháp của object literal để tạo getter và setter.</p> + +<p>Đoạn mã sau minh họa cách định nghĩa và thao tác trên getter và setter.</p> + +<pre class="brush: js">var o = { + a: 7, + get b() { + return this.a + 1; + }, + set c(x) { + this.a = x / 2; + } +}; + +console.log(o.a); // 7 +console.log(o.b); // 8 +o.c = 50; +console.log(o.a); // 25 +</pre> + +<p>Những thuộc tính của object <code>o</code> là:</p> + +<ul> + <li><code>o.a</code> — một số</li> + <li><code>o.b</code> — một getter trả về kết quả của <code>o.a</code> cộng 1</li> + <li><code>o.c</code> — một setter thiết lập giá trị cho <code>o.a</code> với giá trị là một nửa giá trị của đối số được truyền vào</li> +</ul> + +<p>Lưu ý ta dùng hàm để định nghĩa getter và setter, nhưng chúng ta truy xuất nó như một thuộc tính. Để định nghĩa một getter hoặc setter ta dùng cú pháp "[gs]et <em>property</em>()", Hoặc chúng ta một cách khác để định nghĩa getter hoặc setter là dùng <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty" title="en-US/docs/Core JavaScript 1.5 Reference/Global +Objects/Object/defineProperty">Object.defineProperty</a></code> (hoặc dùng cách cũ với <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineGetter" title="en-US/docs/Core JavaScript 1.5 Reference/Global +Objects/Object/defineGetter">Object.prototype.__defineGetter__</a></code>).</p> + +<p>Đoạn mã sau minh họa cách dùng getter và setter mở rộng prototype của {{jsxref("Date")}} để thêm thuộc tính <code>year</code> cho tất cả thực thể được tạo ra từ lớp <code>Date</code>. Và dùng phương thức <code>getFullYear</code> and <code>setFullYear</code> để hỗ trợ getter và setter <code>year</code>.</p> + +<p>Những câu lệnh sau định nghĩa getter và setter cho thuộc tính <code>year</code>:<br> + </p> + +<pre class="brush: js">var d = Date.prototype; +Object.defineProperty(d, 'year', { + get: function() { return this.getFullYear(); }, + set: function(y) { this.setFullYear(y); } +}); +</pre> + +<p>Những câu lệnh sau sử dụng getter và setter trong đối tượng <code>Date</code>:<br> + </p> + +<pre class="brush: js">var now = new Date(); +console.log(now.year); // 2000 +now.year = 2001; // 987617605170 +console.log(now); +// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001 +</pre> + +<p>Điều cần ghi nhớ là, getter vad setter có thể:</p> + +<ul> + <li>hoặc được định nghĩa bằng cách sứ dụng <a href="#Object_initializers">bộ khởi tạo object</a></li> + <li>hoặc được thêm vào sau đó cho bất kỳ object nào tại bất kỳ thời điểm nào bằng cách sử dụng phương thức tạo getter & setter (Object.defineProperty).</li> +</ul> + +<p>Khi tạo getters và settes sử dụng <a href="#Object_initializers">bộ khởi tạo object</a> điều bạn cần làm là đặt từ khóa <code>get</code> trước tên phương thức getter và từ khóa <code>set</code> trước phương thức setter. Tất nhiên là phương thức getter không cần bất kỳ tham số nào, còn phương thức setter cần đúng một tham số. Như ví dụ sau:</p> + +<pre class="brush: js">var o = { + a: 7, + get b() { return this.a + 1; }, + set c(x) { this.a = x / 2; } +}; +</pre> + +<p>Getters and setters có thể được thêm vào một object bất kỳ khi nào sau khi được tạo bằng cách dùng phương thức <code>Object.defineProperties</code>. Tham số đầu tiên của phương thức này là object mà bạn muốn định nghĩa getter và setter. Tham số thứ hai là một object mà tên của thuộc tính là tên của getter và setter, giá trị của thuộc tính là object định nghĩa hàm getter và setter. Sau đây là ví dụ minh họa cách định nghĩa getter và setter</p> + +<pre class="brush: js">var o = { a: 0 }; + +Object.defineProperties(o, { + 'b': { get: function() { return this.a + 1; } }, + 'c': { set: function(x) { this.a = x / 2; } } +}); + +o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property +console.log(o.b); // Runs the getter, which yields a + 1 or 6 +</pre> + +<p>Việc lựa chọn cách nào để định nghĩa getter và setter tùy thuộc vào phong cách lập trình và công việc cụ thể. Nếu bạn luôn dùng bộ khởi tạo object khi định nghĩa một prototype thì bạn nên chọn cách thứ nhất. Cách này đơn giản và tự nhiên. Tuy nhiên, nếu bạn cần thêm getters và setters sau đó — bởi vì bạn không viết prototype hoặc object cụ thể — bạn phải sử dụng cách thứ hai. Cách thứ hai thể hiện tính chất "động" tự nhiên của JavaScript — nhưng nó làm cho code khó đọc và khó hiểu.</p> + +<h2 id="Việc_xóa_bỏ_thuộc_tính">Việc xóa bỏ thuộc tính</h2> + +<p>Bạn có thể xóa bỏ một thuộc tính không kế thừa bằng toán tử <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code>. Câu lệnh sau chỉ bạn cách để xóa bỏ một thuộc tính.</p> + +<pre class="brush: js">// Creates a new object, myobj, with two properties, a and b. +var myobj = new Object; +myobj.a = 5; +myobj.b = 12; + +// Removes the a property, leaving myobj with only the b property. +delete myobj.a; +console.log ('a' in myobj); // yields "false" +</pre> + +<p>Bạn cũng có thể dùng <code>delete</code> để xóa bỏ biến toàn cục nếu bạn không dùng từ khóa <code>var</code> khi định nghĩa biến.</p> + +<pre class="brush: js">g = 17; +delete g; +</pre> + +<h2 id="So_sánh_objects">So sánh objects</h2> + +<p>Trong JavaScript những object là kiểu tham chiếu. Hai đối tượng tách biệt không bao giờ bằng nhau, thậm chí nếu chúng có cùng những thuộc tính. Chỉ khi nó so sánh với chính nó thì kết quả mới là true.</p> + +<pre class="brush: js">// Two variables, two distinct objects with the same properties +var fruit = {name: 'apple'}; +var fruitbear = {name: 'apple'}; + +fruit == fruitbear; // return false +fruit === fruitbear; // return false</pre> + +<pre class="brush: js">// Two variables, a single object +var fruit = {name: 'apple'}; +var fruitbear = fruit; // assign fruit object reference to fruitbear + +// here fruit and fruitbear are pointing to same object +fruit == fruitbear; // return true +fruit === fruitbear; // return true +</pre> + +<pre class="brush: js">fruit.name = 'grape'; +console.log(fruitbear); // yields { name: "grape" } instead of { name: "apple" } +</pre> + +<p>Chi tiết về toán tử so sánh, xem thêm tại <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Comparison operators</a>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Để hiểu sâu hơn về chủ đề này, bạn có thể đọc thêm <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">details of javaScript's objects model</a>.</li> + <li>Để học về ECMAScript 2015 classes (cách mới để định nghĩa object) đọc thêm chương <a href="/en-US/docs/Web/JavaScript/Reference/Classes">JavaScript classes</a>.</li> +</ul> + +<p>{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}</p> diff --git a/files/vi/web/javascript/index.html b/files/vi/web/javascript/index.html new file mode 100644 index 0000000000..bc5593df24 --- /dev/null +++ b/files/vi/web/javascript/index.html @@ -0,0 +1,110 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - Học javascript + - JavaScript + - Landing +translation_of: Web/JavaScript +--- +<div>{{JsSidebar()}}</div> + +<div class="summary"> +<p><strong>JavaScript</strong><sup>®</sup> (viết tắt là <strong>JS</strong>) là một ngôn ngữ lập trình gọn nhẹ, được thông dịch hoặc biên dịch trong thời gian với đặc tính <a href="https://en.wikipedia.org/wiki/First-class_functions" style="font-weight: bold; background-color: rgb(244, 247, 248);" title="https://en.wikipedia.org/wiki/First-class_functions">hàm đối tượng</a> (<a href="https://en.wikipedia.org/wiki/First-class_functions" title="https://en.wikipedia.org/wiki/First-class_functions">first-class functions</a>). JavaScript được biết tới như một ngôn ngữ lập trình dành cho các trang Web - tức là được thực thi trên trình duyệt, rất nhiều <a class="external" href="http://en.wikipedia.org/wiki/JavaScript#Uses_outside_web_pages">môi trường phi trình duyệt khác</a> cũng sử dụng ngôn ngữ này, như là <a class="external" href="http://nodejs.org/">Node.js</a> hay <a href="http://couchdb.apache.org">Apache CouchDB</a> và <a href="https://www.adobe.com/devnet/acrobat/javascript.html">Adobe Acrobat</a>. Ngôn ngữ này có đặc điểm là một ngôn ngữ lập trình <a class="mw-redirect" href="https://en.wikipedia.org/wiki/Prototype-based" style="text-decoration: underline; font-weight: bold; background-color: rgb(244, 247, 248);" title="Prototype-based">dựa trên nguyên mẫu</a> (<a class="mw-redirect" href="https://en.wikipedia.org/wiki/Prototype-based" title="Prototype-based">prototype-based</a>), đa hình (multi-paradigm), đơn luồng nên khá linh động và hỗ trợ được cả các phong cách lập trình hướng đối tượng, lập trình mệnh lệnh và lập trình hàm. Bạn có thể đọc thêm về JavaScript ở <a href="/en-US/docs/Web/JavaScript/About_JavaScript">đây</a>.</p> +</div> + +<p><a href="/en-US/docs/JavaScript/Language_Resources">ECMAScript</a> là tiêu chuẩn chung cho JavaScript và tính tới thời điểm năm 2012 thì tất cả các trình duyện hiện đại đều đã hỗ trợ đầy đủ các tiêu chuẩn ECMAScript 5.1, còn một số trình duyệt cũ thì cũng hỗ trợ ít nhất ở phiên bản ECMAScript 3. Vào ngày 17 tháng 06 năm 2015, phiên bản chính thức thứ 6 của ECMAScript đã được phát hành với tên gọi chính thức là ECMAScript 2015, nhưng nó cũng hay được gọi với tên là ECMAScript 6 hoặc ES6.</p> + +<p>Phần này dành riêng cho việc hướng dẫn về ngôn ngữ JavaScript chứ không mô tả cụ thể cho từng môi trường như Web hay cho các môi trường máy chủ. Về các API dành riêng cho Web, bạn có thể xem ở phần <a href="/en-US/docs/Web/API">Web APIs</a> và <a href="/en-US/docs/Glossary/DOM">DOM</a>.</p> + +<p>Lưu ý rằng JavaScript khác với <a href="http://en.wikipedia.org/wiki/Java_(programming_language)">ngôn ngữ lập trình Java</a> nên đừng nhầm lẫn với Java. Cả "Java" và "JavaScript" là các nhãn hiệu được đăng kí bởi Oracle tại Mĩ và các quốc gia khác. Tuy nhiên, hai ngôn ngữ lập trình này có cú pháp, ngữ nghĩa và cách dùng rất khác nhau.</p> + +<h3 id="Bạn_đang_muốn_trờ_thành_một_người_phát_triển_website_front-end_web_developer">Bạn đang muốn trờ thành một người phát triển website (front-end web developer)?</h3> + +<p>Chúng tôi đã tổng hợp một khóa học bao gồm tất cả thông tin cần thiết mà bạn cần để hướng tới mục tiêu của mình.</p> + +<p><a href="https://wiki.developer.mozilla.org/docs/Learn/Front-end_web_developer">Cùng bắt đầu</a></p> + +<div class="column-container"> +<div class="column-half"> +<h2 id="Creating" name="Creating">Hướng dẫn</h2> + +<p>Học cách lập trình bằng JavaScript.</p> + +<h3 id="Mở_đầu">Mở đầu</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">Dẫn nhập về JavaScript</a></dt> + <dd>Bạn chưa biết về JavaScript? Tốt, phần này sẽ dẫn bạn đi một vòng qua ngôn ngữ này.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">Tổng quan về các công nghệ JavaScript</a></dt> + <dd>Giới thiệu về hiện trạng của JavaScript ở các trình duyệt Web.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Nhập môn hướng đối tượng với JavaScript</a></dt> + <dd>Giới thiệu các khái niệm về lập trình hướng đối tượng trong JavaScript.</dd> +</dl> + +<h3 id="Căn_bản">Căn bản</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript">Giới thiệu lại về JavaScript</a></dt> + <dd>Một bản tổng quan dành cho người đã <em>biết</em> về JavaScript.</dd> +</dl> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">Cấu trúc dữ liệu trong </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures" style="font-weight: bold;">JavaScript</a></dt> + <dd>Tổng quan về các cấu trúc dữ liệu trong JavaScript.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_when_to_use_them">Các phép so sánh bằng và cách sử dụng</a></dt> + <dd>JavaScript cung cấp 3 kiểu so sánh giá trị khác nhau là: so sánh bằng chặt chẽ với <code>===</code> và so sánh bằng lỏng lẻo với <code>==</code>.</dd> +</dl> + +<h3 id="Nâng_cao">Nâng cao</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">Kế thừa và chuỗi nguyên mẫu</a></dt> + <dd>Giải thích về sự hiểu lầm và đánh giá không chuẩn về kế thừa dựa trên nguyên mẫu (prototype-based inheritance)</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Chế độ nghiêm ngặt (strict mode)</a></dt> + <dd>Một biến thể bị giới hạn của JavaScript.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">Các kiểu dữ liệu mảng của JavaScript</a></dt> + <dd>Các mảng của JavaScript cung cấp cơ chế truy cậ dữ liệu nhị phân gốc (raw binary data).</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">Quản lý bộ nhớ</a></dt> + <dd>Về vòng đời bộ nhớ và bộ dọn rác trong JavaScript.</dd> +</dl> +</div> + +<div class="column-half"> +<h2 id="Tài_liệu">Tài liệu</h2> + +<p>Xem bộ tài liệu <a href="/en-US/docs/Web/JavaScript/Reference">tham chiếu JS</a> đầy đủ.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Các đối tượng tiêu chuẩn</a></dt> + <dd>Hướng dẫn về một số đối tượng chuẩn được xây dựng sẵn như {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}} ...</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Các biểu thức và toán tử</a></dt> + <dd>Học thêm về các xử lý của các toán tử trong JavaScript như {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}} ...</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements">Các câu lệnh và khai báo</a></dt> + <dd>Học về các câu lệnh và cách khai báo cũng như các từ khóa trong JavaScirpt như {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}} ...</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Hàm</a></dt> + <dd>Học cách làm việc với các hàm trong JS để phát triển các ứng dụng của bạn.</dd> +</dl> + +<h2 id="Công_cụ_tài_nguyên">Công cụ & tài nguyên</h2> + +<p>Các công cụ hữu dụng để viết mã và gỡ lỗi với JavaScript.</p> + +<dl> + <dt><a href="/en-US/docs/Tools">Các công cụ phát triển của Firefox</a></dt> + <dd><a href="/en-US/docs/Tools/Scratchpad">Scratchpad</a>, <a href="/en-US/docs/Tools/Web_Console">Web Console</a>, <a href="/en-US/docs/Tools/Profiler">JavaScript Profiler</a>, <a href="/en-US/docs/Tools/Debugger">Debugger</a>...</dd> + <dt><a class="external" href="http://www.getfirebug.com/">Firebug</a></dt> + <dd>Chỉnh sửa, gỡ lỗi, và theo dõi các mã CSS, HTML, và JavaScript trực tiếp với bất kì trang web nào.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Shells">JavaScript Shells</a></dt> + <dd>A JavaScript shell cho phép bạn kiểm tra nhanh chóng các đoạn mã JavaScript.</dd> + <dt><a href="https://togetherjs.com/">TogetherJS</a></dt> + <dd> + <p class="hero-header-text large">Hợp tác để giải quyết các vấn đề dễ hơn.</p> + </dd> + <dt><a href="http://stackoverflow.com/questions/tagged/javascript">Stack Overflow</a></dt> + <dd>Các câu hỏi được đánh thẻ "JavaScript" trên hệ thống giải đáp Stack Overflow.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">Các phiên bản JavaScript và các chú thích phát hành</a></dt> + <dd>Xem thêm về lịch sử của JavaScript cùng với các chú thích của nó.</dd> +</dl> +</div> +</div> diff --git a/files/vi/web/javascript/memory_management/index.html b/files/vi/web/javascript/memory_management/index.html new file mode 100644 index 0000000000..3c3da3771d --- /dev/null +++ b/files/vi/web/javascript/memory_management/index.html @@ -0,0 +1,183 @@ +--- +title: Memory Management +slug: Web/JavaScript/Memory_Management +translation_of: Web/JavaScript/Memory_Management +--- +<div>{{JsSidebar("Advanced")}}</div> + +<h2 id="Giới_thiệu">Giới thiệu</h2> + +<p>Ngôn ngữ bậc thấp như C, có các nguyên hàm quản lý bộ nhớ theo cách thủ công như là<a href="https://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html">malloc()</a> và <a href="https://en.wikipedia.org/wiki/C_dynamic_memory_allocation#Overview_of_functions">free()</a>. Trái lại, JavaScript tự động cấp phát bộ nhớ khi object được khởi tạo và giải phóng khi object đó không còn được dùng nữa (<em>bộ thu thập rác</em>). Sự tự động này có thể gây ra bối rối: khiến cho nhà phát triển tưởng rằng họ không cần lo về vấn đề quản lý bộ nhớ.</p> + +<h2 id="Vòng_đời_bộ_nhớ">Vòng đời bộ nhớ</h2> + +<p>Với mọi ngôn ngữ lập trình, vòng đời bộ nhớ khá giống nhau:</p> + +<ol> + <li>Cấp phát bộ nhớ mà bạn cần</li> + <li>Sử dụng bộ nhớ đã cấp phát (đọc, ghi)</li> + <li>Giải phóng bộ nhớ đã cấp phát khi chúng không còn được sử dụng</li> +</ol> + +<p>Phần thứ hai tường minh trên mọi ngôn ngữ. Phần đầu và cuối tường minh trên họ ngôn ngữ bậc thấp nhưng ngầm trên ngôn ngữ bậc cao như JavaScript.</p> + +<h3 id="Cấp_phát_trong_JavaScript">Cấp phát trong JavaScript</h3> + +<h4 id="Khởi_tạo_giá_trị">Khởi tạo giá trị</h4> + +<p>Để không khiến lập trình viên phải bận tâm với việc cấp phát, JavaScript thực hiện điều đó khi khởi tạo giá trị.</p> + +<pre class="brush: js">var n = 123; // cấp phát bộ nhớ cho một số +var s = 'azerty'; // cấp phát bộ nhớ cho một xâu ký tự + +var o = { + a: 1, + b: null +}; // cấp phát bộ nhớ cho object và giá trị bên trong + +// (giống như object) cấp phát bộ nhớ cho mảng +// và giá trị bên trong +var a = [1, null, 'abra']; + +function f(a) { + return a + 2; +} // cấp phát cho hàm (là object khả gọi) + +// biểu thức function cũng được cấp phát như object +someElement.addEventListener('click', function() { + someElement.style.backgroundColor = 'blue'; +}, false); +</pre> + +<h4 id="Cấp_phát_thông_qua_lời_gọi_hàm">Cấp phát thông qua lời gọi hàm</h4> + +<p>Kết quả của vài lời gọi hàm là việc cấp phát cho object.</p> + +<pre class="brush: js">var d = new Date(); // cấp phát cho Date object + +var e = document.createElement('div'); // cấp phát cho phần tử DOM</pre> + +<p>Một số phương thức cấp phát giá trị hoặc object mới:</p> + +<pre class="brush: js">var s = 'azerty'; +var s2 = s.substr(0, 3); // s2 is a new string +// Vì xâu ký tự là giá trị không thể biến đổi +// JavaScript có thể sẽ không cấp phát thêm bộ nhớ +// mà chỉ lưu trữ đoạn [0, 3]. + +var a = ['ouais ouais', 'nan nan']; +var a2 = ['generation', 'nan nan']; +var a3 = a.concat(a2); +// mảng mới với 4 phần tử +// là kết quả của phép nối các phần tử của a và a2 +</pre> + +<h3 id="Sử_dụng_giá_trị">Sử dụng giá trị</h3> + +<p>Sử dụng giá trị về cơ bản nghĩa là đọc và ghi trên bộ nhớ đã cấp phát. Việc này có thể được thực hiện thông qua đọc hoặc ghi giá trị của một biến hoặc một thuộc tính của object hay thậm chí là truyền tham số vào một hàm.</p> + +<h3 id="Giải_phóng_khi_bộ_nhớ_không_còn_cần_tới">Giải phóng khi bộ nhớ không còn cần tới</h3> + +<p>Hầu hết các vấn đề về quản lý bộ nhớ đều xảy ra ở bước này. Nhiệm vụ khó nhất lúc này là tìm "bộ nhớ đã cấp phát không còn cần tới nữa". Thường lúc này nhà phát triển sẽ phải xác định phần bộ nhớ nào trong chương trình không còn cần tới nữa và giải phóng chúng.</p> + +<p>Ngôn ngữ bậc cao nhúng phần mềm có tên là "bộ thu thập rác" có nhiệm vụ dò theo việc cấp phát và sử dụng bộ nhớ để tìm ra "bộ nhớ đã cấp phát không còn cần tới nữa", nó sẽ tự động giải phóng phần bộ nhớ đó. Công cuộc này chỉ gần đúng bởi vì vấn đề chung để biết được liệu phần bộ nhớ đó có cần tới hay không là <a class="external" href="http://en.wikipedia.org/wiki/Decidability_%28logic%29">không thể quyết định</a> (không thể giải quyết bằng thuật toán).</p> + +<h2 id="Bộ_thu_thập_rác">Bộ thu thập rác</h2> + +<p>Như đã nhấn mạnh ở trên, vấn đề chung để tự động tìm ra phần bộ nhớ "không còn cần tới nữa" là không thể quyết định được. Vì vậy, bộ thu thập rác sử dụng tập hạn chế để giải quyết vấn đề chung đó. Phần này sẽ giải thích khái niệm cần thiết để hiểu được các thuật toán thu thập rác và hạn chế của chúng.</p> + +<h3 id="Tham_chiếu">Tham chiếu</h3> + +<p>Thuật toán thu thập rác chủ yếu phụ thuộc vào khái niệm <em>tham chiếu</em>. Trong ngữ cảnh quản lý bộ nhớ, object này được gọi là tham chiếu tới object khác nếu cái trước truy xuất tới cái sau (cả ngầm lẫn tường minh). Chẳng hạn, một JavaScript object tham chiếu tới <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">prototype</a> (tham chiếu ngầm) và tới giá trị thuộc tính của nó (tham chiếu tường minh).</p> + +<p>Trong ngữ cảnh này, khái niệm "object" được hiểu rộng ra hơn với định nghĩa object của JavaScript và còn bao gồm phạm vi hàm (hoặc phạm vi lexical toàn cục).</p> + +<h3 id="Đếm_tham_chiếu">Đếm tham chiếu</h3> + +<p>Đây là thuật toán thu thập rác thô sơ nhất. Thuật toán rút gọn định nghĩa từ "một object không cần tới nữa" thành "một object không có tham chiếu nào tới nó". Một object được coi như là khả thu nếu không có tham chiếu nào trỏ tới nó.</p> + +<h4 id="Ví_dụ">Ví dụ</h4> + +<pre class="brush: js">var o = { + a: { + b: 2 + } +}; +// 2 object được khởi tạo. object này tham chiếu tới object kia như là thuộc tính của nó. +// The other is referenced by virtue of being assigned to the 'o' variable. +// Obviously, none can be garbage-collected + + +var o2 = o; // the 'o2' variable is the second thing that + // has a reference to the object +o = 1; // now, the object that was originally in 'o' has a unique reference + // embodied by the 'o2' variable + +var oa = o2.a; // reference to 'a' property of the object. + // This object now has 2 references: one as a property, + // the other as the 'oa' variable + +o2 = 'yo'; // The object that was originally in 'o' has now zero + // references to it. It can be garbage-collected. + // However its 'a' property is still referenced by + // the 'oa' variable, so it cannot be freed + +oa = null; // The 'a' property of the object originally in o + // has zero references to it. It can be garbage collected. +</pre> + +<h4 id="Hạn_chế_vòng">Hạn chế: vòng</h4> + +<p>Phát sinh hạn chế khi xét tới vòng. Trong ví dụ sau, hai object được khởi tạo và tham chiếu tới nhau, tạo ra vòng. Chúng sẽ không còn được dùng tới nữa sau lời gọi hàm, nên chúng sẽ trở thành vô dụng và khả thu. Tuy nhiên, thuật toán đếm tham chiếu vẫn xét là hai object tham chiếu lần lượt tới nhau, nên cả hai bất khả thu.</p> + +<pre class="brush: js">function f() { + var o = {}; + var o2 = {}; + o.a = o2; // o tham chiếu tới o2 + o2.a = o; // o2 tham chiếu tới o + + return 'azerty'; +} + +f(); +</pre> + +<h4 id="Ví_dụ_thực-tiễn">Ví dụ thực-tiễn</h4> + +<p>Internet Explorer 6 và 7 đều dùng thuật toán đếm tham chiếu cho DOM object. Vòng là lỗi thường gặp mà có thể gây ra rò rỉ bộ nhớ:</p> + +<pre class="brush: js">var div; +window.onload = function() { + div = document.getElementById('myDivElement'); + div.circularReference = div; + div.lotsOfData = new Array(10000).join('*'); +}; +</pre> + +<p>Trong ví dụ trên, phần tử DOM "myDivElement" có tham chiếu vòng tới chính nó trong thuộc tính "circularReference". Nếu thuộc tính đó không được loại bỏ hoặc gán giá trị null một cách tường minh, bộ thu thập rác (đếm tham chiếu) sẽ luôn có ít nhất một tham chiếu không bị thay đổi và sẽ giữ phần tử DOM trong bộ nhớ thậm chí khi nó đã bị loại bỏ khỏi cây DOM. Nếu phần tử DOM mang nhiều dữ liệu (thể hiện trong thuộc tính "lotsOfData"), bộ nhớ tiêu tốn bởi đống dữ liệu này sẽ không bao giờ được giải phóng.</p> + +<h3 id="Thuật_toán_Mark-and-sweep">Thuật toán Mark-and-sweep</h3> + +<p>Thuật toán này rút gọn định nghĩa từ "object không cần tới nữa" thành "object không thể tới được".</p> + +<p>Thuật toán này sử dụng tập các object gọi là <em>root</em> (Trong JavaScript, root là object toàn cục). Theo chu kỳ, bộ thu thập rác sẽ bắt đầu từ root, tìm tất cả object được tham chiếu tới từ root, rồi tới tất cả objects được tham chiếu từ các object trên, tương tự tới hết. Bắt đầu từ root, bộ thu thập rác sẽ tìm tất cả object <em>có thể tới được</em> và thu thập mọi object không thể tới được.</p> + +<p>Thuật toán này tốt hơn thuật toán trước bởi "object có không tham chiếu" dẫn tới object đó không thể tới được. Điều ngược lại không đúng như ví dụ về truy xuất vòng.</p> + +<p>Đến năm 2012, tất cả trình duyệt hiện đại đều hỗ trợ bộ thu thập rác mark-and-sweep. Mọi cải tiến trong bộ thu thập rác của JavaScript (generational/incremental/concurrent/parallel garbage collection) trong nhiều năm qua đều được áp dụng vào thuật toán này, nhưng không cải tiến thẳng vào thuật toán hay là rút gọn định nghĩa khi "object không cần tới nữa".</p> + +<h4 id="Vòng_không_còn_là_mối_lo">Vòng không còn là mối lo</h4> + +<p>Trong ví dụ đầu tiên, sau khi hàm gọi tới lệnh return, sẽ không còn object toàn cục nào tới được 2 object trong hàm. Vì thế, bộ thu thập rác sẽ xác định là chúng không thể tới được.</p> + +<h4 id="Hạn_chế_object_cần_phải_được_bất_khả_tới_một_cách_tường_minh">Hạn chế: object cần phải được bất khả tới một cách tường minh</h4> + +<p>Dù được đánh dấu là hạn chế, nhưng trên thực tế trường hợp này hiếm khi xảy ra nên không ai bận tâm tới bộ thu thập rác cả.</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a class="external" href="http://www.ibm.com/developerworks/web/library/wa-memleak/">IBM article on "Memory leak patterns in JavaScript" (2007)</a></li> + <li><a class="external" href="http://msdn.microsoft.com/en-us/magazine/ff728624.aspx">Kangax article on how to register event handler and avoid memory leaks (2010)</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Performance" title="https://developer.mozilla.org/en-US/docs/Mozilla/Performance">Performance</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/classes/constructor/index.html b/files/vi/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..dddb2555f3 --- /dev/null +++ b/files/vi/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,127 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Phương thức </span></font>constructor</code> là một phương thức đặc biệt dùng để khởi tạo 1 object và được tạo ở trong <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class</a></code>.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">constructor([<em>arguments</em>]) { ... }</pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Chỉ có duy nhất 1 phương thức đặc biệt tên là "constructor" ở trong class. Có nhiều hơn 1 phương thức <code>constructor</code> ở trong class thì sẽ gây ra lỗi{{jsxref("SyntaxError")}}.</p> + +<p>Một constructor có thể sử dụng từ khóa {{jsxref("Operators/super", "super")}} để gọi đến constructor của class cha.</p> + +<p>Nếu bạn không chỉ định 1 phương thức constructor thì constructor mặc định sẽ được sử dụng</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_phương_thức_constructor">Sử dụng phương thức <code>constructor</code> </h3> + +<p>Đoạn code này được lấy từ <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>).</p> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // Here, it calls the parent class' constructor with lengths + // provided for the Polygon's width and height + super(length, length); + // Note: In derived classes, super() must be called before you + // can use 'this'. Leaving this out will cause a reference error. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="Ví_dụ_khác">Ví dụ khác</h3> + +<p>Hãy xem đoạn code sau</p> + +<pre class="brush: js">class Polygon { + constructor() { + this.name = "Polygon"; + } +} + +class Square extends Polygon { + constructor() { + super(); + } +} + +class Rectangle {} + +Object.setPrototypeOf(Square.prototype, Rectangle.prototype); + +console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false +console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true + +let newInstance = new Square(); +console.log(newInstance.name); //Polygon</pre> + +<p>Ở đây prototype của class <strong>Square</strong> đã bị thay đổi nhưng constructor kế thừa từ class <strong>Polygon </strong>vẫn được gọi khi tạo ra 1 thực thể mới.</p> + +<h3 id="Default_constructors">Default constructors</h3> + +<p>Như đã nói ởi trước, nếu bạn không chỉ đỉnh 1 phương thức constructor thì default constructor sẽ được sử dụng. Với những class cơ bản thì default contructor sẽ là:</p> + +<pre class="brush: js">constructor() {} +</pre> + +<p>Với những class dẫn xuất, default constructor sẽ là:</p> + +<pre class="brush: js">constructor(...args) { + super(...args); +}</pre> + +<h2 id="Thông_số_kĩ_thuật">Thông số kĩ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.classes.constructor")}}</p> + +<h2 id="Bài_viết_liên_quan">Bài viết liên quan</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super()</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/classes/extends/index.html b/files/vi/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..a7a2438965 --- /dev/null +++ b/files/vi/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,108 @@ +--- +title: extends(Thừa kế) +slug: Web/JavaScript/Reference/Classes/extends +translation_of: Web/JavaScript/Reference/Classes/extends +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Từ khóa </span></font><strong>extends</strong></code> được sử dụng trong khai báo <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class</a> hoặc trong <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">class expressions</a> để tạo ra 1 class con là con của class khác</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">class ChildClass extends ParentClass { ... }</pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Từ khó <code>extends</code> có thể được sử dụng để tạo ra class con từ những class mà chúng ta tạo ra hoặc những class sẵn có</p> + +<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Thuộc tính </span></font>.prototype</code> của lớp được kế thừa phải trả về giá trị là {{jsxref("Object")}} hoặc {{jsxref("null")}}.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_extends">Sử dụng <code>extends</code></h3> + +<p>Ở ví dụ đầu tiên tạo ra 1 class <code>Square</code> từ class <code>Polygon</code>. Ví dụ này được lấy từ đây <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(source)</a>.</p> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // Ở đây, gọi 1 constructor từ class cha với tham số truyền vào là length + // cung cấp chiều rộng vào chiều cao của class Polygon + super(length, length); + // Chú ý: trong những class con, super() phải được gọi trước khi + // bạn có thể sử dụng từ khóa 'this'. Nếu không sẽ gây ra lỗi tham chiếu + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } +}</pre> + +<h3 id="Sử_dụng_extends_với_những_object_có_sẵn"><code><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="background-color: #333333;">Sử dụng </span></font>extends</code> với những object có sẵn</h3> + +<p>Trong ví dụ này chúng ta thừa kế từ object có sẵn là {{jsxref("Date")}} . Ví dụ này được lấy từ đây<a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(source)</a>.</p> + +<pre class="brush: js">class myDate extends Date { + constructor() { + super(); + } + + getFormattedDate() { + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear(); + } +}</pre> + +<h3 id="Thừa_kế_từ_null">Thừa kế từ <code>null</code></h3> + +<p>Thừa kế từ {{jsxref("null")}} cũng giống như class thông thường, ngoại trừ rằng các prototype của object sẽ không được thừa kế từ {{jsxref("Object.prototype")}}.</p> + +<pre class="brush: js">class nullExtends extends null { + constructor() {} +} + +Object.getPrototypeOf(nullExtends); // Function.prototype +Object.getPrototypeOf(nullExtends.prototype) // null + +new nullExtends(); //ReferenceError: this is not defined +</pre> + +<h2 id="Thông_số_kĩ_thuật">Thông số kĩ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + + + +<p>{{Compat("javascript.classes.extends")}}</p> + +<h2 id="Bài_viết_liên_quan">Bài viết liên quan</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></li> + <li><a href="https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420">Anurag Majumdar - Super & Extends in JavaScript</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/classes/index.html b/files/vi/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..02a693e6fc --- /dev/null +++ b/files/vi/web/javascript/reference/classes/index.html @@ -0,0 +1,410 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Class trong ES6 + - JavaScript + - biểu thức class + - class declarations + - class expressions + - class trong javasript + - khai báo class + - thừa kế +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<div>Lớp (class) trong JavaScript được giới thiệu trong ECMAScript 2015 chủ yếu là cú pháp cải tiến (syntactical sugar) dựa trên nền tảng thừa kế nguyên mẫu (prototypal inheritance) sẵn có trong JavaScript. Cú pháp class <em>không</em> giới thiệu mô hình thừa kế hướng đối tượng mới cho JavaScript.</div> + +<h2 id="Định_nghĩa_class">Định nghĩa class</h2> + +<p>Thực tế các class giống như các "function đặc biệt", và cũng giống như bạn có thể định nghĩa hàm biểu thức (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function">function expressions</a>) và khai báo hàm (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a>), cú pháp class có hai thành phần: <strong>biểu thức class</strong> (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/class">class expressions</a>) và <strong>khai báo class</strong> (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class">class declarations</a>).</p> + +<h3 id="Khai_báo_class">Khai báo class</h3> + +<p>Một cách để định nghĩa class là sử dụng khai báo lớp <strong>class declaration</strong>. Để khai báo một class, bạn sử dụng từ khóa <code>class</code> với tên của class đằng sau (ví dụ "Rectangle" như dưới đây).</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<h4 id="Hoisting_(sự_kéo_lên)">Hoisting (sự kéo lên)</h4> + +<p>Một sự khác biệt quan trọng giữa <strong>khai báo hàm</strong> và <strong>khai báo class</strong> mà các bạn cần chú ý đó là khai báo hàm được kéo lên đầu ({{Glossary("Hoisting", "hoisted")}}), và khai báo class thì không. Bạn cần khai báo class của bạn trước tiên sau đó mới có thể gọi và sử dụng nó, ngược lại nếu viết code giống như phía dưới đây thì sẽ xảy ra lỗi {{jsxref("ReferenceError")}}:</p> + +<pre class="brush: js example-bad">var p = new Rectangle(); // ReferenceError + +class Rectangle {} +</pre> + +<h3 id="Biểu_thức_class">Biểu thức class</h3> + +<p>Một biểu thức class là một cách khác để khai báo một class. Biểu thức class có thể có tên hoặc không tên. Biểu thức class nếu có tên, thì tên đó chỉ được nhìn thấy bên trong thân class. (Tuy nhiên từ bên ngoài nó có thể được lấy ra thông qua thuộc tính {{jsxref("Function.name", "name")}} của class (không phải instance)).</p> + +<pre class="brush: js">// biểu thức class không tên +var Rectangle = class { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; + +console.log(Rectangle.name); +// output: "Rectangle" (tên của biến được gán) + +// biểu thức class có tên +var Rectangle = class Rectangle2 { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; + +console.log(Rectangle.name); +// output: "Rectangle2" (tên phía sau từ khóa class) +</pre> + +<div class="blockIndicator note"> +<p><strong>Lưu ý</strong>: Các biểu thức class cũng theo quy luật hoisting như của {{anch("Class declarations")}} đề cập ở trên.</p> +</div> + +<h2 id="Thân_class_và_định_nghĩa_phương_thức">Thân class và định nghĩa phương thức</h2> + +<p>Phần thân của một class là phần nằm trong dấu ngoặc nhọn <code>{}</code>. Tại đó bạn có thể định nghĩa các thành phần của class như phương thức (method) hoặc hàm khởi tạo (constructor).</p> + +<h3 id="Strict_mode">Strict mode</h3> + +<p>Các phần tử khai báo trong <em>class declarations</em> và <em>class expressions đã </em>được thực hiện ở chế độ<em> </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> như constructor, static tương tự đối với prototype methods, setter, getter functions. (Nếu bạn chưa hiểu chế độ strict mode thì hãy tìm hiểu thêm <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">tại đây</a>).</p> + +<h3 id="Constructor_(hàm_khởi_tạo)">Constructor (hàm khởi tạo)</h3> + +<p>Hàm khởi tạo (constructor) là một hàm đặc biệt, nhiệm vụ của nó là khởi tạo một đối tượng cho một class. Trong một class chỉ có thể tồn tại duy nhất một hàm khởi tạo, nghĩa là bạn chỉ có thể khai báo duy nhất một hàm với tên "constructor". Nếu bạn cố gắng làm ngược lại (khai báo nhiều hơn một hàm constructor) thì sẽ xuất hiện lỗi {{jsxref("SyntaxError")}}.</p> + +<p>Một constructor có thể sử dụng từ khóa super để gọi tới hàm constructor của class cha.</p> + +<h3 id="Phương_thức_Prototype">Phương thức Prototype</h3> + +<p>Xem thêm <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">định nghĩa hàm</a>.</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } + + get area() { + return this.calcArea(); + } + + calcArea() { + return this.height * this.width; + } +} + +const square = new Rectangle(10, 10); + +console.log(square.area);</pre> + +<h3 id="Phương_thức_Static_(phương_thức_tĩnh)">Phương thức Static (phương thức tĩnh)</h3> + +<p>Từ khóa <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> định nghĩa một hàm static (hàm tĩnh) trong một class. Nếu muốn gọi hàm static này thì bạn không cần gọi chúng thông qua các <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instantiating</a> của class đó và bạn cũng không thể gọi chúng thông qua cách khởi tạo class. Hàm static thường được sử dụng vào mục đích tạo ra một hàm tiện ích (có thể gọi là hàm dùng chung) cho cả một ứng dụng.</p> + +<pre class="brush: js">class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + + static distance(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + + return Math.hypot(dx, dy); + } +} + +const p1 = new Point(5, 5); +const p2 = new Point(10, 10); + +console.log(Point.distance(p1, p2));</pre> + +<h3 id="Boxing_với_phương_thức_prototype_và_static">Boxing với phương thức prototype và static</h3> + +<p>Khi hai hàm static và prototype được gọi trực tiếp (không cần tạo đối tượng có giá trị "this") thì bây giờ bên trong hàm gọi, giá trị this sẽ là <strong><code>undefine.</code></strong> Autoboxing sẽ không xảy ra. Hành vi này sẽ giống nhau ngay cả khi chúng ta viết code ở strict mode bởi vì tất cả các hàm, phương thức, hàm khởi tạo, setter và getter đều thực thi mặc định ở strict mode. Chính vì vậy nếu chúng ta không chỉ định giá trị "this" thì giá trị của "this" sẽ là <strong><code>undefined.</code></strong></p> + +<pre class="brush: js">class Animal { + speak() { + return this; + } + static eat() { + return this; + } +} + +let obj = new Animal(); +obj.speak(); // Animal {} +let speak = obj.speak; +speak(); // undefined + +Animal.eat() // class Animal +let eat = Animal.eat; +eat(); // undefined +</pre> + +<p>Nếu chúng ta chỉnh sửa code như trên bằng cách sửa dụng prototype thì autoboxing sẽ tự động hiểu rằng giá trị this bấy giờ là dựa trên cái hàm được gọi. Tham khảo code bên dưới.</p> + +<pre class="brush: js">function Animal() { } + +Animal.prototype.speak = function() { + return this; +} + +Animal.eat = function() { + return this; +} + +let obj = new Animal(); +let speak = obj.speak; +speak(); // global object + +let eat = Animal.eat; +eat(); // global object +</pre> + +<h2 id="Tạo_lớp_con_với_extends">Tạo lớp con với extends</h2> + +<p>Từ khóa <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a> </code>được sử dụng trong <em>class declarations</em> hoặc <em>class expressions </em>để tạo ra một class con kế thừa từ một class sẵn có (class cha).</p> + +<pre class="brush: js">class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Dog extends Animal { + speak() { + console.log(this.name + ' barks.'); + } +} + +var d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>Nếu có một constructor trong lớp con (sub-class), nó cần gọi hàm super() trước khi có thể sử dụng "this".</p> + +<p>Một cách khác cũng có thể gọi và mở rộng hàm có sẵn là dùng prototype:</p> + +<pre class="brush: js">function Animal (name) { + this.name = name; +} + +Animal.prototype.speak = function () { + console.log(this.name + ' makes a noise.'); +} + +class Dog extends Animal { + speak() { + console.log(this.name + ' barks.'); + } +} + +var d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>Cần lưu ý rằng các class không thể extend một object bình thường trong javascript (regular object). Do đó nếu bạn muốn kế thừa một hàm từ object bình thường này, bạn cần thay thế và sử dụng {{jsxref("Object.setPrototypeOf()")}}:</p> + +<pre class="brush: js">var Animal = { // regular object + speak() { + console.log(this.name + ' makes a noise.'); + } +}; + +class Dog { // + constructor(name) { + this.name = name; + } +} + +Object.setPrototypeOf(Dog.prototype, Animal);// Nếu bạn không làm điều này khi gọi hàm speak thì sẽ sinh ra lỗi + +var d = new Dog('Mitzie'); // đối tượng của class Dog +d.speak(); // Mitzie makes a noise. +</pre> + +<h2 id="Species">Species</h2> + +<p>Bạn có thể muốn trả về các đối tượng {{jsxref("Array")}} trong mảng của class <code>MyArray</code>. Mô hình species sẽ cho phép bạn ghi đè lên các hàm khởi tạo mặc định.</p> + +<p>Ví dụ, khi sử dụng những phương thức như là {{jsxref("Array.map", "map()")}} điều đó sẽ trả về giá trị khởi tạo mặc định, bạn muốn những phương thức đó trả về một mảng đối tượng của Array, thay vì đối tượng của <code>MyArray. </code>{{jsxref("Symbol.species")}} sẽ cho phép bạn thực hiện điều này:</p> + +<pre class="brush: js">class MyArray extends Array { + // Overwrite species to the parent Array constructor + static get [Symbol.species]() { return Array; } +} + +var a = new MyArray(1,2,3); +var mapped = a.map(x => x * x); + +console.log(mapped instanceof MyArray); // false +console.log(mapped instanceof Array); // true +</pre> + +<h2 id="Gọi_class_cha_sử_dụng_super">Gọi class cha sử dụng <code>super</code></h2> + +<p>Từ khóa <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> dùng để gọi một hàm có sẵn ở đối tượng cha.</p> + +<pre class="brush: js">class Cat { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Lion extends Cat { + speak() { + super.speak(); + console.log(this.name + ' roars.'); + } +} + +var l = new Lion('Fuzzy'); +l.speak(); +// Fuzzy makes a noise. +// Fuzzy roars. + +</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>Abstract subclasses or <em>mix-ins</em> are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.</p> + +<p>A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:</p> + +<p>Tập hợp các class con hoặc mix-ins được gọi là khuôn mẫu cho các class. Trong ECMAScript một class chỉ có thể có một lớp cha, vì vậy để thừa kế từ tập hợp các class (kế thừa nhiều class) là điều không thể. Các chức năng phải được cung cấp bởi lớp mà nó kế thừa (cung cấp bởi lớp cha).</p> + +<p>Một hàm mà đã được định nghĩa ở lớp cha và lớp con muốn kế thừa và mở rộng hàm đó ra thì có thể sự dụng các lệnh mix-ins trong ECMAScript như sau:</p> + +<pre class="brush: js">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var randomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>Một class để sử dụng mix-ins này có thể viết code như thế này:</p> + +<pre class="brush: js">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="Đặc_điểm_kỹ_thuật">Đặc điểm kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_với_các_trình_duyệt">Tính tương thích với các trình duyệt</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(42.0)}}<sup>[1]</sup><br> + {{CompatChrome(49.0)}}</td> + <td>{{CompatGeckoDesktop(45)}}</td> + <td>13</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(43.0)}}</td> + <td>{{CompatSafari(9.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(45)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>9</td> + <td>{{CompatChrome(56.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Yêu cầu chế độ strict (luôn chạy javascript ở chế độ này). Tắt strict mode trong flag "Enable Experimental JavaScript", mặc định flag này bị vô hiệu hóa.</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/errors/index.html b/files/vi/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/vi/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a <code>name</code> and a <code>message</code>.</p> + +<p>Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.</p> + +<h2 id="List_of_errors">List of errors</h2> + +<p>In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!</p> + +<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Beginner's introductory tutorial on fixing JavaScript errors.</li> +</ul> diff --git a/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..2e5e606618 --- /dev/null +++ b/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,67 @@ +--- +title: 'Lỗi cú pháp: Thiếu dấu ; trước câu lệnh' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +tags: + - JavaScript + - Lỗi + - Lỗi cú pháp +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Thông_điệp">Thông điệp</h2> + +<pre class="syntaxbox">SyntaxError: missing ; before statement +</pre> + +<h2 id="Kiểu_lỗi">Kiểu lỗi</h2> + +<p>{{jsxref("Lỗi cú pháp")}}.</p> + +<h2 id="Sai_ở_đâu">Sai ở đâu?</h2> + +<p>Bạn đang thiếu dấu (<code>;</code>) ở đâu đó. <a href="/en-US/docs/Web/JavaScript/Reference/Statements">Câu lệnh JavaScript</a> phải được kết thúc bằng một dấu "chấm phẩy". Một vài trong số đó được thêm tự động bởi tính năng <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a>, nhưng trong tình huống này bạn cần thêm thủ công để JavaScript có thể hiểu câu lệnh của bạn chính xác.</p> + +<p>Tuy nhiên, thi thoảng lỗi này lại là kết quả của một vài lỗi khác, ví dụ như không kết thúc chuỗi ký tự một cách chính xác, hoặc sử dụng từ khoá <code>var</code> không đúng. Cũng có thể bạn đã thêm quá nhiều dấu ngoặc tròn ở đâu đó. Nếu bạn nhìn thấy lỗi này, trước hết hãy kiểm tra cẩn thận các lỗi cú pháp.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Không_kết_thúc_chuỗi">Không kết thúc chuỗi</h3> + +<p>Lỗi này có thể xảy ra khi bạn quên kết thúc chuỗi, còn JavaScrip thì đang mong đợi điều ấy:</p> + +<pre class="brush: js example-bad">var foo = 'Tom's bar'; +// SyntaxError: missing ; before statement</pre> + +<p>Bạn có thể sử dụng dấu nháy kép hoặc sử dụng dấu \ cho những ký tự đặc biệt thế này:</p> + +<pre class="brush: js example-good">var foo = "Tom's bar"; +var foo = 'Tom\'s bar'; +</pre> + +<h3 id="Khai_báo_thuộc_tính_với_từ_khoá_var">Khai báo thuộc tính với từ khoá var</h3> + +<p>Bạn <strong>KHÔNG THỂ </strong>khai báo thuộc tính của một đối tượng hoặc một mảng bằng từ khoá <strong>var</strong>:</p> + +<pre class="brush: js example-bad">var obj = {}; +var obj.foo = 'hi'; // SyntaxError missing ; before statement + +var array = []; +var array[0] = 'there'; // SyntaxError missing ; before statement +</pre> + +<p>Thay vào đó, hãy cứ bỏ qua từ khoá <strong>var</strong> như thế này:</p> + +<pre class="brush: js example-good">var obj = {}; +obj.foo = 'hi'; + +var array = []; +array[0] = 'there'; +</pre> + +<h2 id="Xem_thêm">Xem thêm:</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">Automatic semicolon insertion (ASI)</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html b/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html new file mode 100644 index 0000000000..4cf87a8b6d --- /dev/null +++ b/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html @@ -0,0 +1,45 @@ +--- +title: 'TypeError: More arguments needed' +slug: Web/JavaScript/Reference/Errors/More_arguments_needed +translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">TypeError: tham số không phải là một đối tượng và không phải là null (Edge) +TypeError: Object.create requires cần ít nhất 1 tham số, nhưng chỉ có 0 được thông qua +TypeError: Object.setPrototypeOf requires cần ít nhất 2 tham số nhưng chỉ có 0 được thông qua +TypeError: Object.defineProperties requires cần ít nhất một tham số, nhưng chỉ có 0 được thông qua +</pre> + +<h2 id="Loại_lỗi">Loại lỗi</h2> + +<p>{{jsxref("Lỗi")}}.</p> + +<h2 id="Chuyện_gì_đã_xảy_ra">Chuyện gì đã xảy ra?</h2> + +<p>Đã có một lỗi với hàm được gọi. Cần cung cấp nhiều tham số hơn</p> + +<h2 id="VÍ_dụ">VÍ dụ</h2> + +<p>Phương thức {{jsxref("Object.create()")}} cần ít nhất 1 tham số và phương thức {{jsxref("Object.setPrototypeOf()")}} cần ít nhất 2 tham số:</p> + +<pre class="brush: js example-bad">var obj = Object.create(); +// TypeError: Object.create requires cần ít nhất là 1 tham số, nhưng chỉ có 0 được thông qua + +var obj = Object.setPrototypeOf({}); +// TypeError: Object.setPrototypeOf requires cần ít nhât 2 tham số, nhưng chỉ có 1 được thông qua +</pre> + +<p>Bạn có thể khắc phục bằng cách đặt {{jsxref("null")}} về nguyên mẫu, ví dụ:</p> + +<pre class="brush: js example-good">var obj = Object.create(null); + +var obj = Object.setPrototypeOf({}, null);</pre> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/errors/not_a_function/index.html b/files/vi/web/javascript/reference/errors/not_a_function/index.html new file mode 100644 index 0000000000..a267a8bc74 --- /dev/null +++ b/files/vi/web/javascript/reference/errors/not_a_function/index.html @@ -0,0 +1,84 @@ +--- +title: 'TypeError: "x" is not a function' +slug: Web/JavaScript/Reference/Errors/Not_a_function +tags: + - JavaScript + - Lỗi + - Lỗi đánh máy +translation_of: Web/JavaScript/Reference/Errors/Not_a_function +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">TypeError: "x" is not a function +</pre> + +<h2 id="Thể_loại_sai">Thể loại sai:</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="Chuyện_gì_đã_xảy_ra">Chuyện gì đã xảy ra?</h2> + +<p>Dự định gọi 1 giá trị như 1 chức năng, nhưng giá trị đó không thật sự là 1 chức năng. Một số đoạn mã chờ bạn cung cấp 1 chức năng, nhưng điều đó không xảy ra.</p> + +<p>Có lẽ là do bạn đánh sai tên chức năng chăng? Có lẽ object mà bạn định gọi method cho không có chức năng này? Ví dụ như những object của Javascript không có chức năng map, nhưng object của Javascript xâu (Array) thì có.</p> + +<p>Có rất nhiều chức năng có sẵn khi cần dùng lại 1 chức năng. Bạn sẽ phải cung cấp 1 chức năng để những method này hoạt động 1 cách chính xác.</p> + +<ul> + <li>Khi sử dụng những object {{jsxref("Array")}} hoặc {{jsxref("TypedArray")}}: + <ul> + <li>{{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Array.prototype.map()")}}, {{jsxref("Array.prototype.filter()")}}, {{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}}, {{jsxref("Array.prototype.find()")}}</li> + </ul> + </li> + <li>Khi sử dụng những object {{jsxref("Map")}} và {{jsxref("Set")}} : + <ul> + <li>{{jsxref("Map.prototype.forEach()")}} and {{jsxref("Set.prototype.forEach()")}}</li> + </ul> + </li> +</ul> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Lỗi_đánh_máy_trong_tên_chức_năng">Lỗi đánh máy trong tên chức năng</h3> + +<p>Trong trường hợp này, xảy ra rất thường xuyên, có 1 lỗi đánh máy trong tên method:</p> + +<pre class="brush: js example-bad">var x = document.getElementByID('foo'); +// TypeError: document.getElementByID is not a function +</pre> + +<p>Tên đúng là <code>getElementByI<strong>d</strong></code>:</p> + +<pre class="brush: js example-good">var x = document.getElementById('foo'); +</pre> + +<h3 id="Chức_năng_bị_gọi_sai_trên_object">Chức năng bị gọi sai trên object</h3> + +<p>Đối với 1 số method nhất định, bạn phải cung cấp 1 chức năng (để gọi trở lại) và nó sẽ hoạt động trên những object nhất định đó thôi. Ví dụ khi {{jsxref("Array.prototype.map()")}} được sử dụng, thì sẽ chỉ chạy với object {{jsxref("Array")}} này mà thôi.</p> + +<pre class="brush: js example-bad">var obj = {a: 13, b: 37, c: 42}; + +obj.map(function(num) { + return num * 2; +}); + +// TypeError: obj.map is not a function</pre> + +<p>Thay vào đó, sử dụng 1 xâu:</p> + +<pre class="brush: js example-good">var numbers = [1, 4, 9]; + +numbers.map(function(num) { + return num * 2; +}); + +// Array [2, 8, 18] +</pre> + +<h2 id="Liên_kết">Liên kết:</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/errors/qua_nhieu_de_quy/index.html b/files/vi/web/javascript/reference/errors/qua_nhieu_de_quy/index.html new file mode 100644 index 0000000000..a4851c4f56 --- /dev/null +++ b/files/vi/web/javascript/reference/errors/qua_nhieu_de_quy/index.html @@ -0,0 +1,54 @@ +--- +title: 'InternalError: Quá nhiều đệ quy' +slug: Web/JavaScript/Reference/Errors/qua_nhieu_de_quy +tags: + - JavaScript + - Lỗi + - Lỗi bên trong +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Thông_điệp">Thông điệp</h2> + +<pre class="syntaxbox">InternalError: too much recursion +</pre> + +<h2 id="Loại_lỗi">Loại lỗi</h2> + +<p>{{jsxref("InternalError")}}.</p> + +<h2 id="Lỗi_phát_sinh_ra_khi_nào">Lỗi phát sinh ra khi nào?</h2> + +<p>Một hàm gọi chính nó được gọi là hàm đệ quy . Trong một số trường hợp, đệ quy tương tự như một vòng lặp. Cả hai đều thực hiện cùng một mã nhiều lần, Và cả hai đều yêu cầu một điều kiện ( Để tránh một vòng lặp vô hạn, hoặc đúng hơn, đệ quy vô hạn trong trường hợp này ). <span class="seoSummary"> Khi có quá nhiều hoặc vô hạn đệ quy, JavaScript sẽ ném lỗi này.</span></p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<p>Chức năng đệ quy này chạy 10 lần, theo điều kiện x >= 10 .</p> + +<pre class="brush: js">function loop(x) { + if (x >= 10) // "x >= 10" là điều kiện dừng + return; + // do stuff + loop(x + 1); // gọi lại chính nó (đệ quy) +} +loop(0);</pre> + +<p>Đặt điều kiện này lên một giá trị rất cao, sẽ không hoạt động:</p> + +<pre class="brush: js example-bad">function loop(x) { + if (x >= 1000000000000) + return; + // do stuff + loop(x + 1); +} +loop(0); + +// InternalError: too much recursion</pre> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{Glossary("Recursion")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Recursion">Recursive functions</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/functions/arguments/index.html b/files/vi/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..ffcb00b472 --- /dev/null +++ b/files/vi/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,234 @@ +--- +title: The arguments object +slug: Web/JavaScript/Reference/Functions/arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +<p>{{JSSidebar("Functions")}}</p> + +<p><strong><code>arguments</code></strong> là object giống <code>Array</code> khả truy cập bên trong <a href="/en-US/docs/Web/JavaScript/Guide/Functions">hàm</a>, chứa các giá trị của đối số truyền vào trong hàm đó.</p> + +<div class="blockIndicator note"> +<p><strong>Ghi chú:</strong> Nếu bạn viết mã tương thích cho ES6, thì bạn nên tham khảo <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> +</div> + +<div class="blockIndicator note"> +<p><strong>Ghi chú:</strong> “Giống Array” tức là <code>arguments</code> có thuộc tính {{jsxref("Functions/arguments/length", "length")}} và đánh chỉ mục từ không (0), nhưng nó không có phương thức dựng sẵn của {{JSxRef("Array")}} như {{jsxref("Array.forEach", "forEach()")}} và {{jsxref("Array.map", "map()")}}. Xem <a href="#Mô_tả">§Mô tả</a> để biết thêm chi tiết.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">arguments</pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Object <code>arguments</code> là biến cục bộ có sẵn cho mọi hàm không phải <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">hàm mũi tên</a>. Bạn có thể tham chiếu tới đối số của một hàm bên trong hàm đó bằng cách sử dụng object <code>arguments</code>. Nó chứa từng đối số mà hàm đó được gọi cùng, với chỉ mục bắt đầu từ 0.</p> + +<p>Chẳng hạn, nếu một hàm được truyền vào 3 đối số, bạn có thể truy cập nó theo cách sau:</p> + +<pre class="brush: js">arguments[0] // đối số thứ nhất +arguments[1] // đối số thứ hai +arguments[2] // đối số thứ ba +</pre> + +<p>Mỗi đối số đều có thể thiết lập hoặc gán lại:</p> + +<pre class="brush: js">arguments[1] = 'new value'; +</pre> + +<p>Object <code>arguments</code> không phải là {{jsxref("Array")}}. Nó tương tự nhưng không có thuộc tính của <code>Array</code> ngoài {{jsxref("Array.length", "length")}}. Chẳng hạn, nó không có phương thức {{jsxref("Array.pop", "pop()")}}. Tuy nhiên, nó có thể ép kiểu về <code>Array</code>:</p> + +<pre class="brush: js">var args = Array.prototype.slice.call(arguments); +// Using an array literal is shorter than above but allocates an empty array +var args = [].slice.call(arguments); +</pre> + +<p>Như có thể làm với mọi object giống-Array, bạn có thể dùng phương thức {{jsxref("Array.from()")}} của ES2015 hoặc <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">cú pháp spread</a> để ép kiểu <code>arguments</code> thành Array:</p> + +<pre class="brush: js">var args = Array.from(arguments); +var args = [...arguments]; +</pre> + +<p>Object <code>arguments</code> có ích đối với hàm được truyền nhiều đối số hơn so với khởi tạo ban đầu. Kỹ thuật này có ích với hàm cần được truyền nhiều biến, như là {{jsxref("Math.min()")}}. Hàm ví dụ dưới đây chấp nhật mọi xâu ký tự và trả về xâu dài nhất:</p> + +<pre class="brush: js">function longestString() { + var longest = ''; + for (var i=0; i < arguments.length; i++) { + if (arguments[i].length > longest.length) { + longest = arguments[i]; + } + } + return longest; +} +</pre> + +<p>Bạn có thể dùng {{jsxref("Functions/arguments/length", "arguments.length")}} để đếm số lượng đối số được truyền vào khi hàm được gọi. Thay vì thế, nếu bạn muốn đếm số lượng tham số chính quy mà hàm chấp nhận khi khởi tạo, hãy tham khảo thuộc tính {{jsxref("Function.length", "length")}} của hàm.</p> + +<h3 id="Sử_dụng_typeof_với_Arguments">Sử dụng <code>typeof</code> với Arguments</h3> + +<p>Toán tử {{jsxref("Operators/typeof", "typeof")}} trả về <code>'object'</code> khi dùng với <code>arguments</code></p> + +<pre class="brush: js">console.log(typeof arguments); // 'object' </pre> + +<p>Kiểu của từng đối số có thể xác định lần lượt bằng cách chỉ đích danh trong object <code>arguments</code>:</p> + +<pre>console.log(typeof arguments[0]); // trả về kiểu của đối số thứ nhất</pre> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt>{{jsxref("Functions/arguments/callee", "arguments.callee")}}</dt> + <dd>Tham chiếu tới hàm đang được thực thi sở hữu arguments.</dd> + <dt>{{jsxref("Functions/arguments/caller", "arguments.caller")}} {{Obsolete_Inline}}</dt> + <dd>Reference to the function that invoked the currently executing function.</dd> + <dt>{{jsxref("Functions/arguments/length", "arguments.length")}}</dt> + <dd>Số lượng đối số được truyền vào hàm.</dd> + <dt>{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}</dt> + <dd>Returns a new {{jsxref("Array/@@iterator", "<code>Array</code> iterator", "", 0)}} object that contains the values for each index in the <code>arguments</code>.</dd> +</dl> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Định_nghĩa_hàm_nối_xâu_ký_tự">Định nghĩa hàm nối xâu ký tự</h3> + +<p>Ví dụ sau đây định nghĩa một hàm nối các xâu ký tự với nhau. Tham số chính quy mà hàm nhận là một xâu chứa các ký tự ngăn cách các xâu với nhau sau khi được nối.</p> + +<pre class="brush:js">function myConcat(separator) { + var args = Array.prototype.slice.call(arguments, 1); + return args.join(separator); +}</pre> + +<p>Bạn có thể truyền vào bao nhiêu xâu ký tự tuỳ ý. Giá trị trả về là một xâu chứa tất cả các đối số được truyền vào:</p> + +<pre class="brush:js">// trả về "red, orange, blue" +myConcat(', ', 'red', 'orange', 'blue'); + +// trả về "elephant; giraffe; lion; cheetah" +myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah'); + +// trả về "sage. basil. oregano. pepper. parsley" +myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');</pre> + +<h3 id="Định_nghĩa_hàm_sinh_danh_sách_HTML">Định nghĩa hàm sinh danh sách HTML</h3> + +<p>Ví dụ sau đây định nghĩa một hàm sinh ra một xâu ký tự chứa các thẻ HTML để tạo thành một danh sách. Tham số chính quy duy nhất mà hàm nhận là một ký tự như "<code>u</code>" nếu danh sách không có thứ tự (đánh dấu chấm), hay "<code>o</code>" nếu danh sách có thứ tự (đánh số). Hàm đó được định nghĩa như sau:</p> + +<pre class="brush:js">function list(type) { + var html = '<' + type + 'l><li>'; + var args = Array.prototype.slice.call(arguments, 1); + html += args.join('</li><li>'); + html += '</li></' + type + 'l>'; // end list + + return html; +}</pre> + +<p>Bạn có thể truyền bao nhiêu đối số tuỳ ý, và nó sẽ thêm từng đối số vào danh sách có kiểu xác định trước. Chẳng hạn:</p> + +<pre class="brush:js">var listHTML = list('u', 'One', 'Two', 'Three'); + +/* listHTML is: +"<ul><li>One</li><li>Two</li><li>Three</li></ul>" +*/</pre> + +<h3 id="Tham_số_rest_default_và_destructured">Tham số rest, default và destructured</h3> + +<p>Object <code>arguments</code> có thể dùng cùng lúc với các tham số như <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default</a>, và <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructured</a>.</p> + +<pre class="brush: js">function foo(...args) { + return args; +} +foo(1, 2, 3); // [1,2,3] +</pre> + +<p>Tuy trong strict-mode, tham số rest, default, hoặc destructured parameters không can thiệp vào <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode#Making_eval_and_arguments_simpler">hành vi của object <code>arguments</code></a>, nhưng trong non-strict mode vẫn có không ít khác biệt.</p> + +<p>Nếu một hàm non-strict <strong>không</strong> chứa tham số rest, default, hay destructured, thì giá trị trong object <code>arguments</code> <strong>có</strong> thay đổi đồng bộ với giá trị của tham số truyền vào. Hãy xem đoạn mã dưới đây:</p> + +<pre class="brush: js">function func(a) { + arguments[0] = 99; // cập nhật arguments[0] cũng cập nhật a + console.log(a); +} +func(10); // 99 +</pre> + +<p>và</p> + +<pre class="brush: js">function func(a) { + a = 99; // cập nhật a cũng cập nhật arguments[0] + console.log(arguments[0]); +} +func(10); // 99 +</pre> + +<p>Khi hàm non-strict <strong>có</strong> chứa tham số rest, default hoặc destructured, thì giá trị trong object <code>arguments</code> <strong>không</strong> theo dõi giá trị của đối số. Thay vì vậy, chúng ánh xạ đến đối số truyền vào khi hàm được gọi:</p> + +<pre class="brush: js">function func(a = 55) { + arguments[0] = 99; // updating arguments[0] does not also update a + console.log(a); +} +func(10); // 10</pre> + +<p>và</p> + +<pre class="brush: js">function func(a = 55) { + a = 99; // updating a does not also update arguments[0] + console.log(arguments[0]); +} +func(10); // 10 +</pre> + +<p>và</p> + +<pre class="brush: js">// An untracked default parameter +function func(a = 55) { + console.log(arguments[0]); +} +func(); // undefined</pre> + +<h2 id="Đặc_tả_kĩ_thuật">Đặc tả kĩ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + + + +<p>{{Compat("javascript.functions.arguments")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{JSxRef("Function")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/functions/arrow_functions/index.html b/files/vi/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..6da70e4205 --- /dev/null +++ b/files/vi/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,426 @@ +--- +title: Hàm mũi tên (hàm rút gọn) +slug: Web/JavaScript/Reference/Functions/Arrow_functions +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong>Biểu thức hàm mũi tên</strong> là một thay thế rút gọn cho <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">hàm biểu thức</a> truyền thống, nhưng bị hạn chế và không thể sử dụng trong mọi trường hợp.</p> + +<p><strong>Sự khác biệt & Hạn chế:</strong></p> + +<ul> + <li>Không hỗ trợ binddings đến con trỏ <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Operators/this">this</a></code> hoặc <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Operators/super">super</a></code>, và không nên dùng ở <code><a href="https://wiki.developer.mozilla.org/vi/docs/Glossary/Method">methods</a></code>.</li> + <li>Không có <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>, hoặc từ khóa <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></code>.</li> + <li>Không phù hợp với các phương thức <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call</a></code>, <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply</a></code> và <a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"><code>bind</code></a>, thường dựa vào thiết lập <a href="https://wiki.developer.mozilla.org/vi/docs/Glossary/Scope"><code>scope</code>.</a></li> + <li>Không sử dụng để <code><a href="https://wiki.developer.mozilla.org/vi/docs/Glossary/constructor">constructors</a></code>.</li> + <li>Không thể dùng <code><a href="https://wiki.developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code>, trong nội dung (body).</li> +</ul> + +<p>{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}</p> + +<h3 id="So_sánh_hàm_truyền_thống_và_hàm_mũi_tên"><strong>So sánh hàm truyền thống và hàm mũi tên</strong></h3> + +<p>Hãy phân tách "hàm truyền thống" thành "hàm mũi tên" đơn giản nhất theo từng bước:<br> + LƯU Ý: Mỗi bước là một "hàm mũi tên" hợp lệ.</p> + +<pre class="notranslate">// Hàm truyền thống +function (a){ + return a + 100; +} + +// Phân rã thành hàm mũi tên + +// 1. Xóa từ khóa "function" và thay thế bằng mũi tên ở giữa đối số và dấu ngoặc nhọn bắt đầu nội dung hàm +(a) => { + return a + 100; +} + +// 2. Xóa dấu ngoặc nhọn và từ khóa "return" sự trả về đã bao hàm (mặc định) khi sử dụng hàm mũi tên. +(a) => a + 100; + +// 3. Xóa luôn dấu ngoặc đơn của đối số +a => a + 100;</pre> + +<p>Như bạn thấy ở bên trên, dấu { ngoặc nhọn } và dấu (ngoặc tròn ở đối ố) và "return" là tùy chọn, nhưng đôi khi có thể bắt buộc phải có.</p> + +<p>Ví dụ, nếu bạn có <strong>nhiều đối số</strong> hoặc <strong>không có đối số</strong>, bạn cần phải thêm dấu ngoặc tròn vào xung quanh các đối số:</p> + +<pre class="notranslate">// Hàm Truyền thống +function (a, b){ + return a + b + 100; +} + +// Hàm mũi tên +(a, b) => a + b + 100; + +// Hàm truyền thống (không đối số) +let a = 4; +let b = 2; +function (){ + return a + b + 100; +} + +// Hàm mũi tên (không đối số) +let a = 4; +let b = 2; +() => a + b + 100;</pre> + +<p>Tương tự như vậy, nếu nội dung (body) hàm cần thêm <strong>nhiều dòng</strong> để xử lý thì bạn cần thêm vào dấu ngoặc nhọn <strong>CỘNG thêm "return"</strong> (hàm mũi tên không có kỳ diệu đến mức biết khi nào bạn muốn "return"):</p> + +<pre class="notranslate">// Hàm truyền thống +function (a, b){ + let chuck = 42; + return a + b + chuck; +} + +// Hàm mũi tên +(a, b) => { + let chuck = 42; + return a + b + chuck; +}</pre> + +<p>Và cuối cùng, với các <strong>hàm được đặt tên</strong> chúng tôi xử lý các biểu thức mũi tên như các biến</p> + +<pre class="notranslate">// Hàm truyền thống +function bob (a){ + return a + 100; +} + +// Hàm mũi tên +let bob = a => a + 100;</pre> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<h3 id="Cú_pháp_cơ_bản">Cú pháp cơ bản</h3> + +<pre class="syntaxbox notranslate"><strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>) => {</strong> <em>statements</em> <strong>}</strong> +<strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>) =></strong> <em>expression</em> +// tương đương với: <strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>)</strong> => { return <em>expression</em>; } + +// Dấu ngoặc đơn không bắt buộc khi chỉ có một tham số truyền vào: +<em>(singleParam)</em> <strong>=> {</strong> <em>statements</em> <strong>}</strong> +<em>singleParam</em> <strong>=></strong> { <em>statements }</em> + +// Hàm khi không có tham số truyền vào bắt buộc phải là dấu (): +<strong>() => {</strong> <em>statements</em> <strong>} +</strong>() => <em>expression</em> // tương đương: () => { return <em>expression</em>; } +</pre> + +<h3 id="Cú_pháp_nâng_cao">Cú pháp nâng cao</h3> + +<pre class="syntaxbox notranslate">// Bên trong dấu ngoặc đơn là một đối tượng: +<em>params</em> => ({<em>foo: bar</em>}) + +// <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a> và <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> được hỗ trợ +(<em>param1</em>, <em>param2</em>, <strong>...rest</strong>) => { <em>statements</em> } +(<em>param1</em> <strong>= defaultValue1</strong>, <em>param2</em>, …, paramN <strong>= defaultValueN</strong>) => { <em>statements</em> } + +// <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring</a> within the parameter list is also supported +var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); // 6 +</pre> + +<p>Chi tiết các ví dụ bạn có thể xem ở <a href="http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax">đây</a>.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Xem thêm <a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 Chuyên sâu: Những hàm arrow" trên hacks.mozilla.org</a>.</p> + +<p>Two factors influenced the introduction of arrow functions: shorter functions and non-binding of <code>this</code>.</p> + +<h3 id="Hàm_ngắn">Hàm ngắn</h3> + +<p>Một vài ví dụ, cú pháp hàm rút gọn luôn được <strong>coder </strong>yêu thích, cùng so sánh:</p> + +<pre class="brush: js notranslate">var materials = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +// thông thường +var materialsLength1 = materials.map(function(material) { + return material.length; +}); + +// ngắn hơn (như mùa đông 5 độ vậy) +var materialsLength2 = materials.map((material) => { + return material.length; +}); + +// ngắn hơn nữa (và -2 độ, bạn còn bao nhiêu cm ?) +var materialsLength3 = materials.map(material => material.length); +</pre> + +<h3 id="Không_ràng_buộc_this">Không ràng buộc <code>this</code></h3> + +<p>Cho tới khi hàm rút gọn xuất hiện, mọi hàm mới đều tự định nghĩa giá trị <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> của riêng hàm (là object vừa được khởi tạo nếu dùng constructor, là undefined nếu đặt <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> khi gọi hàm, là context object nếu hàm được gọi như một "object method", vân vân.). <code>This</code> trở nên khá khó chịu khi làm việc với phong cách lập trình hướng đối tượng.</p> + +<pre class="brush: js notranslate">function Person() { + // constructor của Person() định nghĩa `this` như một biến. + this.age = 0; + + setInterval(function growUp() { + // Khi dùng non-strict mode, hàm growUp() định nghĩa `this` + // như một đối tượng toàn cục, khác hoàn toàn so với `this` + // được định nghĩa bởi constructor của Person(). + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>Theo ECMAScript 3/5, vấn đề của <code>this</code> có thể sửa được bằng cách gán <code>this</code> cho một biến gần nhất.</p> + +<pre class="brush: js notranslate">function Person() { + var that = this; + that.age = 0; + + setInterval(function growUp() { + // Hàm callback trỏ tới biến `that`với + // giá trị là đối tượng mong đợi. + that.age++; + }, 1000); +}</pre> + +<p>Nói cách khác, tạo ra một <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">hàm ràng buộc</a> để truyền giá trị của <code>this</code> vào hàm ràng buộc đích (chẳng hạn như hàm <code>growUp()</code> phía trên).</p> + +<p>Hàm rút gọn không tạo ra ngữ cảnh <code>this</code> của riêng hàm, thế nên <code>this</code> có ý nghĩa trong ngữ cảnh bọc quanh nó. Đoạn code phía dưới là một ví dụ:</p> + +<pre class="brush: js notranslate">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this| ở đây trỏ tới đối tượng person + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="Mối_liên_hệ_với_strict_mode">Mối liên hệ với strict mode</h4> + +<p>Giả sử <code>this</code> bị bó buộc trong thân hàm, <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> sẽ khiến cho <code>this</code> bị bỏ qua.</p> + +<pre class="brush: js notranslate">var f = () => { 'use strict'; return this; }; +f() === window; // hoặc đối tượng toàn cục</pre> + +<p>Các strict mode khác được áp dụng như bình thường.</p> + +<h4 id="Gọi_thông_qua_call_hoặc_apply">Gọi thông qua call hoặc apply</h4> + +<p>Vì <code>this</code><em> </em>không bị ràng buộc bên trong hàm rút gọn, các phương thức <code>call()</code><em> </em>hoặc <code>apply()</code> chỉ có thể truyền tham số. <code>this</code> bị bỏ qua.</p> + +<pre class="brush: js notranslate">var adder = { + base: 1, + + add: function(a) { + var f = v => v + this.base; + return f(a); + }, + + addThruCall: function(a) { + var f = v => v + this.base; + var b = { + base: 2 + }; + + return f.call(b, a); + } +}; + +console.log(adder.add(1)); // Sẽ trả ra 2 +console.log(adder.addThruCall(1)); // Vẫn sẽ trả ra 2</pre> + +<h3 id="Không_ràng_buộc_arguments">Không ràng buộc <code>arguments</code></h3> + +<p>Hàm rút gọn không ràng buộc <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> object</a>. Do đó, trong ví dụ sau, <code>arguments</code> chỉ đơn giản là một tham chiếu đến đối tượng cùng tên trong phạm vi bao quanh:</p> + +<pre class="brush: js notranslate">var arguments = 42; +var arr = () => arguments; + +arr(); // 42 + +function foo() { + var f = (i) => arguments[0] + i; // <em>foo</em>'s implicit arguments binding + return f(2); +} + +foo(1); // 3</pre> + +<p>Trong nhiều trường hợp, sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> là một cách thay thế tốt để dùng đối tượng <code>arguments</code>.</p> + +<pre class="brush: js notranslate">function foo() { + var f = (...args) => args[0]; + return f(2); +} + +foo(1); // 2</pre> + +<h3 id="Dùng_hàm_rút_gọn_như_một_phương_thức">Dùng hàm rút gọn như một phương thức</h3> + +<p>Như đã nói phía trên, biểu thức hàm rút gọn cực kì hợp với các hàm non-method. Hãy xem chuyện gì sẽ xảy ra khi ta dùng chúng như phương thức trong ví dụ bên dưới nhé:</p> + +<pre class="brush: js notranslate">'use strict'; +var obj = { + i: 10, + b: () => console.log(this.i, this), + c: function() { + console.log(this.i, this); + } +} +obj.b(); // in ra undefined, Object {...} +obj.c(); // in ra 10, Object {...}</pre> + +<p>Hàm rút gọn không định nghĩa ("ràng buộc") <code>this</code> của hàm. Một ví dụ khác đối với {{jsxref("Object.defineProperty()")}}:</p> + +<pre class="brush: js notranslate">'use strict'; +var obj = { + a: 10 +}; + +Object.defineProperty(obj, 'b', { + get: () => { + console.log(this.a, typeof this.a, this); + return this.a + 10; // đại diện cho đối tượng toàn cục 'Window', bởi vậy 'this.a' trả về 'undefined' + } +}); +</pre> + +<h3 id="Dùng_toán_tử_new">Dùng toán tử <code>new</code></h3> + +<p>Hàm rút gọn không thể dùng như phương thức khởi tạo và sẽ báo lỗi nếu dùng toán tử <code>new</code>.</p> + +<pre class="brush: js notranslate">var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</pre> + +<h3 id="Dùng_thuộc_tính_prototype">Dùng thuộc tính <code>prototype</code></h3> + +<p>Hàm rút gọn không có thuộc tính <code>prototype</code>.</p> + +<pre class="brush: js notranslate">var Foo = () => {}; +console.log(Foo.prototype); // undefined +</pre> + +<h3 id="Dùng_từ_khoá_yield">Dùng từ khoá <code>yield</code></h3> + +<p>Từ khoá <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> có thể sẽ không dùng được trong thân hàm rút gọn (trừ khi được gọi trong hàm lồng trong hàm rút gọn). Tức là, hàm rút gọn không thể dùng như là generator (hàm sinh).</p> + +<h2 id="Phần_thân_hàm">Phần thân hàm</h2> + +<p>Hàm rút gọn vừa có thể có "concise body" hoặc dạng thường thấy "block body".</p> + +<p>Trong concise body, chỉ cần biểu thức, return sẽ được gán ngầm. Còn với block body, bạn phải có <code>return</code>.</p> + +<pre class="brush: js notranslate">var func = x => x * x; // concise syntax, implied "return" +var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed +</pre> + +<h2 id="Trả_về_object_literals">Trả về object literals</h2> + +<p>Không thể dùng cú pháp <code>params => {object:literal}</code> nếu muốn trả về object literal.</p> + +<pre class="brush: js notranslate">var func = () => { foo: 1 }; // Calling func() returns undefined! +var func = () => { foo: function() {} }; // SyntaxError: function statement requires a name</pre> + +<p>Bởi vì đoạn code bên trong ({}) được phân giải thành một chuỗi các trình tự nối tiếp (ví dụ <code>foo</code> được coi như một nhãn, thay vì một key trong object literal).</p> + +<p>Thế nên hãy bao object literal trong ngoặc tròn.</p> + +<pre class="brush: js notranslate">var func = () => ({foo: 1});</pre> + +<h2 id="Kí_tự_xuống_dòng">Kí tự xuống dòng</h2> + +<p>Hàm rút gọn không thể chứa bất cứ kí tự rút gọn nào giữa phần truyền tham số và dấu mũi tên.</p> + +<pre class="brush: js notranslate">var func = () + => 1; // SyntaxError: expected expression, got '=>'</pre> + +<h2 id="Parsing_order">Parsing order</h2> + +<p>Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a> compared to regular functions.</p> + +<pre class="brush: js notranslate">let callback; + +callback = callback || function() {}; // ok +callback = callback || () => {}; // SyntaxError: invalid arrow-function arguments +callback = callback || (() => {}); // ok +</pre> + +<h2 id="Một_số_ví_dụ_khác">Một số ví dụ khác</h2> + +<pre class="brush: js notranslate">// An empty arrow function returns undefined +let empty = () => {}; + +(() => 'foobar')(); // <a href="/en-US/docs/Glossary/IIFE">IIFE</a>, returns "foobar" + +var simple = a => a > 15 ? 15 : a; +simple(16); // 15 +simple(10); // 10 + +let max = (a, b) => a > b ? a : b; + +// Easy array filtering, mapping, ... + +var arr = [5, 6, 13, 0, 1, 18, 23]; +var sum = arr.reduce((a, b) => a + b); // 66 +var even = arr.filter(v => v % 2 == 0); // [6, 0, 18] +var double = arr.map(v => v * 2); // [10, 12, 26, 0, 2, 36, 46] + +// More concise promise chains +promise.then(a => { + // ... +}).then(b => { + // ... +}); + +// Parameterless arrow functions that are visually easier to parse +setTimeout( () => { + console.log('I happen sooner'); + setTimeout( () => { + // deeper code + console.log('I happen later'); + }, 1); +}, 1); +</pre> + +<h2 id="Đặc_điểm_kĩ_thuật">Đặc điểm kĩ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div>{{Compat("javascript.functions.arrow_functions")}}</div> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> + <li>The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of <a href="/en-US/docs/Mozilla/Firefox/Releases/24">Firefox 24</a>. The use of <code>"use strict";</code> is now required.</li> + <li>Arrow functions are semantically different from the non-standard {{jsxref("Operators/Expression_Closures", "expression closures", "", 1)}} added in <a href="/en-US/Firefox/Releases/3">Firefox 3</a> (details: <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8">JavaScript 1.8</a>), for {{jsxref("Operators/Expression_Closures", "expression closures", "", 1)}} do not bind <code>this</code> lexically.</li> + <li>Prior to <a href="/en-US/Firefox/Releases/39">Firefox 39</a>, a line terminator (<code>\n</code>) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like <code>() \n => {}</code> will now throw a {{jsxref("SyntaxError")}} in this and later versions.</li> +</ul> + +<h2 id="Tìm_đọc">Tìm đọc</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" trên hacks.mozilla.org</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/functions/default_parameters/index.html b/files/vi/web/javascript/reference/functions/default_parameters/index.html new file mode 100644 index 0000000000..11ae77dab7 --- /dev/null +++ b/files/vi/web/javascript/reference/functions/default_parameters/index.html @@ -0,0 +1,198 @@ +--- +title: Default parameters +slug: Web/JavaScript/Reference/Functions/Default_parameters +translation_of: Web/JavaScript/Reference/Functions/Default_parameters +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Các tham số của hàm mặc định cho phép khởi tạo với các giá trị mặc định khi không truyền giá trị vào đó.</p> + +<div>{{EmbedInteractiveExample("pages/js/functions-default.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param1</em>[ = defaultValue1 ][, ..., <em>paramN</em>[ = defaultValueN ]]]) { + <em>statements</em> +} +</pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Trong JavaScript, tham số của hàm mặc định <code>{{jsxref("undefined")}}</code>. Tuy nhiên, chúng thường hữu ích hơn khi tạo giá trị mặc định khác. </p> + +<p>Trước đây, quy tắc chung khi tạo giá trị mặc định là kiểm tra các giá trị tham số trong thân hàm và gán vào tham số nếu nó không xác định.</p> + +<p>Trong ví dụ sau, nếu không cung cấp giá trị cho b khi gọi hàm multiply, b sẽ không xác định trong phép tính a * b và hàm multiply sẽ trả về NaN.</p> + +<pre class="brush: js">function multiply(a, b) { + return a * b; +} + +multiply(5, 2); // 10 +multiply(5); // NaN ! +</pre> + +<p>Để tránh điều này, ta sẽ dùng một dòng code xác định b=1 nếu hàm chỉ được gọi với 1 đối số.</p> + +<pre class="brush: js">function multiply(a, b) { + b = (typeof b !== 'undefined') ? b : 1; + return a * b; +} + +multiply(5, 2); // 10 +multiply(5); // 5 +</pre> + +<p>Với các tham số mặc định trong ES2015, việc kiểm tra thân hàm không còn cần thiết. Bạn có thể gán 1 cho b ở đầu hàm:</p> + +<pre class="brush: js">function multiply(a, b = 1) { + return a * b; +} + +multiply(5, 2); // 10 +multiply(5); // 5 +</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Truyền_giá_trị_undefined_với_giá_trị_ảo">Truyền giá trị <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(255, 255, 255, 0.4);">undefined</span></font> với giá trị ảo</h3> + +<p>Trong lời gọi thứ hai, ngay cả khi đối số thứ nhất không xác định (không phải null hay giá trị ảo), đối số num vẫn mặc định.</p> + +<p>function test(num = 1) { console.log(typeof num); } test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: test(''); // 'string' (num is set to '') test(null); // 'object' (num is set to null)</p> + +<h3 id="Xét_tại_thời_điểm_gọi">Xét tại thời điểm gọi</h3> + +<p>Đối số mặc định được xét tại thời điểm gọi. Trong khi Python, một đối tượng mới được tạo ra mỗi khi hàm được gọi.</p> + +<p>function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]</p> + +<p>Áp dụng cho cả hàm và biến:</p> + +<pre class="brush: js">function callSomething(thing = something()) { + return thing; +} + +let numberOfTimesCalled = 0; +function something() { + numberOfTimesCalled += 1; + return numberOfTimesCalled; +} + +callSomething(); // 1 +callSomething(); // 2</pre> + +<h3 id="Các_tham_số_mặc_định_có_sẵn_cho_các_tham_số_mặc_định_sau">Các tham số mặc định có sẵn cho các tham số mặc định sau:</h3> + +<p>Các tham số được xác định trước (bên trái) có sẵn cho các tham số mặc định sau:</p> + +<p>function greet(name, greeting, message = greeting + ' ' + name) { return [name, greeting, message]; } greet('David', 'Hi'); // ["David", "Hi", "Hi David"] greet('David', 'Hi', 'Happy Birthday!'); // ["David", "Hi", "Happy Birthday!"]</p> + +<p>This functionality can be aChức năng này sử dụng cho nhiều trường hợp xảy ra:</p> + +<pre class="brush: js">function go() { + return ':P'; +} + +function withDefaults(a, b = 5, c = b, d = go(), e = this, + f = arguments, g = this.value) { + return [a, b, c, d, e, f, g]; +} + +function withoutDefaults(a, b, c, d, e, f, g) { + switch (arguments.length) { + case 0: + a; + case 1: + b = 5; + case 2: + c = b; + case 3: + d = go(); + case 4: + e = this; + case 5: + f = arguments; + case 6: + g = this.value; + default: + } + return [a, b, c, d, e, f, g]; +} + +withDefaults.call({value: '=^_^='}); +// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] + +withoutDefaults.call({value: '=^_^='}); +// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] +</pre> + +<h3 id="Định_nghĩa_hàm_trong_thân_hàm">Định nghĩa hàm trong thân hàm</h3> + +<p>Giới thiệu trong Gecko 33 {{geckoRelease(33)}}. Các hàm được khai báo trong thân hàm không thể được tham chiếu bên trong với các tham số mặc định của hàm ngoài. Nếu bạn thử, {{jsxref("ReferenceError")}} sẽ bị loại bỏ. Các tham số mặc định luôn được thực thi trước, hàm khai báo bên trong thân hàm sẽ thực thi sau.</p> + +<pre class="brush: js">// Doesn't work! Throws ReferenceError. +function f(a = go()) { + function go() { return ':P'; } +} +</pre> + +<h3 id="Tham_số_không_mặc_định">Tham số không mặc định</h3> + +<p>Trước Gecko 26 {{geckoRelease(26)}}, đoạn code sau cho kết quả {{jsxref("SyntaxError")}}. Sau đó được sửa lại {{bug(777060)}}. Các tham số vẫn xuất hiện từ trái qua phải, ghi đè lên các tham số mặc định kể cả các tham số sau không mặc định.</p> + +<pre class="brush: js">function f(x = 1, y) { + return [x, y]; +} + +f(); // [1, undefined] +f(2); // [2, undefined] +</pre> + +<h3 id="Tham_số_bị_hủy_gán_với_giá_trị_mặc_định">Tham số bị hủy gán với giá trị mặc định</h3> + +<p>Có thể dùng giá trị mặc định với kí hiệu <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment</a>:</p> + +<pre class="brush: js">function f([x, y] = [1, 2], {z: z} = {z: 3}) { + return x + y + z; +} + +f(); // 6</pre> + +<h2 id="Đặc_điểm">Đặc điểm</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc điểm</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa ban đầu</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<div> + + +<p>{{Compat("javascript.functions.default_parameters")}}</p> +</div> + +<h2 id="Liên_quan">Liên quan</h2> + +<ul> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values" rel="external" title="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values">Original proposal at ecmascript.org</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/functions/index.html b/files/vi/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..e7935d3318 --- /dev/null +++ b/files/vi/web/javascript/reference/functions/index.html @@ -0,0 +1,657 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> + +<p>In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> + +<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> + +<h2 id="Description">Description</h2> + +<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> + +<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is {{jsxref("undefined")}}.</p> + +<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:</p> + +<pre class="brush: js">/* Declare the function 'myFunc' */ +function myFunc(theObject) { + theObject.brand = "Toyota"; + } + + /* + * Declare variable 'mycar'; + * create and initialize a new Object; + * assign reference to it to 'mycar' + */ + var mycar = { + brand: "Honda", + model: "Accord", + year: 1998 + }; + + /* Logs 'Honda' */ + console.log(mycar.brand); + + /* Pass object reference to the function */ + myFunc(mycar); + + /* + * Logs 'Toyota' as the value of the 'brand' property + * of the object, as changed to by the function. + */ + console.log(mycar.brand); +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> + +<h2 id="Defining_functions">Defining functions</h2> + +<p>There are several ways to define functions:</p> + +<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> + +<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> + +<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> + +<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not <em>hoisted</em> onto the beginning of the scope, therefore they cannot be used before they appear in the code.</p> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<p>Here is an example of an <strong>anonymous</strong> function expression (the <code>name</code> is not used):</p> + +<pre class="brush: js">var myFunction = function() { + statements +}</pre> + +<p>It is also possible to provide a name inside the definition in order to create a <strong>named</strong> function expression:</p> + +<pre class="brush: js">var myFunction = function namedFunction(){ + statements +} +</pre> + +<p>One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.</p> + +<p>As we can see, both example do not start with the <code>function</code> keyword. Statements involving functions which do not start with <code>function</code> are function expressions.</p> + +<p>When function are used only once, a common pattern is an <strong>IIFE (<em>Immediately Invokable Function Expressions</em>)</strong>.</p> + +<pre class="brush: js">(function() { + statements +})();</pre> + +<p>IIFE are function expression that are invoked as soon as the function is declared.</p> + +<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> + +<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> + +<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> + +<p>A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):</p> + +<pre class="syntaxbox">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> + +<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> + +<pre class="syntaxbox">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> + <dt><code>statements or expression</code></dt> + <dd>Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.</dd> +</dl> + +<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>Function</code> constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.</p> +</div> + +<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function body.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.</p> +</div> + +<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Function_parameters">Function parameters</h2> + +<h3 id="Default_parameters">Default parameters</h3> + +<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> + +<h3 id="Rest_parameters">Rest parameters</h3> + +<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> + +<h2 id="The_arguments_object">The <code>arguments</code> object</h2> + +<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> + +<ul> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> +</ul> + +<h2 id="Defining_method_functions">Defining method functions</h2> + +<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> + +<p>You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>Binds an object property to a function that will be called when that property is looked up.</p> + </dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> +</dl> + +<h3 id="Method_definition_syntax">Method definition syntax</h3> + +<p>Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="Function_constructor_vs._function_declaration_vs._function_expression"><code>Function</code> constructor vs. function declaration vs. function expression</h2> + +<p>Compare the following:</p> + +<p>A function defined with the <code>Function</code> constructor assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = new Function('x', 'y', 'return x * y');</pre> + +<p>A <em>function declaration</em> of a function named <code>multiply</code>:</p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} // there is no semicolon here +</pre> + +<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="Differences">Differences</h3> + +<p>All do approximately the same thing, with a few subtle differences:</p> + +<p>There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // throws an error +</pre> + +<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> + +<p>On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.</p> + +<p>As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:</p> + +<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> + +<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> + +<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> + +<pre class="brush: js">var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); +foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.</pre> + +<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> + +<ul> + <li>becomes part of an expression</li> + <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> +</ul> + +<pre class="brush: js">var x = 0; // source element +if (x == 0) { // source element + x = 10; // not a source element + function boo() {} // not a source element +} +function foo() { // source element + var y = 20; // source element + function bar() {} // source element + while (y == 10) { // source element + function blah() {} // not a source element + y++; // not a source element + } +} +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// function declaration +function foo() {} + +// function expression +(function bar() {}) + +// function expression +x = function hello() {} + + +if (x) { + // function expression + function world() {} +} + + +// function declaration +function a() { + // function declaration + function b() {} + if (0) { + // function expression + function c() {} + } +} +</pre> + +<h2 id="Block-level_functions">Block-level functions</h2> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// f() === 2 in non-strict mode +</pre> + +<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> + +<p>In a word: Don't.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // DANGER: compatibility risk + console.log("This is zero."); + } +} +</pre> + +<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define <code>zero</code> whether the block executed or not.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> + +<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> + +<pre class="brush: js">var zero; +if (0) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="Examples_2">Examples</h2> + +<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> + +<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> + +<pre class="brush: js">// This function returns a string padded with leading zeros +function padZeros(num, totalLen) { + var numStr = num.toString(); // Initialize return value as string + var numZeros = totalLen - numStr.length; // Calculate no. of zeros + for (var i = 1; i <= numZeros; i++) { + numStr = "0" + numStr; + } + return numStr; +} +</pre> + +<p>The following statements call the padZeros function.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // returns "0042" +result = padZeros(42,2); // returns "42" +result = padZeros(5,4); // returns "0005" +</pre> + +<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> + +<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is performed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> + +<pre class="brush: js"> if ('function' == typeof window.noFunc) { + // use noFunc() + } else { + // do something else + } +</pre> + +<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Generator functions</td> + <td>39</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>26</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Arrow functions</td> + <td>{{CompatChrome(45.0)}}</td> + <td>{{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(32)}}</td> + <td>10</td> + </tr> + <tr> + <td>Block-level functions</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("46.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Generator functions</td> + <td>{{CompatUnknown}}</td> + <td>39</td> + <td>{{CompatGeckoMobile("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>26</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Arrow functions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Block-level functions</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("46.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> + <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/concat/index.html b/files/vi/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..f19a1b981b --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,150 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>concat()</strong></code> dùng để kết nối 2 hay nhiều mảng với nhau. Phương thức này không làm thay đổi các mảng đã có mà thay vào đó sẽ trả về 1 mảng mới.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-concat.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">var <var>newArray</var> = <var>oldArray</var>.concat(<var>value1</var>[, <var>value2</var>[, ...[, <var>valueN</var>]]])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>value<em>N</em></code></dt> + <dd>Các giá trị hay mảng dùng để nối lại với nhau trong mảng mới .</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một mảng {{jsxref("Array")}} mới.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức <code>concat</code> tạo ra 1 mảng mới bao gồm các phần tử trong đối tượng mà nó được gọi thực thi, và theo thứ tự lần lượt, với mỗi tham số truyền vào là các phần tử của tham số đó (nếu tham số truyền vào là 1 mảng) hoặc là chính tham số đó (nếu tham số truyền vào không phải là 1 mảng). Phương thức này sẽ không thực thi 1 cách đệ quy cho các tham số là mảng lồng nhau.</p> + +<p>Phương thức <code>concat</code> không thay đổi <code>this</code> (mảng được gọi thực thi) hay bất cứ mảng được truyền vào làm tham số mà thay vào đó nó sẽ trả về 1 bản sao tham chiếu (shallow copy) bao gồm các bản sao của cùng 1 phần tử được kết hợp từ các mảng ban đầu. Các phần từ của mảng ban đầu được sao chép vào mảng mới như sau: </p> + +<ul> + <li>Đối với tham chiếu đối tượng (và không phải đối tượng thực tế): <code>concat</code> sao chép tham chiếu đối tượng vào mảng mới. Cả mảng ban đầu và mảng mới đều tham chiếu tới cùng 1 đối tượng. Nghĩa là nếu đối tượng được tham chiếu tới bị thay đổi thì việc thay đổi đó sẽ ảnh hưởng trong cả mảng ban đầu và mảng mới. Điều này bao gồm các phần tử của các mảng làm tham số cũng đều là mảng. </li> + <li>Đối với dữ liệu kiểu chuỗi(strings), số(numbers), và booleans (không phải là các đối tượng kiểu {{jsxref("Global_Objects/String", "String")}}, {{jsxref("Global_Objects/Number", "Number")}}, và {{jsxref("Global_Objects/Boolean", "Boolean")}}): <code>concat</code> sẽ sao chép giá trị của chuỗi, số vào mảng mới.</li> +</ul> + +<div class="note"> +<p><strong>Chú ý:</strong> Việc ghép nối các mảng hay giá trị sẽ không "đụng chạm" tới các giá trị ban đầu. Hơn nữa, bất cứ thao tác nào trên mảng trả về (ngoại trừ các thao tác trên các phần từ là tham chiếu đối tượng) sẽ không ảnh hưởng tới các mảng ban đầu, và ngược lại.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Nối_2_mảng">Nối 2 mảng</h3> + +<p>Đoạn mã dưới đây sẽ nối 2 mảng lại với nhau:</p> + +<pre class="brush: js">var alpha = ['a', 'b', 'c']; +var numeric = [1, 2, 3]; + +alpha.concat(numeric); +// result in ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Nối_3_mảng">Nối 3 mảng</h3> + +<p>Đoạn mã dưới đây sẽ nối 3 mảng lại với nhau</p> + +<pre class="brush: js">var num1 = [1, 2, 3], + num2 = [4, 5, 6], + num3 = [7, 8, 9]; + +var nums = num1.concat(num2, num3); + +console.log(nums); +// results in [1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h3 id="Nối_các_giá_trị_vào_1_mảng">Nối các giá trị vào 1 mảng</h3> + +<p>Đoạn mã sau đây sẽ nối 3 giá trị vào 1 mảng:</p> + +<pre class="brush: js">var alpha = ['a', 'b', 'c']; + +var alphaNumeric = alpha.concat(1, [2, 3]); + +console.log(alphaNumeric); +// results in ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Nối_mảng_lồng_nhau">Nối mảng lồng nhau</h3> + +<p>Đoạn mã sau đây sẽ nối các mảng lồng nhau và thể hiện sự lưu trữ tham chiếu:</p> + +<pre class="brush: js">var num1 = [[1]]; +var num2 = [2, [3]]; + +var nums = num1.concat(num2); + +console.log(nums); +// results in [[1], 2, [3]] + +// modify the first element of num1 +num1[0].push(4); + +console.log(nums); +// results in [[1, 4], 2, [3]] +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Định nghĩa lần đầu. Hiện thực trong JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.concat")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — thêm/xóa phần tử từ cuối mảng</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — thêm/xóa các phần tử từ đầu mảng</li> + <li>{{jsxref("Array.splice", "splice")}} — thêm/xóa các phần tử tại vị trí xác định trong mảng</li> + <li>{{jsxref("String.prototype.concat()")}}</li> + <li>{{jsxref("Symbol.isConcatSpreadable")}} – control flattening.</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html b/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..fd216cbc54 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,170 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +<div>{{JSRef}}</div> + +<p> <code><strong>copyWithin() </strong></code> là một phương thức sao chép cạn một phần của mảng tới một vị trí khác trong mảng đó và trả về giá trị mà không thay đổi độ dài của mảng</p> + +<div>{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.copyWithin(<var>target[, start[, end]]</var>) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">target</span></font></dt> + <dd>Zero-based index at which to copy the sequence to. If negative, <code>target</code> will be counted from the end.</dd> + <dd>If <code>target</code> is at or greater than <code>arr.length</code>, nothing will be copied. If <code>target</code> is positioned after <code>start</code>, the copied sequence will be trimmed to fit <code>arr.length</code>.</dd> + <dt><code>start</code> {{optional_inline}}</dt> + <dd>Zero-based index at which to start copying elements from. If negative, <code>start</code> will be counted from the end.</dd> + <dd>If <code>start</code> is omitted, <code>copyWithin</code> will copy from index <code>0</code>. </dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>Zero-based index at which to end copying elements from. <code>copyWithin</code> copies up to but not including <code>end</code>. If negative, <code>end</code> will be counted from the end.</dd> + <dd>If <code>end</code> is omitted, <code>copyWithin</code> will copy until the last index (default to <code>arr.length</code>).</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>The modified array.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>copyWithin</code> works like C and C++'s <code>memmove</code>, and is a high-performance method to shift the data of an {{jsxref("Array")}}. This especially applies to the {{jsxref("TypedArray/copyWithin", "TypedArray")}} method of the same name. The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap.</p> + +<p>The <code>copyWithin</code> function is intentionally <em>generic</em>, it does not require that its <code>this</code> value be an {{jsxref("Array")}} object.</p> + +<p>The <code>copyWithin</code> method is a mutable method. It does not alter the length of <code>this</code>, but it will change its content and create new properties, if necessary.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js notranslate">if (!Array.prototype.copyWithin) { + Object.defineProperty(Array.prototype, 'copyWithin', { + value: function(target, start/*, end*/) { + // Steps 1-2. + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + var O = Object(this); + + // Steps 3-5. + var len = O.length >>> 0; + + // Steps 6-8. + var relativeTarget = target >> 0; + + var to = relativeTarget < 0 ? + Math.max(len + relativeTarget, 0) : + Math.min(relativeTarget, len); + + // Steps 9-11. + var relativeStart = start >> 0; + + var from = relativeStart < 0 ? + Math.max(len + relativeStart, 0) : + Math.min(relativeStart, len); + + // Steps 12-14. + var end = arguments[2]; + var relativeEnd = end === undefined ? len : end >> 0; + + var final = relativeEnd < 0 ? + Math.max(len + relativeEnd, 0) : + Math.min(relativeEnd, len); + + // Step 15. + var count = Math.min(final - from, len - to); + + // Steps 16-17. + var direction = 1; + + if (from < to && to < (from + count)) { + direction = -1; + from += count - 1; + to += count - 1; + } + + // Step 18. + while (count > 0) { + if (from in O) { + O[to] = O[from]; + } else { + delete O[to]; + } + + from += direction; + to += direction; + count--; + } + + // Step 19. + return O; + }, + configurable: true, + writable: true + }); +}</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_copyWithin">Using copyWithin</h3> + +<pre class="brush: js notranslate">[1, 2, 3, 4, 5].copyWithin(-2) +// [1, 2, 3, 1, 2] + +[1, 2, 3, 4, 5].copyWithin(0, 3) +// [4, 5, 3, 4, 5] + +[1, 2, 3, 4, 5].copyWithin(0, 3, 4) +// [4, 2, 3, 4, 5] + +[1, 2, 3, 4, 5].copyWithin(-2, -3, -1) +// [1, 2, 3, 3, 4] + +[].copyWithin.call({length: 5, 3: 1}, 0, 3) +// {0: 1, 3: 1, length: 5} + +// ES2015 Typed Arrays are subclasses of Array +var i32a = new Int32Array([1, 2, 3, 4, 5]) + +i32a.copyWithin(0, 2) +// Int32Array [3, 4, 5, 4, 5] + +// On platforms that are not yet ES2015 compliant: +[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); +// Int32Array [4, 2, 3, 4, 5] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.copyWithin")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/entries/index.html b/files/vi/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..6be2131071 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,82 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>entries()</code></strong> trả về một mảng đối tượng <strong>Array Iterator</strong> chứa cặp key/value cho mỗi chỉ mục trong mảng.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-entries.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><var>array</var>.entries()</pre> + +<h3 id="Return_value">Return value</h3> + +<p>Một {{jsxref("Array")}} đối tượng iterator.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Iterating_with_index_and_element">Iterating with index and element</h3> + +<pre class="brush:js notranslate">const a = ['a', 'b', 'c']; + +for (const [index, element] of a.entries()) + console.log(index, element); + +// 0 'a' +// 1 'b' +// 2 'c' +</pre> + +<h3 id="Using_a_for…of_loop">Using a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for…of</a> loop</h3> + +<pre class="brush:js notranslate">var a = ['a', 'b', 'c']; +var iterator = a.entries(); + +for (let e of iterator) { + console.log(e); +} +// [0, 'a'] +// [1, 'b'] +// [2, 'c'] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.entries")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.values()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/every/index.html b/files/vi/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..efeaa2deca --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,236 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong>every()</strong> sẽ kiểm tra xem mọi phần tử bên trong một array được truyền vào có vượt qua được bài kiểm tra khi thực hiện với function được cung cấp không. every() sẽ return về một kết quả Boolean.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-every.html","shorter")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.every(<var>callback</var>(<var>element</var>[, <var>index</var>[, <var>array</var>]])[, <var>thisArg</var>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><var>callback</var></code></dt> + <dd>Một function với chức năng là kiểm tra từng phần tử trong mảng được cung cấp cho every(), nhận vào 3 đối số: + <dl> + <dt><code><var>element</var></code></dt> + <dd>Là phần tử hiện tại của mảng đang được function xử lý.</dd> + <dt><code><var>index</var></code> {{Optional_inline}}</dt> + <dd>Index của phần tử trên.</dd> + <dt><code><var>array</var></code> {{Optional_inline}}</dt> + <dd>Mảng mà every() gọi.</dd> + </dl> + </dd> + <dt><code><var>thisArg</var></code> {{Optional_inline}}</dt> + <dd>A value to use as <code>this</code> when executing <code><var>callback</var></code>.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><code><strong>true</strong></code> if the <code><var>callback</var></code> function returns a <a href="/en-US/docs/Glossary/truthy">truthy</a> value for every array element. Otherwise, <code><strong>false</strong></code>.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>every</code> method executes the provided <code><var>callback</var></code> function once for each element present in the array until it finds the one where <code><var>callback</var></code> returns a <a href="/en-US/docs/Glossary/falsy">falsy</a> value. If such an element is found, the <code>every</code> method immediately returns <code>false</code>. Otherwise, if <code><var>callback</var></code> returns a <a href="/en-US/docs/Glossary/truthy">truthy</a> value for all elements, <code>every</code> returns <code>true</code>.</p> + +<div class="blockIndicator note"> +<p><strong>Caution</strong>: Calling this method on an empty array will return <code>true</code> for any condition!</p> +</div> + +<p><code><var>callback</var></code> is invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values.</p> + +<p><code><var>callback</var></code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p> + +<p>If a <code><var>thisArg</var></code> parameter is provided to <code>every</code>, it will be used as callback's <code>this</code> value. Otherwise, the value <code>undefined</code> will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code><var>callback</var></code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p><code>every</code> does not mutate the array on which it is called.</p> + +<p>The range of elements processed by <code>every</code> is set before the first invocation of <code><var>callback</var></code>. Therefore, <code><var>callback</var></code> will not run on elements that are appended to the array after the call to <code>every</code> begins. If existing elements of the array are changed, their value as passed to <code><var>callback</var></code> will be the value at the time <code>every</code> visits them. Elements that are deleted are not visited.</p> + +<p><code>every</code> acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns <code>true</code>. (It is <a href="http://en.wikipedia.org/wiki/Vacuous_truth">vacuously true</a> that all elements of the <a href="https://en.wikipedia.org/wiki/Empty_set#Properties">empty set</a> satisfy any given condition.)</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>every</code> was added to the ECMA-262 standard in the 5<sup>th</sup> edition, and it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>every</code> in implementations which do not natively support it.</p> + +<p>This algorithm is exactly the one specified in ECMA-262, 5<sup>th</sup> edition, assuming <code>Object</code> and <code>TypeError</code> have their original values, and that <code><var>callbackfn</var>.call</code> evaluates to the original value of {{jsxref("Function.prototype.call")}}.</p> + +<pre class="brush: js notranslate">if (!Array.prototype.every) { + Array.prototype.every = function(callbackfn, thisArg) { + 'use strict'; + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the this + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal method + // of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. + if (typeof callbackfn !== 'function' && Object.prototype.toString.call(callbackfn) !== '[object Function]') { + throw new TypeError(); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat, while k < len + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + var testResult; + // i. Let kValue be the result of calling the Get internal method + // of O with argument Pk. + kValue = O[k]; + + // ii. Let testResult be the result of calling the Call internal method + // of callbackfn with T as the this value if T is not undefined + // else is the result of calling callbackfn + // and argument list containing kValue, k, and O. + if(T) testResult = callbackfn.call(T, kValue, k, O); + else testResult = callbackfn(kValue,k,O) + + // iii. If ToBoolean(testResult) is false, return false. + if (!testResult) { + return false; + } + } + k++; + } + return true; + }; +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Testing_size_of_all_array_elements">Testing size of all array elements</h3> + +<p>The following example tests whether all elements in the array are bigger than 10.</p> + +<pre class="brush: js notranslate">function isBigEnough(element, index, array) { + return element >= 10; +} +[12, 5, 8, 130, 44].every(isBigEnough); // false +[12, 54, 18, 130, 44].every(isBigEnough); // true +</pre> + +<h3 id="Using_arrow_functions">Using arrow functions</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> provide a shorter syntax for the same test.</p> + +<pre class="brush: js notranslate">[12, 5, 8, 130, 44].every(x => x >= 10); // false +[12, 54, 18, 130, 44].every(x => x >= 10); // true</pre> + +<h3 id="Affecting_Initial_Array_modifying_appending_and_deleting">Affecting Initial Array (modifying, appending, and deleting)</h3> + +<p>The following examples tests the behaviour of the <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">every</span></font> method when the array is modified.</p> + +<pre class="brush: js notranslate">// --------------- +// Modifying items +// --------------- +let arr = [1, 2, 3, 4]; +arr.every( (elem, index, arr) => { + arr[index+1] -= 1 + console.log(`[${arr}][${index}] -> ${elem}`) + return elem < 2 +}) + +// Loop runs for 3 iterations, but would +// have run 2 iterations without any modification +// +// 1st iteration: [1,1,3,4][0] -> 1 +// 2nd iteration: [1,1,2,4][1] -> 1 +// 3rd iteration: [1,1,2,3][2] -> 2 + +// --------------- +// Appending items +// --------------- +arr = [1, 2, 3]; +arr.every( (elem, index, arr) => { + arr.push('new') + console.log(`[${arr}][${index}] -> ${elem}`) + return elem < 4 +}) + +// Loop runs for 3 iterations, even after appending new items +// +// 1st iteration: [1, 2, 3, new][0] -> 1 +// 2nd iteration: [1, 2, 3, new, new][1] -> 2 +// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3 + +// --------------- +// Deleting items +// --------------- +arr = [1, 2, 3, 4]; +arr.every( (elem, index, arr) => { + arr.pop() + console.log(`[${arr}][${index}] -> ${elem}`) + return elem < 4 +}) + +// Loop runs for 2 iterations only, as the remaining +// items are `pop()`ed off +// +// 1st iteration: [1,2,3][0] -> 1 +// 2nd iteration: [1,2][1] -> 2</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.every")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("TypedArray.prototype.every()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/fill/index.html b/files/vi/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..e7e8201c46 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,149 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>fill()</strong></code> điền (sửa đổi) tất cả các phần tử của một mảng từ một chỉ mục bắt đầu (số không mặc định) đến một chỉ mục kết thúc (độ dài mảng mặc định) với một giá trị tĩnh. Nó trả về mảng đã sửa đổi</p> + +<div>{{EmbedInteractiveExample("pages/js/array-fill.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.fill(<var>value[</var>, <var>start[<var>, <var>end]]</var>)</var></var> +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Value to fill an array.</dd> + <dt><code>start</code> {{optional_inline}}</dt> + <dd>Start index, defaults to 0.</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>End index, defaults to <code>this.length</code>.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>The modified array.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>fill</code> method takes up to three arguments <code>value</code>, <code>start</code> and <code>end</code>. The <code>start</code> and <code>end</code> arguments are optional with default values of <code>0</code> and the <code>length</code> of the <code>this</code> object.</p> + +<p>If <code>start</code> is negative, it is treated as <code>length+start</code> where <code>length</code> is the length of the array. If <code>end</code> is negative, it is treated as <code>length+end</code>.</p> + +<p><code>fill</code> is intentionally generic, it does not require that its <code>this</code> value be an Array object.</p> + +<p><code>fill</code> is a mutable method, it will change <code>this</code> object itself, and return it, not just return a copy of it.</p> + +<p>When <code>fill</code> gets passed an object, it will copy the reference and fill the array with references to that object.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">[1, 2, 3].fill(4); // [4, 4, 4] +[1, 2, 3].fill(4, 1); // [1, 4, 4] +[1, 2, 3].fill(4, 1, 2); // [1, 4, 3] +[1, 2, 3].fill(4, 1, 1); // [1, 2, 3] +[1, 2, 3].fill(4, 3, 3); // [1, 2, 3] +[1, 2, 3].fill(4, -3, -2); // [4, 2, 3] +[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] +[1, 2, 3].fill(4, 3, 5); // [1, 2, 3] +Array(3).fill(4); // [4, 4, 4] +[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3} + +// Objects by reference. +var arr = Array(3).fill({}) // [{}, {}, {}]; +arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (!Array.prototype.fill) { + Object.defineProperty(Array.prototype, 'fill', { + value: function(value) { + + // Steps 1-2. + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + var O = Object(this); + + // Steps 3-5. + var len = O.length >>> 0; + + // Steps 6-7. + var start = arguments[1]; + var relativeStart = start >> 0; + + // Step 8. + var k = relativeStart < 0 ? + Math.max(len + relativeStart, 0) : + Math.min(relativeStart, len); + + // Steps 9-10. + var end = arguments[2]; + var relativeEnd = end === undefined ? + len : end >> 0; + + // Step 11. + var final = relativeEnd < 0 ? + Math.max(len + relativeEnd, 0) : + Math.min(relativeEnd, len); + + // Step 12. + while (k < final) { + O[k] = value; + k++; + } + + // Step 13. + return O; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.fill")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("TypedArray.prototype.fill()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/filter/index.html b/files/vi/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..900c22a1ac --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,232 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>filter()</strong></code> dùng để tạo một mảng mới với tất cả các phần tử thỏa điều kiện của một hàm test.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-filter.html")}}</div> + +<p class="hidden">Mã nguồn của ví dụ tương tác này được lưu tại GitHub. Nếu bạn muốn đóng góp cho các ví dụ tương tác này, hãy clone repo <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi pull request cho chúng tôi.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>var newArray = arr</var>.filter(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Đây là hàm thử, dùng để kiểm tra từng phần tử của mảng. Trả về <code>true</code> để giữ lại phần tử, hoặc <code>false</code> để loại nó ra. Nó được gọi với ba tham số:</dd> + <dd> + <dl> + <dt><code>element</code></dt> + <dd>Phần tử đang được xử lý trong mảng.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>Chỉ mục (index) của phần tử đang được xử lý.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>Mảng nguồn mà hàm <code>filter</code> đang xử lý.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd>Không bắt buộc. Giá trị của <code>this</code> bên trong hàm <code>callback</code>.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một mảng mới với các phần tử đã thỏa điều kiện của hàm test. Nếu không có phần tử nào thỏa điều kiện, một mảng rỗng sẽ được trả về.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>filter()</code> sẽ thực thi hàm <code>callback</code> trên từng phần tử của mảng, và xây dựng một mảng mới với các phần tử mà giá trị trả về của <code>callback</code> <a href="/en-US/docs/Glossary/Truthy">nếu ép kiểu sẽ mang giá trị <code>true</code></a>. <code>callback</code> chỉ được thực thi tại những chỉ mục (index) của mảng mà chúng được gán giá trị; nó không được thực thi tại chỉ mục đã bị xóa hoặc chưa từng được gán giá trị. Những phần tử không thỏa điều kiện tại hàm thử <code>callback</code> sẽ bị bỏ qua, không được cho vào mảng mới.</p> + +<p><code>callback</code> được gọi với ba tham số:</p> + +<ol> + <li>giá trị của phần tử</li> + <li>chỉ mục (index) của phần tử</li> + <li>mảng ban đầu mà hàm thử đang được gọi lên</li> +</ol> + +<p>Nếu tham số <code>thisArg</code> được truyền cho hàm <code>filter</code>, nó sẽ được thay vào giá trị của từ khóa <code>this</code> trong hàm callback. Nếu không, giá trị <code>undefined</code> sẽ được dùng cho <code>this</code>. Tóm lại, giá trị của từ khóa <code>this</code> trong hàm <code>callback</code> được xác định tuân theo <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">các quy tắc thông thường để xác định <code>this</code> trong một hàm</a>.</p> + +<p><code>filter()</code> không làm thay đổi mảng mà nó được gọi.</p> + +<p>Các phần tử được <code>filter()</code> chạy qua được xác định từ đầu trước khi <code>callback</code> được gọi lần đầu tiên. Những phần tử mới được thêm vào sau khi <code>filter()</code> bắt đầu chạy sẽ không được truyền vào <code>callback</code>. Trong lúc <code>filter()</code> đang chạy, nếu những phần tử hiện tại của mảng bị thay đổi, thì giá trị của chúng khi được truyền cho <code>callback</code> là giá trị tại thời điểm <code>filter()</code> chạy qua; những phần tử đã xóa sẽ bị bỏ qua.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Lọc_bỏ_các_giá_trị_nhỏ">Lọc bỏ các giá trị nhỏ</h3> + +<p>Ví dụ sau sẽ dùng <code>filter()</code> để tạo một mảng lọc không có các phần tử nào nhỏ hơn 10.</p> + +<pre class="brush: js">function isBigEnough(value) { + return value >= 10; +} + +var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); +// filtered is [12, 130, 44] +</pre> + +<h3 id="Lọc_các_giá_trị_không_hợp_lệ_khỏi_JSON">Lọc các giá trị không hợp lệ khỏi JSON</h3> + +<p>Ví dụ sau sẽ dùng hàm <code>filter()</code> để lọc lại các phần tử của JSON chỉ chứa <code>id</code> có giá trị số và khác 0.</p> + +<pre class="brush: js">var arr = [ + { id: 15 }, + { id: -1 }, + { id: 0 }, + { id: 3 }, + { id: 12.2 }, + { }, + { id: null }, + { id: NaN }, + { id: 'undefined' } +]; + +var invalidEntries = 0; + +function isNumber(obj) { + return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj); +} + +function filterByID(item) { + if (isNumber(item.id) && item.id !== 0) { + return true; + } + invalidEntries++; + return false; +} + +var arrByID = arr.filter(filterByID); + +console.log('Filtered Array\n', arrByID); +// Filtered Array +// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] + +console.log('Number of Invalid Entries = ', invalidEntries); +// Number of Invalid Entries = 5 +</pre> + +<h3 id="Tìm_kiếm_trong_mảng">Tìm kiếm trong mảng</h3> + +<p>Ví dụ sau dùng <code>filter()</code> để lọc ra phần tử có nội dung thỏa chuỗi tìm kiếm</p> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * Array filters items based on search criteria (query) + */ +function filterItems(query) { + return fruits.filter(function(el) { + return el.toLowerCase().indexOf(query.toLowerCase()) > -1; + }) +} + +console.log(filterItems('ap')); // ['apple', 'grapes'] +console.log(filterItems('an')); // ['banana', 'mango', 'orange']</pre> + +<h3 id="Ví_dụ_ở_trên_với_ES2015">Ví dụ ở trên với ES2015</h3> + +<pre class="brush: js">const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * Array filters items based on search criteria (query) + */ +const filterItems = (query) => { + return fruits.filter((el) => + el.toLowerCase().indexOf(query.toLowerCase()) > -1 + ); +} + +console.log(filterItems('ap')); // ['apple', 'grapes'] +console.log(filterItems('an')); // ['banana', 'mango', 'orange'] + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>filter()</code> chỉ được thêm vào đặc tả ECMA-262 phiên bản thứ 5; cho nên nó có thể không tồn tại trong một số hiện thực (implementation) của đặc tả. Bạn có thể xoay sở bằng cách thêm vào đoạn code bên dưới vào đầu script của bạn, cho phép sử dụng <code>filter()</code> tại những nơi mà nó không được hỗ trợ sẵn. Giải thuật trong hàm polyfill này chính xác với đặc tả trong ECMA-262, 5th edition, với yêu cầu <code>fn.call</code> trả về giá trị ban đầu của {{jsxref("Function.prototype.bind()")}}, và {{jsxref("Array.prototype.push()")}} không bị thay đổi.</p> + +<pre class="brush: js">if (!Array.prototype.filter){ + Array.prototype.filter = function(func, thisArg) { + 'use strict'; + if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) ) + throw new TypeError(); + + var len = this.length >>> 0, + res = new Array(len), // preallocate array + t = this, c = 0, i = -1; + if (thisArg === undefined){ + while (++i !== len){ + // checks to see if the key was set + if (i in this){ + if (func(t[i], i, t)){ + res[c++] = t[i]; + } + } + } + } + else{ + while (++i !== len){ + // checks to see if the key was set + if (i in this){ + if (func.call(thisArg, t[i], i, t)){ + res[c++] = t[i]; + } + } + } + } + + res.length = c; // shrink down array to proper size + return res; + }; +}</pre> + +<p> </p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.filter")}}</p> +</div> + +<h2 id="Tương_tự">Tương tự</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/find/index.html b/files/vi/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..ba4631a924 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,226 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>find() </strong></code>sẽ trả về <strong>giá trị đầu tiên tìm thấy</strong> ở trong mảng được cung cấp. Hoặc có thể trả về {{jsxref("undefined")}} .</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>Xem thêm phương thức {{jsxref("Array.findIndex", "findIndex()")}} , sẽ trả về <strong>index</strong> của phần tử tìm thấy trong mảng thay vì giá trị của nó.</p> + +<p>Nếu bạn muốn tìm vị trí của phần tử hoặc tìm phần tử đó có tồn tại trong mảng hay không, hãy thử sử dụng {{jsxref("Array.prototype.indexOf()")}} or {{jsxref("Array.prototype.includes()")}}.</p> + +<h2 id="Cú_Pháp">Cú Pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.find(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parameters_(_thông_số_đầu_vào_)">Parameters ( thông số đầu vào )</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm thực thi với mỗi giá trị trong mảng, chuyền vào 3 giá trị : + <dl> + <dt><code>element</code></dt> + <dd>Phần tử hiện tại đang được xử lý trong mảng.</dd> + <dt><code>index</code> {{optional_inline}}</dt> + <dd>Thứ tự của phần tử hiện tại đang được xử lý trong mảng..</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd>Mảng được gọi.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd>Đối tượng tùy chọn để sử dụng như thế này khi thực hiện <code>callback</code>.</dd> +</dl> + +<h3 id="Return_value_(_giá_trị_trả_về_)">Return value ( giá trị trả về )</h3> + +<p><strong>Giá trị ( value )</strong> của<strong> phần tử đầu tiên ( first element )</strong> trong mảng thỏa mãn chức năng kiểm tra được cung cấp. Nếu không, sẽ trả về {{jsxref("undefined")}}.</p> + +<h2 id="Mô_Tả">Mô Tả</h2> + +<p>Phương thức <code>find thực thi hàm</code> <code>callback</code> với mỗi giá trị trong mảng cho đến khi tìm được giá trị mà hàm <code>callback</code> trả về giá trị. Nếu phần tử đó được tìm thấy, phương thức <code>find sẽ</code> trả về giá trị của phần tử đó. Nếu không tìm thấy, <code>find</code> sẽ trả về {{jsxref("undefined")}}. <code>callback</code> được gọi cho mọi <code>index</code> có trong mảng từ <code>0</code> đến<code>length - 1</code> và cho tất cả các <code>indexes</code>, không chỉ những giá trị đã được gán. Điều này chỉ ra rằng nó có thể kém hiệu quả hơn so với các phương thức khác chỉ truy cập các <code>indexes</code> có giá trị được gán.</p> + +<p><code>callback</code> được gọi với ba <strong>arguments</strong>: giá trị của phần tử ( the value of the element ), biến đếm của phần tử ( the index of the element ) và đối tượng mảng cần tìm ( the Array object being traversed ).</p> + +<p>Nếu <code>thisArg</code> tham số ( <strong>parameter </strong>) cung cấp cho phương thức <code>find</code>, nó sẽ được sử dụng như là giá trị <code>this</code> cho mỗi lần gọi <code>callback</code>. Nếu không được cung cấp tham số, thì {{jsxref("undefined")}} sẽ được thay thế.</p> + +<p>Phương thức <code>find</code> sẽ không làm thay đổi mảng mà nó được gọi hoặc sử dụng.</p> + +<p>Phạm vi của các phần tử được xử lý bởi <code>find</code> sẽ được gán trước ghi gọi hàm <code>callback</code>. Vì thế, <code>callback</code> sẽ không truy cập các phần tử được gắn vào mảng sau khi phương thức <code>find được</code> bắt đầu. Các phần tử bị xóa vẫn có thể truy cập được.</p> + +<h2 id="Ví_Dụ">Ví Dụ</h2> + +<h3 id="Tìm_một_đối_tượng_trong_một_mảng_bằng_một_trong_các_thuộc_tính">Tìm một đối tượng trong một mảng bằng một trong các thuộc tính</h3> + +<pre class="brush: js">const inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +function isCherries(fruit) { + return fruit.name === 'cherries'; +} + +console.log(inventory.find(isCherries)); +// { name: 'cherries', quantity: 5 }</pre> + +<h4 id="Sử_dụng_arrow_function_(_ES2015_)">Sử dụng arrow function ( ES2015 )</h4> + +<pre class="brush: js">const inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +const result = inventory.find( fruit => fruit.name === 'cherries' ); + +console.log(result) // { name: 'cherries', quantity: 5 }</pre> + +<h3 id="Tìm_số_nguyên_tố_trong_mảng">Tìm số nguyên tố trong mảng</h3> + +<p>Theo ví dụ sau đây tìm thấy một phần tử trong mảng là số nguyên tố (hoặc sẽ trả về {{jsxref("undefined")}} nếu trong mảng không có số nguyên tố nào).</p> + +<pre class="brush: js">function isPrime(element, index, array) { + let start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found +console.log([4, 5, 8, 12].find(isPrime)); // 5 +</pre> + +<p>Ví dụ sau đây cho thấy các phần tử không tồn tại và bị xóa vẫn được truy cập và giá trị được chuyển cho <code>callback </code>lại là giá trị của chúng khi được truy cập.</p> + +<pre class="brush: js">// Declare array with no element at index 2, 3 and 4 +const array = [0,1,,,,5,6]; + +// Shows all indexes, not just those that have been assigned values +array.find(function(value, index) { + console.log('Visited index ' + index + ' with value ' + value); +}); + +// Shows all indexes, including deleted +array.find(function(value, index) { + + // Delete element 5 on first iteration + if (index == 0) { + console.log('Deleting array[5] with value ' + array[5]); + delete array[5]; + } + // Element 5 is still visited even though deleted + console.log('Visited index ' + index + ' with value ' + value); +}); +// expected output: +// Deleting array[5] with value 5 +// Visited index 0 with value 0 +// Visited index 1 with value 1 +// Visited index 2 with value undefined +// Visited index 3 with value undefined +// Visited index 4 with value undefined +// Visited index 5 with value undefined +// Visited index 6 with value 6 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Phương pháp này đã được thêm vào ECMAScript 2015 và có thể không có sẵn trong tất cả các phiên bản JavaScript. Tuy nhiên, bạn có thể sử dụng <code>Array.prototype.find</code> với cú pháp :</p> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + }, + configurable: true, + writable: true + }); +} + +</pre> + +<h2 id="Đặc_Điểm">Đặc Điểm</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_Tương_Thích_Với_Trình_Duyệt_Web">Tính Tương Thích Với Trình Duyệt Web</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.find")}}</p> +</div> + +<h2 id="Những_Phương_Thức_Liên_Quan">Những Phương Thức Liên Quan</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – find and return an index</li> + <li>{{jsxref("Array.prototype.includes()")}} – test whether a value exists in the array</li> + <li>{{jsxref("Array.prototype.filter()")}} – find all matching elements</li> + <li>{{jsxref("Array.prototype.every()")}} – test all elements together</li> + <li>{{jsxref("Array.prototype.some()")}} – test at least one element</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/findindex/index.html b/files/vi/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..3c8d822f07 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,207 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>findIndex()</strong></code> trả về <strong>chỉ số (index)</strong> của phần tử đầu tiên trong mảng thỏa mãn hàm truyền vào. Nếu không phần tử nào thỏa mãn, phương thức trả lại -1.</p> + +<pre class="brush: js">function isBigEnough(element) { + return element >= 15; +} + +[12, 5, 8, 130, 44].findIndex(isBigEnough); // Trả về 3, phần tử thứ 4.</pre> + +<p>Xem thêm phương thức {{jsxref("Array.find", "find()")}}, trả về <strong>giá trị (value)</strong> của phần tử được tìm thấy thay vì chỉ số.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.findIndex(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm kiểm tra, được thực thi cho mỗi phần tử của mảng, có thể chứa 3 tham số: + <dl> + <dt><code>element</code></dt> + <dd>Phần tử đang xét.</dd> + <dt><code>index</code></dt> + <dd>Chỉ số của phần tử đang xét.</dd> + <dt><code>array</code></dt> + <dd>Mảng được gọi.</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd>Optional. Object to use as <code>this</code> when executing <code>callback</code>.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chỉ số của mảng nếu tìm được phần tử đầu tiên thỏa mãn hàm kiểm tra; otherwise, <strong>-1</strong>.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức <code>findIndex</code> thực thi hàm <code>callback</code> từng lần cho toàn bộ chỉ số mảng từ <code>0..length-1</code> (bao gồm hai nút) trong mảng cho tới khi tìm thấy chỉ số mà phần tử tại đó làm cho <code>callback</code> trả về một giá trị đúng (a value that coerces to <code>true</code>). Nếu một phần tử được tìm thấy, <code>findIndex</code> lập tức trả về chỉ số của phần tử này. Nếu hàm callback luôn nhận giá trị không đúng hoặc số phần tử của mảng bằng 0, <code>findIndex</code> trả về -1. Không giống như cách phương thức về mảng khác như Array#some, trong mảng thưa thớt hàm <code>callback</code> được gọi là ngay cả đối với các chỉ mục của mục không có trong mảng đó.</p> + +<p><code>callback</code> được gọi với 3 đối số: giá trị của phần tử, chỉ số của phần tử, và mảng đang được xét.</p> + +<p>Nếu tham số <code>thisArg</code> được đưa vào <code>findIndex</code>, Nó sẽ được sử dụng như là <code>this</code> cho mỗi lần gọi <code>callback</code>. Nếu nó không được đưa vào, thì {{jsxref("undefined")}} sẽ được sử dụng.</p> + +<p><code>findIndex</code> không làm thay đổi mảng mà nó được gọi.</p> + +<p>The range of elements processed by <code>findIndex</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>findIndex</code> begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will be the value at the time that <code>findIndex</code> visits that element's index; elements that are deleted are not visited.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tìm_chỉ_số_của_một_số_nguyên_tố_trong_mảng">Tìm chỉ số của một số nguyên tố trong mảng</h3> + +<p>Ví dụ dưới đây tìm chỉ số của một phần tử trong mảng mà là số nguyên tố (trả về -1 nếu không tìm thấy).</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found +console.log([4, 6, 7, 12].findIndex(isPrime)); // 2 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex +if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return k. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return k; + } + // e. Increase k by 1. + k++; + } + + // 7. Return -1. + return -1; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="Các_thông_số">Các thông số</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Edge</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(45.0)}}</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>Yes</td> + <td>Yes</td> + <td>{{CompatSafari("7.1")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/flat/index.html b/files/vi/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..065a92a7a5 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,179 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - flat +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +<div>{{JSRef}}</div> + +<div>Phương thức <code><strong>flat()</strong></code> trả về một mảng mới. Trong đó, tất cả các phần tử của mảng con được gán ngược vào nó bằng cách đệ quy lên đến độ sâu đã chỉ định.</div> + + + +<p>{{EmbedInteractiveExample("pages/js/array-flat.html")}}</p> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><var>var newArray = arr</var>.flat(<em>[depth]</em>);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>depth</code> {{optional_inline}}</dt> + <dd>Chỉ định độ sâu của mảng kết quả cuối cùng. Mặc định là 1</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Một mảng mới với các phần tử của mảng con được nối với nó.</p> + +<h2 id="Alternatives">Alternatives</h2> + +<h3 id="reduce_and_concat">reduce and concat</h3> + +<pre class="brush: js notranslate">const arr = [1, 2, [3, 4]]; + +// Trả về mảng chỉ có 1 level +arr.flat(); + +// Nó ngang với việc sử dụng reduce +arr.reduce((acc, val) => acc.concat(val), []); +// [1, 2, 3, 4] + +// hoặc decomposition syntax +const flattened = arr => [].concat(...arr); +</pre> + +<h3 id="reduce_concat_isArray_recursivity">reduce + concat + isArray + recursivity</h3> + +<pre class="brush: js notranslate">const arr = [1, 2, [3, 4, [5, 6]]]; + +// ?Sử dụng reduce, concat và deep level +function flatDeep(arr, d = 1) { + return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) + : arr.slice(); +}; + +flatDeep(arr, Infinity); +// [1, 2, 3, 4, 5, 6] +</pre> + +<h3 id="Use_a_stack">Use a stack</h3> + +<pre class="brush: js notranslate">// Sử dụng stack để đệ quy không cần báo deep level + +function flatten(input) { + const stack = [...input]; + const res = []; + while(stack.length) { + // Lấy gía trị ra khỏi stack + const next = stack.pop(); + if(Array.isArray(next)) { + // Gán trở lại arry, không thay đổi giá trị của item đó + stack.push(...next); + } else { + res.push(next); + } + } + // Đảo ngược array để trả về đúng order ban đầu + return res.reverse(); +} + +const arr = [1, 2, [3, 4, [5, 6]]]; +flatten(arr); +// [1, 2, 3, 4, 5, 6] +</pre> + +<h3 id="Use_Generator_function">Use Generator function</h3> + +<pre class="brush: js notranslate">function* flatten(array, depth) { + if(depth === undefined) { + depth = 1; + } + for(const item of array) { + if(Array.isArray(item) && depth > 0) { + yield* flatten(item, depth - 1); + } else { + yield item; + } + } +} + +const arr = [1, 2, [3, 4, [5, 6]]]; +const flattened = [...flatten(arr, Infinity)]; +// [1, 2, 3, 4, 5, 6] +</pre> + +<div class="hidden"> +<p>Please do not add polyfills on this article. For reference, please check: <a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a></p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Flattening_nested_arrays">Flattening nested arrays</h3> + +<pre class="brush: js notranslate">const arr1 = [1, 2, [3, 4]]; +arr1.flat(); +// [1, 2, 3, 4] + +const arr2 = [1, 2, [3, 4, [5, 6]]]; +arr2.flat(); +// [1, 2, 3, 4, [5, 6]] + +const arr3 = [1, 2, [3, 4, [5, 6]]]; +arr3.flat(2); +// [1, 2, 3, 4, 5, 6] + +const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; +arr4.flat(Infinity); +// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +</pre> + +<h3 id="Flattening_and_array_holes">Flattening and array holes</h3> + +<p>The flat method removes empty slots in arrays:</p> + +<pre class="brush: js notranslate">const arr5 = [1, 2, , 4, 5]; +arr5.flat(); +// [1, 2, 4, 5] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.flat', 'Array.prototype.flat')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.flat")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.flatMap()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/foreach/index.html b/files/vi/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..6121f40a83 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,303 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>forEach()</strong></code> sẽ thực thi một hàm khi duyệt qua từng phần tử của mảng.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.forEach(function <var>callback(currentValue[, index[, array]]) { + //your iterator +}</var>[, <var>thisArg</var>]);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm sẽ thực thi lên từng phần tử của mảng được gọi, hàm này nhận 3 tham số: + <dl> + <dt><code>currentValue</code>{{optional_inline}}</dt> + <dd>Giá trị của phần tử đang được duyệt.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>Chỉ mục của phần tử đang được duyệt.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>Mảng mà hàm <code>forEach()</code> đang duyệt.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd> + <p>Giá trị được gán cho từ khóa <code><strong>this</strong></code> bên trong hàm <code>callback</code> khi được thực thi.</p> + </dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Mô_tả_chi_tiết">Mô tả chi tiết</h2> + +<p><code>forEach()</code> thực thi hàm <code>callback</code> trong lúc duyệt tới từng phần tử của mảng theo thứ tự tăng dần. Nó sẽ không được gọi cho vị trí index đã bị xóa hoặc không được khởi tạo (đối với mảng thưa - sparse arrays).</p> + +<p><code>callback</code> được gọi với <strong>3 tham số</strong>:</p> + +<ul> + <li><strong>giá trị của phần tử</strong></li> + <li><strong>index của phần tử</strong></li> + <li><strong>mảng đang được duyệt </strong></li> +</ul> + +<p>Nếu tham số <code>thisArg</code> được truyền vào cho <code>forEach()</code>, nó sẽ được dùng cho từ khóa <code>this</code> trong hàm callback. Nếu không, giá trị {{jsxref("undefined")}} sẽ được dùng cho từ khóa <code>this</code>. Tóm lại, giá trị của từ khóa <code>this</code> trong hàm <code>callback</code> được xác định tuân theo <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">các quy tắc thông thường để xác định <code>this</code> trong một hàm</a>.</p> + +<p>Khoảng các phần tử được xử lý bởi <code>forEach()</code> được thiết lập trước lần gọi đầu tiên của <code>callback</code>. Phần tử được thêm vào mảng sau khi gọi <code>forEach()</code> sẽ không được <code>callback</code> bắt gặp. Nếu giá trị của các phần tử sẵn có trong mảng thay đổi, thì giá trị truyền vào <code>callback</code> sẽ là giá trị lúc <code>forEach()</code> gặp chúng; phần tử bị xoá trước khi bắt gặp sẽ không tính. Nếu phần tử đã gặp rồi bị loại đi (ví dụ dùng {{jsxref("Array.prototype.shift()", "shift()")}}) trong quá trình lặp, các phần tử sau sẽ bị bỏ qua - xem ví dụ phía dưới.</p> + +<p><code>forEach()</code> executes the <code>callback</code> function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.</p> + +<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<div class="note"> +<p>Khác với cú pháp lặp truyền thống, không có cách nào để ngừng vòng lặp forEach ngoài việc ném ra một ngoại lệ. Nếu vì một mục đích nào đó mà bạn cần ngừng vòng lặp thì nên dùng cách khác thay vì dùng forEach</p> + +<p>Một số cách có thể dùng trong trường hợp đó:</p> + +<ul> + <li>Vòng lặp <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> đơn giản</li> + <li>Vòng lặp <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> </li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> + +<p>Một số hàm khác trên kiểu mảng: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Converting_a_for_loop_to_forEach">Converting a for loop to forEach</h3> + +<p>before</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +for (let i=0; i<items.length; i++) { + copy.push(items[i]) +} +</pre> + +<p>after</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +items.forEach(function(item){ + copy.push(item) +}); + +</pre> + +<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// Notice that index 2 is skipped since there is no item at +// that position in the array. +[2, 5, , 9].forEach(logArrayElements); +// logs: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="Using_thisArg">Using <code>thisArg</code></h3> + +<p>The following (contrived) example updates an object's properties from each entry in the array:</p> + +<pre class="brush:js">function Counter() { + this.sum = 0; + this.count = 0; +} +Counter.prototype.add = function(array) { + array.forEach(function(entry) { + this.sum += entry; + ++this.count; + }, this); + // ^---- Note +}; + +const obj = new Counter(); +obj.add([2, 5, 9]); +obj.count; +// 3 +obj.sum; +// 16 +</pre> + +<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p> + +<div class="note"> +<p>If passing the function argument using an <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p> +</div> + +<h3 id="An_object_copy_function">An object copy function</h3> + +<p>The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</p> + +<pre class="brush: js">function copy(obj) { + const copy = Object.create(Object.getPrototypeOf(obj)); + const propNames = Object.getOwnPropertyNames(obj); + + propNames.forEach(function(name) { + const desc = Object.getOwnPropertyDescriptor(obj, name); + Object.defineProperty(copy, name, desc); + }); + + return copy; +} + +const obj1 = { a: 1, b: 2 }; +const obj2 = copy(obj1); // obj2 looks like obj1 now +</pre> + +<h3 id="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3> + +<p>The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. <code>forEach()</code> does not make a copy of the array before iterating.</p> + +<pre class="brush:js">var words = ['one', 'two', 'three', 'four']; +words.forEach(function(word) { + console.log(word); + if (word === 'two') { + words.shift(); + } +}); +// one +// two +// four +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>forEach()</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback/*, thisArg*/) { + + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling toObject() passing the + // |this| value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get() internal + // method of O with the argument "length". + // 3. Let len be toUint32(lenValue). + var len = O.length >>> 0; + + // 4. If isCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let + // T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat while k < len. + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator. + // b. Let kPresent be the result of calling the HasProperty + // internal method of O with argument Pk. + // This step can be combined with c. + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined. + }; +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/from/index.html b/files/vi/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..cee1cc84f7 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,228 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Phương Thức + - Tham khảo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>Array.from()</strong></code> tạo ra một thực thể <code>Array</code> mới được sao chép cạn (shallow-copied) từ các đối tượng giống mảng hoặc các đối tượng khả duyệt.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-from.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre>Array.from(arrayLike[, mapFn[, thisArg]]) +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>arrayLike</code></dt> + <dd>Đối tượng có tính chất giống mảng hoặc khả duyệt</dd> + <dt><code>mapFn</code>{{Optional_inline}}</dt> + <dd>Hàm Map được gọi khi thực thi trên từng phần tử.</dd> + <dt><code>thisArg</code>{{Optional_inline}}</dt> + <dd>Giá trị được sử dụng như <code>this</code>, thường là tham chiếu đến phạm vi của đối tượng gọi hàm <code>mapFn</code>.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một thực thể {{jsxref("Array")}} mới.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>Array.from()</code> cho phép tạo <code>Array</code> từ:</p> + +<ul> + <li>Các đối tượng giống mảng (một đối tượng giống mảng sẽ có thuộc tính mô tả chiều dài <code>length</code> và các phần tử được đánh chỉ mục) </li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable objects</a> - đối tượng khả duyệt (là các đối tượng mà các phần tử của nó có thể được duyệt ví dụ như {{jsxref("Map")}} và {{jsxref("Set")}}).</li> +</ul> + +<p><code>Array.from()</code> còn cung cấp thêm một tham số tuỳ chọn là <code>mapFn</code>, vốn là một hàm được tự động thực thi khi duyệt qua từng phần tử của {{jsxref("Array.prototype.map", "map")}}. Điểm khác biệt quan trọng của<code> Array.from(obj, mapFn, thisArg)</code> so với <code>Array.from(obj).map(mapFn, thisArg)</code> là nó không tạo ra mảng trung gian. Đây là điểm quan trọng cho các mảng kế thừa như <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed arrays</a> vì mảng trung gian nhất thiết sẽ có các giá trị được cắt ngắn để vừa với loại thích hợp.</p> + +<p>Thuộc tính <code>length</code> của phương thức <code>from()</code> là 1.</p> + +<p>Với ES2015 thì cú pháp class cho phép kế thừa từ cả các lớp có sẵn hoặc do người dùng định nghĩa, tất nhiên kể cả các phương thức tĩnh như <code>Array.from</code> cũng được kế thừa trong subclass, và kết quả trả về của <code>from</code> trong subclass là thực thể của subclass, không phải <code>Array</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tạo_mảng_từ_chuỗi">Tạo mảng từ chuỗi</h3> + +<pre class="brush: js">Array.from('foo'); +// ["f", "o", "o"]</pre> + +<h3 id="Tạo_mảng_từ_tập_hợp_Set">Tạo mảng từ tập hợp <code>Set</code></h3> + +<pre class="brush: js">var s = new Set(['foo', window]); +Array.from(s); +// ["foo", window]</pre> + +<h3 id="Tạo_mảng_từ_một_Map"><code><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="background-color: #333333;">Tạo mảng từ một </span></font>Map</code></h3> + +<pre class="brush: js">var m = new Map([[1, 2], [2, 4], [4, 8]]); +Array.from(m); +// [[1, 2], [2, 4], [4, 8]] + +var mapper = new Map([['1', 'a'], ['2', 'b']]); +Array.from(mapper.values()); +// ['a', 'b']; + +Array.from(mapper.keys()); +// ['1', '2']; +</pre> + +<h3 id="Tạo_mảng_từ_một_đối_tượng_có_tính_chất_giống_mảng_(arguments)">Tạo mảng từ một đối tượng có tính chất giống mảng (arguments)</h3> + +<pre class="brush: js">function f() { + return Array.from(arguments); +} + +f(1, 2, 3); + +// [1, 2, 3]</pre> + +<h3 id="Hàm_arrow_trong_Array.from">Hàm arrow trong <code>Array.from</code></h3> + +<pre class="brush: js">// Using an arrow function as the map function to +// manipulate the elements +Array.from([1, 2, 3], x => x + x); +// [2, 4, 6] + + +// Generate a sequence of numbers +// Since the array is initialized with `undefined` on each position, +// the value of `v` below will be `undefined` +Array.from({length: 5}, (v, i) => i); +// [0, 1, 2, 3, 4] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>Array.from</code> đã được thêm vào tiêu chuẩn ECMA-262 trong ấn bản thứ 6 (ES2015); như vậy nó có thể không có mặt trong các bản hiện thực khác của ECMA-262 khác. Bạn có thể giải quyết vấn đề này bằng cách chèn đoạn mã sau vào đầu các đoạn mã JavaScript cho phép sử dụng <code>Array.from</code> trong các bản thực thi không hỗ trợ <code>Array.from</code>.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 6, 22.1.2.1 +if (!Array.from) { + Array.from = (function () { + var toStr = Object.prototype.toString; + var isCallable = function (fn) { + return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; + }; + var toInteger = function (value) { + var number = Number(value); + if (isNaN(number)) { return 0; } + if (number === 0 || !isFinite(number)) { return number; } + return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); + }; + var maxSafeInteger = Math.pow(2, 53) - 1; + var toLength = function (value) { + var len = toInteger(value); + return Math.min(Math.max(len, 0), maxSafeInteger); + }; + + // The length property of the from method is 1. + return function from(arrayLike/*, mapFn, thisArg */) { + // 1. Let C be the this value. + var C = this; + + // 2. Let items be ToObject(arrayLike). + var items = Object(arrayLike); + + // 3. ReturnIfAbrupt(items). + if (arrayLike == null) { + throw new TypeError('Array.from requires an array-like object - not null or undefined'); + } + + // 4. If mapfn is undefined, then let mapping be false. + var mapFn = arguments.length > 1 ? arguments[1] : void undefined; + var T; + if (typeof mapFn !== 'undefined') { + // 5. else + // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. + if (!isCallable(mapFn)) { + throw new TypeError('Array.from: when provided, the second argument must be a function'); + } + + // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 2) { + T = arguments[2]; + } + } + + // 10. Let lenValue be Get(items, "length"). + // 11. Let len be ToLength(lenValue). + var len = toLength(items.length); + + // 13. If IsConstructor(C) is true, then + // 13. a. Let A be the result of calling the [[Construct]] internal method + // of C with an argument list containing the single item len. + // 14. a. Else, Let A be ArrayCreate(len). + var A = isCallable(C) ? Object(new C(len)) : new Array(len); + + // 16. Let k be 0. + var k = 0; + // 17. Repeat, while k < len… (also steps a - h) + var kValue; + while (k < len) { + kValue = items[k]; + if (mapFn) { + A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); + } else { + A[k] = kValue; + } + k += 1; + } + // 18. Let putStatus be Put(A, "length", len, true). + A.length = len; + // 20. Return A. + return A; + }; + }()); +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Khởi tạo.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.from")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("TypedArray.from()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/includes/index.html b/files/vi/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..bc4b1980f4 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,135 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - JavaScript + - Mảng + - Phương Thức + - Pollyfill + - Prototype + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>includes()</strong></code> kiểm tra xem phần tử đã cho có tồn tại trong mảng hay không, trả về kết quả <code>true</code> hoặc <code>false</code>.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<var>valueToFind</var>[, <var>fromIndex</var>]) +</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code><var>valueToFind</var></code></dt> + <dd> + <p>Giá trị muốn kiểm tra.</p> + + <div class="blockIndicator note"> + <p><strong>Lưu ý:</strong> Khi kiểm tra chuỗi hoặc kí tự, <code>includes()</code> sẽ <strong>phân biệt hoa thường</strong>.</p> + </div> + </dd> + <dt><code><var>fromIndex</var></code> {{optional_inline}}</dt> + <dd>Vị trí trong mảng để bắt đầu tìm kiếm <code><var>valueToFind</var></code>; đầu tìm kiếm tại <code><var>fromIndex</var></code> khi <code><var>fromIndex</var></code> mang giá trị dương, hoặc tại <code>array.length + fromIndex</code> khi <code><var>fromIndex</var></code> mang giá trị âm (sử dụng {{interwiki("wikipedia", "absolute value", "giá trị tuyệt đối")}} của <code><var>fromIndex</var></code> làm số lượng kí tự tính từ cuối mảng làm vị trí bắt đầu). Giá trị mặc định là 0.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Có kiểu {{jsxref("Boolean")}}, trả về <code>true</code> nếu <code><var>valueToFind</var></code> được tìm thấy trong mảng (hoặc một phần của mảng được xác định bởi <code><var>fromIndex</var></code> nếu có). Các giá trị "không" được coi là bằng nhau (-0 sẽ bằng 0 và +0), nhưng <code>false</code> thì không bằng 0.</p> + +<div class="note"> +<p><strong>Lưu ý:</strong> Về mặt kĩ thuật, <code>includes()</code> sử dụng thuật toán <code><a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality">sameValueZero</a></code> để kiểm tra phần tử đã cho có tìm thấy hay không.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">[1, 2, 3].includes(2); // true +[1, 2, 3].includes(4); // false +[1, 2, 3].includes(3, 3); // false +[1, 2, 3].includes(3, -1); // true +[1, 2, NaN].includes(NaN); // true +</pre> + +<h3 id="fromIndex_lớn_hơn_hoặc_bằng_độ_dài_mảng"><code><var>fromIndex</var></code> lớn hơn hoặc bằng độ dài mảng</h3> + +<p>Nếu <code><var>fromIndex</var></code> lớn hơn hoặc bằng độ dài mảng, trả về kết quả <code>false</code></p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); // false +arr.includes('c', 100); // false</pre> + +<h3 id="Computed_index_nhỏ_hơn_0">Computed index nhỏ hơn 0</h3> + +<p>Nếu <code><var>fromIndex</var></code> là số âm, computed index sẽ được dùng làm vị trí bắt đầu để tìm kiếm <code><var>valueToFind</var></code>. Nếu computed index nhỏ hơn hoặc bằng <code>-1 * array.length</code>, phần tử đã cho sẽ được tìm kiếm trong toàn bộ mảng (tương tự như <code><var>fromIndex</var></code> bằng 0).</p> + +<pre class="brush: js">// độ dài mảng là 3 +// fromIndex là -100 +// computed index là 3 + (-100) = -97 + +var arr = ['a', 'b', 'c']; + +arr.includes('a', -100); // true +arr.includes('b', -100); // true +arr.includes('c', -100); // true +arr.includes('a', -2); // false</pre> + +<h3 id="includes_used_as_a_generic_method"><code>includes()</code> used as a generic method</h3> + +<p><code>includes()</code> method is intentionally generic. It does not require <code>this</code> value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates <code>includes()</code> method called on the function's <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> object.</p> + +<pre class="brush: js">(function() { + console.log([].includes.call(arguments, 'a')); // true + console.log([].includes.call(arguments, 'd')); // false +})('a','b','c');</pre> + +<div class="hidden"> +<p>Please do not add polyfills on reference articles. For more details and discussion, see <a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a></p> +</div> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_của_trình_duyệt">Khả năng tương thích của trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.includes")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/index.html b/files/vi/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..151242e596 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,433 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>Đối tượng <strong><code>Array</code></strong> trong JavaScript là đối tượng toàn cục được dùng để xây dựng nên các mảng; là những đối tượng cấp cao và giống một dạng danh sách.</p> + +<p><strong>Tạo một Mảng</strong></p> + +<pre class="brush: js notranslate">var fruits = ['Apple', 'Banana']; + +console.log(fruits.length); +// 2 +</pre> + +<p><strong>Truy cập (bằng chỉ mục) đến một phần tử của Mảng</strong></p> + +<pre class="brush: js notranslate">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p><strong>Lặp qua một Mảng</strong></p> + +<pre class="brush: js notranslate">fruits.forEach(function(item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p><strong>Thêm phần tử vào cuối Mảng</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.push('Orange'); +// ["Apple", "Banana", "Orange"] +</pre> + +<p><strong>Xóa phần tử từ cuối Mảng</strong></p> + +<pre class="brush: js notranslate">var last = fruits.pop(); // xoá bỏ Orange (từ vị trí cuối) +// ["Apple", "Banana"]; +</pre> + +<p><strong>Xóa phần tử từ đầu Mảng</strong></p> + +<pre class="brush: js notranslate">var first = fruits.shift(); // xoá bỏ Apple từ vị trí đầu +// ["Banana"]; +</pre> + +<p><strong>Thêm phần tử vào đầu Mảng</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.unshift('Strawberry') // thêm vào vị trí đầu +// ["Strawberry", "Banana"]; +</pre> + +<p><strong>Tìm chỉ mục của một phần tử trong Mảng</strong></p> + +<pre class="brush: js notranslate">fruits.push('Mango'); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf('Banana'); +// 1 +</pre> + +<p><strong>Xóa một phần tử bằng chỉ mục của nó</strong></p> + +<pre class="brush: js notranslate">var removedItem = fruits.splice(pos, 1); // đây là cách để xoá bỏ một phần tử + +// ["Strawberry", "Mango"]</pre> + +<p><strong>Xóa các phần tử bắt đầu từ vị trí của chỉ mục</strong></p> + +<pre class="brush: js notranslate">var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']; +console.log(vegetables); +// ["Cabbage", "Turnip", "Radish", "Carrot"] + +var pos = 1, n = 2; + +var removedItems = vegetables.splice(pos, n); +// đây là cách để xoá các phần tử, n định nghĩa số phần tử cần xoá bỏ, +// từ vị trí đó (pos) trở đi đến cuối mảng. + +console.log(vegetables); +// ["Cabbage", "Carrot"] (mảng ban đầu đã bị thay đổi) + +console.log(removedItems); +// ["Turnip", "Radish"]</pre> + +<p><strong>Sao chép một Mảng</strong></p> + +<pre class="brush: js notranslate">var shallowCopy = fruits.slice(); // đây là cách để tạo một bản sao +// ["Strawberry"] +</pre> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate"><code>[ <var>element0</var> , <var>element1</var> , ..., <var>elementN</var> ] +new Array(<var>element0</var> , <var>element1</var> [, ... [, <var>elementN</var> ]]) +new Array(<var>arrayLength</var>)</code></pre> + +<dl> + <dt><code>nguyên tố <em>N</em></code></dt> + <dd>Một mảng JavaScript được khởi tạo với các yếu tố nhất định, ngoại trừ trong trường hợp một đối số duy nhất được truyền vào <code>mảng</code> xây dựng và lập luận đó là một con số. (Xem bên dưới). Lưu ý rằng trường hợp đặc biệt này chỉ áp dụng cho các mảng JavaScript tạo ra với các <code>mảng</code> xây dựng, không mảng literals tạo ra với cú pháp khung.</dd> + <dt><code>arrayLength</code></dt> + <dd>Nếu đối số duy nhất được truyền cho các <code>mảng</code> constructor là một số nguyên giữa 0 và 2 <sup>32</sup> -1 (bao gồm), điều này trả về một mảng JavaScript mới với chiều dài thiết lập để con số đó. Nếu đối số là số nào khác, một {{jsxref ("Global_Objects / RangeError", "RangeError")}} ngoại lệ được ném ra.</dd> +</dl> + +<h2 id="Miêu_tả">Miêu tả</h2> + +<p>Mảng là đối tượng danh sách giống như nguyên mẫu mà có phương pháp để thực hiện traversal và đột biến hoạt động. Cả chiều dài của một mảng JavaScript hay các loại của các yếu tố của nó được cố định. Vì chiều dài kích thước của một mảng lớn hoặc thu nhỏ bất cứ lúc nào, các mảng JavaScript là không đảm bảo được dày đặc. Nói chung, đây là những đặc điểm thuận tiện; nhưng nếu các tính năng này không được mong muốn sử dụng cụ thể của bạn, bạn có thể xem xét sử dụng các mảng gõ.</p> + +<p>Một số người nghĩ rằng <a class="external" href="http://www.andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/">bạn không nên sử dụng một mảng như là một mảng kết hợp</a> . Trong mọi trường hợp, bạn có thể sử dụng đồng bằng {{jsxref ("Global_Objects / Object", "đối tượng")}} thay vào đó, mặc dù làm như vậy đi kèm với hãy cẩn thận của mình. Xem các bài viết <a class="external" href="http://www.less-broken.com/blog/2010/12/lightweight-javascript-dictionaries.html">từ điển JavaScript nhẹ với các phím tùy ý</a> như là một ví dụ.</p> + +<h3 id="Truy_cập_vào_các_phần_tử_mảng">Truy cập vào các phần tử mảng</h3> + +<p>Mảng JavaScript được zero-lập chỉ mục: phần tử đầu tiên của mảng là lúc chỉ số <code>0</code> , và các yếu tố cuối cùng là chỉ số tương đương với giá trị của của mảng {{jsxref ("Array.length", "chiều dài")}} tài sản trừ đi 1.</p> + +<pre class="brush: js notranslate">var arr = ['đây là yếu tố đầu tiên "," đây là yếu tố thứ hai']; +console.log(arr[0]); // Nhật ký này là yếu tố đầu tiên ' +console.log(arr[1]); // Nhật ký này là yếu tố thứ hai ' +console.log(arr[arr.length - 1]); // Nhật ký này là yếu tố thứ hai ' +</pre> + +<p>Các phần tử mảng là thuộc tính đối tượng trong cùng một cách mà <code>toString</code> là một thuộc tính, nhưng cố gắng để truy cập vào một phần tử của mảng như sau ném một lỗi cú pháp, bởi vì tên sở hữu là không hợp lệ:</p> + +<pre class="brush: js notranslate">console.log(arr.0); // Một lỗi cú pháp +</pre> + +<p>Có gì đặc biệt về mảng JavaScript và các thuộc tính gây ra điều này là. Tính JavaScript bắt đầu bằng một chữ số không thể được tham chiếu với ký hiệu dấu chấm; và phải được truy cập bằng cách sử dụng ký hiệu khung. Ví dụ, nếu bạn đã có một đối tượng với một thuộc tính có tên <code>'3D'</code> , nó chỉ có thể được tham chiếu bằng cách sử dụng ký hiệu khung. Ví dụ như:</p> + +<pre class="brush: js notranslate">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // Một lỗi cú pháp +console.log(years[0]); // Đúng cú pháp +</pre> + +<pre class="brush: js notranslate">renderer.3d.setTexture (model, 'character.png'); // Một lỗi cú pháp +renderer['3D']setTexture (model, 'character.png.'); // Đúng cú pháp +</pre> + +<p>Lưu ý rằng trong ví dụ <code>3d</code> , <code>'3D'</code> đã được trích dẫn. Có thể trích dẫn các chỉ số mảng JavaScript cũng như (ví dụ, <code>năm ['2']</code> thay vì <code>năm [2]</code> ), mặc dù nó không cần thiết. 2 trong <code>năm [2]</code> là bị cưỡng chế vào một chuỗi các công cụ JavaScript thông qua một tiềm ẩn <code>toString</code> chuyển đổi. Chính vì lý do này mà <code>'2'</code> và <code>'02'</code> sẽ chỉ đến hai khe cắm khác nhau trên <code>năm</code> đối tượng và các ví dụ sau đây có thể là <code>sự thật</code> :</p> + +<pre class="brush: js notranslate">console.log(years['2'] = years['02']!); +</pre> + +<p>Tương tự, thuộc tính đối tượng đó xảy ra để được dành riêng chỉ có thể được truy cập như các chuỗi trong ký hiệu khung:</p> + +<pre class="brush: js notranslate">var promise = { + 'Var': 'text', + 'Array': [1, 2, 3, 4] +}; + +console.log(promise['Array']); +</pre> + +<h3 id="Mối_quan_hệ_giữa_chiều_dài_và_số_thuộc_tính">Mối quan hệ giữa <code>chiều dài</code> và số thuộc tính</h3> + +<p>Một mảng của JavaScript {{jsxref ("Array.length", "chiều dài")}} tài sản và tính toán được kết nối. Một số phương pháp mảng xây dựng trong (ví dụ, {{jsxref ("Array.join", "tham gia")}}, {{jsxref ("Array.slice", "lát cắt")}}, {{jsxref (" Array.indexOf "," indexOf ")}}, vv) có tính đến các giá trị của một mảng {{jsxref (" Array.length "," chiều dài ")}} tài sản khi chúng được gọi. Các phương pháp khác (ví dụ, {{jsxref ("Array.push", "đẩy")}}, {{jsxref ("Array.splice", "mối nối")}}, vv) cũng cho kết quả trong bản cập nhật tới một mảng của { {jsxref ("Array.length", "chiều dài")}} thuộc tính.</p> + +<pre class="notranslate"><code>var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3</code></pre> + +<p>Khi thiết lập một thuộc tính trên một mảng JavaScript khi tài sản là một chỉ số mảng hợp lệ và chỉ số đó là ngoài giới hạn hiện tại của mảng, engine sẽ cập nhật thuộc tính {{jsxref ("Array.length", "chiều dài")}} của mảng cho phù hợp:</p> + +<pre class="notranslate"><code>fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6</code></pre> + +<p>Tăng {{jsxref ("Array.length", "chiều dài")}}.</p> + +<pre class="brush: js notranslate">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>Giảm thuộc tính {{jsxref ("Array.length", "chiều dài")}} , tuy nhiên, xóa các phần tử.</p> + +<pre class="brush: js notranslate">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>Điều này được giải thích thêm về {{jsxref ("Array.length")}} trang.</p> + +<h3 id="Tạo_một_mảng_bằng_cách_sử_dụng_kết_quả_của_một_trận_đấu">Tạo một mảng bằng cách sử dụng kết quả của một trận đấu</h3> + +<p>Kết quả của một trận đấu giữa một biểu hiện thường xuyên và một chuỗi có thể tạo ra một mảng JavaScript. Mảng này có các tính chất và các yếu tố trong đó cung cấp thông tin về trận đấu. Một mảng đó được trả về bởi {{jsxref ("RegExp.exec")}}, {{jsxref ("String.match")}} và {{jsxref ("string.Replace")}}. Để giúp giải thích các thuộc tính và các yếu tố, nhìn vào ví dụ sau đây và sau đó tham khảo bảng dưới đây:</p> + +<pre class="brush: js notranslate">// Trận đấu một d theo sau bởi một hoặc nhiều b theo sau bởi một d +// Ghi phù hợp của b và d sau +// Bỏ qua trường hợp + +var Myre = / d (b +) (d) / i; +var myArray = myRe.exec('cdbBdbsbz'); +</pre> + +<p>Các tính chất và các yếu tố trở về từ trận đấu này như sau:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Bất động sản / tử</td> + <td class="header">Miêu tả</td> + <td class="header">Thí dụ</td> + </tr> + <tr> + <td><code>đầu vào</code></td> + <td>Một thuộc tính chỉ đọc phản ánh các chuỗi ban đầu dựa vào đó các biểu thức chính quy được kết hợp.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>mục lục</code></td> + <td>Một thuộc tính chỉ đọc mà là chỉ số không dựa trên các trận đấu trong chuỗi.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>Một yếu tố chỉ đọc mà xác định các ký tự tương ứng cuối cùng.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ... [n]</code></td> + <td>Chỉ đọc các yếu tố đó chỉ định các trận đấu substring parenthesized, nếu có trong các biểu hiện thường xuyên. Số lượng các chuỗi con trong ngoặc có thể là không giới hạn.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt>{{Jsxref ("Array.length")}}</dt> + <dd>Thuộc tính chiều dài của <code>Array</code> trong constructor (hàm dựng) có giá trị là 1.</dd> + <dt>{{Jsxref ("Array.prototype")}}</dt> + <dd>Cho phép bổ sung các thuộc tính cho tất cả các đối tượng mảng.</dd> +</dl> + +<h2 id="Phương_thức">Phương thức</h2> + +<dl> + <dt>{{Jsxref ("Array.from()")}} {{experimental_inline}}</dt> + <dd>Tạo ra một <code>Mảng</code> mới từ một đối tượng giống mảng hoặc iterable.</dd> + <dt>{{Jsxref ("Array.isArray()")}}</dt> + <dd>Trả về true nếu một biến là một mảng, ngược lại false nếu không phải là mảng.</dd> + <dt>{{Jsxref ("Array.of()")}} {{experimental_inline}}</dt> + <dd>Tạo ra một <code>Array</code> mới với một số lượng các đối số, bất kể số hoặc loại của các đối số.</dd> +</dl> + +<h2 id="Array_instances"><code>Array</code> instances</h2> + +<p>Tất cả instance <code>Array </code>kế thừa từ {{jsxref ("Array.prototype")}}. Các đối tượng nguyên mẫu của <code>Array</code> constructor có thể được sửa đổi để ảnh hưởng đến tất cả các instance <code>Array</code>.</p> + +<h3 id="Thuộc_tính_2">Thuộc tính</h3> + +<div>{{Page ('/ en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Properties')}}</div> + +<h3 id="Phương_thức_2">Phương thức</h3> + +<h4 id="Phương_thức_mutator">Phương thức mutator</h4> + +<div>{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Mutator_methods')}}</div> + +<h4 id="Phương_thức_accessor">Phương thức accessor</h4> + +<div>{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Accessor_methods')}}</div> + +<h4 id="Phương_thức_lặp_đi_lặp_lại">Phương thức lặp đi lặp lại</h4> + +<div>{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Iteration_methods')}}</div> + +<h2 id="Array_phương_thức_chung"><code>Array</code> phương thức chung</h2> + +<p>Đôi khi bạn muốn áp dụng phương thức mảng các chuỗi hoặc các đối tượng mảng giống khác (chẳng hạn như chức năng {{jsxref ("Chức năng / lập luận", "lý luận", "", 1)}}). Bằng cách này, bạn đối xử với một chuỗi như là một mảng kí tự (hoặc nếu không điều trị một phi mảng như là một mảng). Ví dụ, để kiểm tra xem tất cả các nhân vật trong biến <var>str</var> là một lá thư, bạn có thể viết:</p> + +<pre class="brush: js notranslate">function isLetter (person) { + return person >= 'a' && person <= 'z'; +} + +if (Array.prototype.every.call (str, isLetter)) { + console.log("<code>The string</code> " + str + " <code>contains only letters</code>!"); +} +</pre> + +<p>Ký hiệu này là khá lãng phí và JavaScript 1.6 giới thiệu một cách viết tắt chung:</p> + +<pre class="brush: js notranslate">if (Array.every (str, isLetter)) { + console.log("<code>The string</code> " + str + " <code>contains only letters</code>!"); +} +</pre> + +<p>{{Jsxref ("Global_Objects / String", "Generics", "#String_generic_methods", 1)}} cũng có sẵn trên {{jsxref ("Global_Objects / String", "String")}}.</p> + +<p>Đây không phải là một phần của tiêu chuẩn ECMAScript và chúng không được hỗ trợ bởi các trình duyệt không phải là Gecko. Như một thay thế tiêu chuẩn, bạn có thể chuyển đổi đối tượng của bạn thành một mảng bằng cách sử dụng ({{jsxref ("Array.from ()")}}, mặc dù phương pháp này có thể không được hỗ trợ trong các trình duyệt cũ:</p> + +<pre class="notranslate"><code>if (Array.from(str).every(isLetter)) { + console.log("The string " + str + " contains only letters!"); +}</code></pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tạo_một_mảng">Tạo một mảng</h3> + +<p>Ví dụ sau tạo một mảng, <code>msgArray</code> , với chiều dài 0, sau đó gán giá trị cho <code>[0] msgArray</code> và <code>msgArray [99]</code> , thay đổi độ dài của mảng đến 100.</p> + +<pre class="brush: js notranslate">var msgArray = []; +msgArray [0] = "Hello"; +msgArray [99] = 'World'; + +if (msgArray.length === 100) { + console.log('Chiều dài là 100'); +} +</pre> + +<h3 id="Tạo_một_mảng_hai_chiều">Tạo một mảng hai chiều</h3> + +<p>Sau đây tạo ra một bàn cờ như là một mảng hai chiều của chuỗi. Động thái đầu tiên được thực hiện bằng cách sao chép 'p' trong (6,4) đến (4,4). Các vị trí cũ (6,4) được làm trống.</p> + +<pre class="notranslate"><code>var board = [ + ['R','N','B','Q','K','B','N','R'], + ['P','P','P','P','P','P','P','P'], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + ['p','p','p','p','p','p','p','p'], + ['r','n','b','q','k','b','n','r'] ]; + +console.log(board.join('\n') + '\n\n'); + +// Di chuyển King's Pawn về phía trước 2 +board[4][4] = board[6][4]; +board[6][4] = ' '; +console.log(board.join('\n'));</code></pre> + +<p>Đây là kết quả:</p> + +<pre class="eval notranslate">R, N, B, Q, K, B, N, R +P, P, P, P, P, P, P, P + ,,,,,,, + ,,,,,,, + ,,,,,,, + ,,,,,,, +p, p, p, p, p, p, p, p +r, n, b, q, k, b, n, r + +R, N, B, Q, K, B, N, R +P, P, P, P, P, P, P, P + ,,,,,,, + ,,,,,,, + ,,,, P,,, + ,,,,,,, +p, p, p, p,, p, p, p +r, n, b, q, k, b, n, r +</pre> + +<h3 id="Sử_dụng_một_mảng_để_sắp_xếp_một_tập_các_giá_trị">Sử dụng một mảng để sắp xếp một tập các giá trị</h3> + +<pre class="notranslate"><code>values = []; +for (var x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +}; +console.table(values)</code></pre> + +<p>Kết quả là:</p> + +<pre class="notranslate"><code>0 1 0 +1 2 2 +2 4 8 +3 8 18 +4 16 32 +5 32 50 +6 64 72 +7 128 98 +8 256 128 +9 512 162</code></pre> + +<p>(Cột đầu tiên là index (chỉ mục))</p> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc điểm kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu.</td> + </tr> + <tr> + <td>{{SpecName("ES5.1", "#sec-15.4", "Array")}}</td> + <td>{{Spec2("ES5.1")}}</td> + <td>Phương thức mới được thêm vào: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf ")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array. prototype.forEach","forEach")}}, {{jsxref("Array.prototype.map","map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}</td> + </tr> + <tr> + <td>{{SpecName("ES6", "#sec-array-objects", "Array")}}</td> + <td>{{Spec2 ("ES6")}}</td> + <td>Phương thức mới được thêm vào: {{jsxref ("Array.from")}}, {{jsxref ("Array.of")}}, {{jsxref ("Array.prototype.find", "find")}}, {{jsxref ("Array.prototype.findIndex", "findIndex")}}, {{jsxref ("Array.prototype.fill", "fill")}}, {{jsxref ("Array.prototype.copyWithin", "copyWithin")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_trình_duyệt">Khả năng tương thích trình duyệt</h2> + +<div>{{Compat("javascript.builtins.Array")}}</div> + +<div id="compat-desktop"></div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">Hướng dẫn JavaScript: "thuộc tính đối tượng Indexing"</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: Array Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Mảng Typed</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/indexof/index.html b/files/vi/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..1ac4ea6321 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,228 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong>indexOf()</strong> sẽ trả về giá trị index đầu tiên của mảng, nơi mà nó đc tìm thấy trong mảng, hoặc trả về -1 nếu không tồn tại trong mảng.</p> + +<div class="note"> +<p><strong>Chú ý:</strong> sử dụng indexOf() cho String, xem ở đây {{jsxref("String.prototype.indexOf()")}}.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/array-indexof.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.indexOf(<var>searchElement[</var>, <var>fromIndex]</var>)</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>Phần tử cần tìm trong mảng.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>Vị trí index nơi bắt đầu tìm kiếm. Nếu index lớn hơn hoặc bằng số phần tử trong mảng, <strong>-1</strong> sẽ được trả về, việc tìm kiếm sẽ không xảy ra. Nếu giá trị <code>fromIndex</code> là một số âm, vị trí index được tính từ cuối mảng. Lưu ý: cho dù <code>fromIndex</code> là số âm, kết quả tìm kiếm vẫn tính từ đầu mảng trở về sau. Nếu index bằng 0, cả mảng sẽ được tìm kiếm. Mặc định: 0 (cả mảng sẽ được tìm kiếm)</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Index đầu tiên của phần tử tìm thấy trong mảng; <strong>-1</strong> nếu không tìm thấy.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>indexOf()</code> sẽ so sánh giá trị <code>searchElement</code> với các phần tử của mảng sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">so sánh chặt</a> (tương đương với việc so sánh toán tử ba-dấu-bằng <code>===</code>)</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_indexOf">Sử dụng <code>indexOf()</code></h3> + +<p>Ví dụ sau sẽ dùng <code>indexOf()</code> để tìm vị trí của giá trị trong một mảng.</p> + +<pre class="brush: js">var array = [2, 9, 9]; +array.indexOf(2); // 0 +array.indexOf(7); // -1 +array.indexOf(9, 2); // 2 +array.indexOf(2, -1); // -1 +array.indexOf(2, -3); // 0 +</pre> + +<h3 id="Tìm_tất_cả_các_lần_xuất_hiện_của_phần_tử">Tìm tất cả các lần xuất hiện của phần tử</h3> + +<pre class="brush: js">var indices = []; +var array = ['a', 'b', 'a', 'c', 'a', 'd']; +var element = 'a'; +var idx = array.indexOf(element); +while (idx != -1) { + indices.push(idx); + idx = array.indexOf(element, idx + 1); +} +console.log(indices); +// [0, 2, 4] +</pre> + +<h3 id="Xác_định_phần_tử_đã_tồn_tại_trong_mảng_hay_chưa_và_cập_nhật_lại_mảng">Xác định phần tử đã tồn tại trong mảng hay chưa và cập nhật lại mảng</h3> + +<pre class="brush: js">function updateVegetablesCollection (veggies, veggie) { + if (veggies.indexOf(veggie) === -1) { + veggies.push(veggie); + console.log('New veggies collection is : ' + veggies); + } else if (veggies.indexOf(veggie) > -1) { + console.log(veggie + ' already exists in the veggies collection.'); + } +} + +var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; + +updateVegetablesCollection(veggies, 'spinach'); +// New veggies collection is : potato,tomato,chillies,green-pepper,spinach +updateVegetablesCollection(veggies, 'spinach'); +// spinach already exists in the veggies collection. +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>indexOf()</code> được thêm vào đặc tả ECMA-262, phiên bản 5; nên có thể nó không có sẵn trong tất cả trình duyệt. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script. Polyfill này sẽ giúp bạn vẫn sử dụng được <code>indexOf</code> dù trình duyệt nào đó vẫn chưa hỗ trợ sẵn. Giải thuật của polyfill này tương đương với đặc tả của <code>indexOf</code> trong ECMA-262, 5th edition, với yêu cầu {{jsxref("Global_Objects/TypeError", "TypeError")}} và {{jsxref("Math.abs()")}} không bị thay đổi.<br> + </p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// This version tries to optimize by only checking for "in" when looking for undefined and</span> +<span class="comment token">// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.</span> +<span class="comment token">// Whether it is actually faster remains to be seen.</span> +<span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span><span class="class-name token">Array</span><span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>indexOf<span class="punctuation token">)</span> + <span class="class-name token">Array</span><span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>indexOf <span class="operator token">=</span> <span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">Object<span class="punctuation token">,</span> max<span class="punctuation token">,</span> min</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="string token">"use strict"</span> + <span class="keyword token">return</span> <span class="keyword token">function</span> <span class="function token">indexOf</span><span class="punctuation token">(</span><span class="parameter token">member<span class="punctuation token">,</span> fromIndex</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="keyword token">this</span> <span class="operator token">===</span> <span class="keyword token">null</span> <span class="operator token">||</span> <span class="keyword token">this</span> <span class="operator token">===</span> <span class="keyword token">undefined</span><span class="punctuation token">)</span> + <span class="keyword token">throw</span> <span class="function token">TypeError</span><span class="punctuation token">(</span><span class="string token">"Array.prototype.indexOf called on null or undefined"</span><span class="punctuation token">)</span> + + <span class="keyword token">var</span> that <span class="operator token">=</span> <span class="function token">Object</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">)</span><span class="punctuation token">,</span> Len <span class="operator token">=</span> that<span class="punctuation token">.</span>length <span class="operator token">>>></span> <span class="number token">0</span><span class="punctuation token">,</span> i <span class="operator token">=</span> <span class="function token">min</span><span class="punctuation token">(</span>fromIndex <span class="operator token">|</span> <span class="number token">0</span><span class="punctuation token">,</span> Len<span class="punctuation token">)</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>i <span class="operator token"><</span> <span class="number token">0</span><span class="punctuation token">)</span> i <span class="operator token">=</span> <span class="function token">max</span><span class="punctuation token">(</span><span class="number token">0</span><span class="punctuation token">,</span> Len <span class="operator token">+</span> i<span class="punctuation token">)</span> + <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>i <span class="operator token">>=</span> Len<span class="punctuation token">)</span> <span class="keyword token">return</span> <span class="operator token">-</span><span class="number token">1</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span>member <span class="operator token">===</span> <span class="keyword token">void</span> <span class="number token">0</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="comment token">// undefined</span> + <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="punctuation token">;</span> i <span class="operator token">!==</span> Len<span class="punctuation token">;</span> <span class="operator token">++</span>i<span class="punctuation token">)</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>that<span class="punctuation token">[</span>i<span class="punctuation token">]</span> <span class="operator token">===</span> <span class="keyword token">void</span> <span class="number token">0</span> <span class="operator token">&&</span> i <span class="keyword token">in</span> that<span class="punctuation token">)</span> <span class="keyword token">return</span> i + <span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>member <span class="operator token">!==</span> member<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="comment token">// NaN</span> + <span class="keyword token">return</span> <span class="operator token">-</span><span class="number token">1</span> <span class="comment token">// Since NaN !== NaN, it will never be found. Fast-path it.</span> + <span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="comment token">// all else</span> + <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="punctuation token">;</span> i <span class="operator token">!==</span> Len<span class="punctuation token">;</span> <span class="operator token">++</span>i<span class="punctuation token">)</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>that<span class="punctuation token">[</span>i<span class="punctuation token">]</span> <span class="operator token">===</span> member<span class="punctuation token">)</span> <span class="keyword token">return</span> i + + <span class="keyword token">return</span> <span class="operator token">-</span><span class="number token">1</span> <span class="comment token">// if the value was not found, then return -1</span> + <span class="punctuation token">}</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">(</span>Object<span class="punctuation token">,</span> Math<span class="punctuation token">.</span>max<span class="punctuation token">,</span> Math<span class="punctuation token">.</span>min<span class="punctuation token">)</span></code></pre> + +<p>Tuy nhiên, nếu bạn muốn hiểu rõ mọi chi tiết của đặc tả ECMA, và không mấy quan tâm đến performance hay cần phải ngắn gọn, thì bạn nên tham khảo đoạn polyfill bên dưới:</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.14 +// Reference: http://es5.github.io/#x15.4.4.14 +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function(searchElement, fromIndex) { + + var k; + + // 1. Let o be the result of calling ToObject passing + // the this value as the argument. + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let lenValue be the result of calling the Get + // internal method of o with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = o.length >>> 0; + + // 4. If len is 0, return -1. + if (len === 0) { + return -1; + } + + // 5. If argument fromIndex was passed let n be + // ToInteger(fromIndex); else let n be 0. + var n = fromIndex | 0; + + // 6. If n >= len, return -1. + if (n >= len) { + return -1; + } + + // 7. If n >= 0, then Let k be n. + // 8. Else, n<0, Let k be len - abs(n). + // If k is less than 0, then let k be 0. + k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + // 9. Repeat, while k < len + while (k < len) { + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the + // HasProperty internal method of o with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + // i. Let elementK be the result of calling the Get + // internal method of o with the argument ToString(k). + // ii. Let same be the result of applying the + // Strict Equality Comparison Algorithm to + // searchElement and elementK. + // iii. If same is true, return k. + if (k in o && o[k] === searchElement) { + return k; + } + k++; + } + return -1; + }; +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.indexOf")}}</p> +</div> + +<h2 id="Lưu_ý_về_tương_thích">Lưu ý về tương thích</h2> + +<ul> + <li>Kể từ Firefox 47 {{geckoRelease(47)}}, phương thức này không còn trả về <code>-0</code>. Ví dụ: <code>[0].indexOf(0, -0)</code> sẽ luôn trả về <code>+0</code> ({{bug(1242043)}}).</li> +</ul> + +<h2 id="Tương_tự">Tương tự</h2> + +<ul> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("TypedArray.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/isarray/index.html b/files/vi/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..9f34413842 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,130 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript 5 + - JavaScript + - Phương Thức + - Tham khảo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.isArray()</strong></code> là một phương thức để xác định liệu giá trị truyền vào có phải là một mảng kiểu {{jsxref("Array")}}.</p> + +<pre class="brush: js">Array.isArray([1, 2, 3]); // true +Array.isArray({foo: 123}); // false +Array.isArray('foobar'); // false +Array.isArray(undefined); // false +</pre> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">Array.isArray(value)</pre> + +<h3 id="Tham_Số">Tham Số</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Giá trị được kiểm tra.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p><code>true</code> nếu giá trị là kiểu mảng {{jsxref("Array")}}; <code>false</code> nếu không phải mảng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Nếu giá trị là {{jsxref("Array")}}, trả về <code>true</code>, nếu không thì trả về <code>false</code>.</p> + +<p>Xem bài viết <a href="http://web.mit.edu/jwalden/www/isArray.html">“Determining with absolute accuracy whether or not a JavaScript object is an array”</a> để có thêm chi tiết. Giả sử ta có một {{jsxref("TypedArray")}} instance, <code>false</code> sẽ luôn được trả về.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">// all following calls return true +Array.isArray([]); +Array.isArray([1]); +Array.isArray(new Array()); +// Little known fact: Array.prototype itself is an array: +Array.isArray(Array.prototype); + +// all following calls return false +Array.isArray(); +Array.isArray({}); +Array.isArray(null); +Array.isArray(undefined); +Array.isArray(17); +Array.isArray('Array'); +Array.isArray(true); +Array.isArray(false); +Array.isArray({ __proto__: Array.prototype }); +</pre> + +<h3 id="instanceof_vs_isArray"><code>instanceof</code> vs <code>isArray</code></h3> + +<p>Để kiểm tra kiểu <code>Array</code>, nên dùng <code>Array.isArray</code> hơn là <code>instanceof</code> bởi vì nó vẫn ra đúng khi giá trị kiểm tra được truyền qua <code>iframes</code>.</p> + +<pre class="brush: js">var iframe = document.createElement('iframe'); +document.body.appendChild(iframe); +xArray = window.frames[window.frames.length-1].Array; +var arr = new xArray(1,2,3); // [1,2,3] + +// Correctly checking for Array +Array.isArray(arr); // true +// Considered harmful, because doesn't work through iframes +arr instanceof Array; // false +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Chạy mã dưới đây đầu tiên trước các mã khác sẽ tạo <code>Array.isArray()</code> nếu nó không có sẵn.</p> + +<pre class="brush: js">if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.isArray")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/join/index.html b/files/vi/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..12e5286a98 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,113 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - JavaScript + - Mảng + - Phương Thức + - Prototype + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">Phương thức <code><strong>join()</strong></code> tạo ra một chuỗi mới bằng cách nối tất cả các phần tử của mảng (hoặc một <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array-like object</a>), ngăn cách chúng bởi dấu phẩy hoặc một chuỗi ký tự xác định. Nếu mảng chỉ có một phần tử, kết quả sẽ trả về chính phần tử đó.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-join.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.join([<var>chuỗi_ngăn_cách</var>])</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>chuỗi_ngăn_cách</code> {{optional_inline}}</dt> + <dd>Là một chuỗi xác định dùng để ngăn cách các phần tử liền kề của mảng. Nếu bỏ qua, các phần tử sẽ được ngăn cách bởi dấu phẩy (","). Nếu là một chuỗi rỗng, các phần tử sẽ nối với nhau mà không có bất kì ký tự nào ngăn cách chúng.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Trả về một chuỗi với giá trị là các phần tử đã được nối với nhau. Nếu <code><em>arr</em>.length</code> bằng <code>0</code>, sẽ trả về một chuỗi rỗng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Chuyển giá trị của tất cả các phần tử mảng thành chuỗi và nối chúng lại thành một chuỗi.</p> + +<div class="warning"> +<p>Nếu phần tử mảng là <code>undefined</code> hoặc <code>null</code>, sẽ trả về một chuỗi rỗng.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Nối_chuỗi_với_4_cách_khác_nhau">Nối chuỗi với 4 cách khác nhau</h3> + +<p>Tạo một mảng <code>a</code> với ba phần tử, sau đó nối chúng lại với 4 cách khác nhau: dùng <code>chuỗi_ngăn_cách</code> mặc định, với dấu phẩy và khoảng cách, với dấu cộng và một chuỗi rỗng.</p> + +<pre class="brush: js notranslate">var a = ['Wind', 'Water', 'Fire']; +a.join(); // 'Wind,Water,Fire' +a.join(', '); // 'Wind, Water, Fire' +a.join(' + '); // 'Wind + Water + Fire' +a.join(''); // 'WindWaterFire'</pre> + +<h3 id="Nối_một_array-like_object">Nối một array-like object</h3> + +<p>Nối <span class="seoSummary"><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array-like object</a></span> (<code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>), bằng cách gọi {{jsxref("Function.prototype.call")}} <code>Array.prototype.join</code>.</p> + +<pre class="brush: js notranslate">function f(a, b, c) { + var s = Array.prototype.join.call(arguments); + console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> +} +f(1, 'a', true); +//expected output: "1,a,true" +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Được đưa vào lần đầu trong JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_của_trình_duyệt">Khả năng tương thích của trình duyệt</h2> + + + +<p>{{Compat("javascript.builtins.Array.join")}}</p> + +<h2 id="Xem_thêm_các_mục_tương_tự">Xem thêm các mục tương tự</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/length/index.html b/files/vi/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..01186b015a --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,144 @@ +--- +title: Array.length +slug: "Web/JavaScript/Reference/Global_Objects/Array/\blength" +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +<div>{{JSRef}}</div> + +<p>Thuộc tính <code><strong>length</strong></code> của một mảng trả về số phần tử trong mảng đó. Đó là một số nguyên 32 bit không dấu và luôn lớn hơn chỉ mục lớn nhất của mảng (chỉ mục lớn nhất chính là dộ dài của mảng trừ đi 1).</p> + +<div>{{EmbedInteractiveExample("pages/js/array-length.html")}}</div> + + + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Giá trị hợp lệ mà </span></font>length</code> có thể biểu diễn là một số nguyên dương có miền giá trị nằm trong khoảng 2 đến 2<sup>32</sup>.</p> + +<pre class="brush: js">var namelistA = new Array(4294967296); //2 to the 32nd power<sup> = </sup>4294967296 +var namelistC = new Array(-100) //negative sign + +console.log(namelistA.length); //RangeError: Invalid array length +console.log(namelistC.length); //RangeError: Invalid array length + + + +var namelistB = []; +namelistB.length = Math.pow(2,32)-1; //set array length less than 2 to the 32nd power +console.log(namelistB.length); + +//4294967295 +</pre> + +<p><code>length</code> có thể được dùng để thay đổi số lượng phần tử có trong mảng bằng cách gán lại giá trị của <code>length</code> . Trong ví dụ dưới đây, khi mảng chỉ có 2 phần tử nhưng ta thay đổi <code>length</code> thành 3 thì mảng sẽ tự động có thêm một phần tử mới. Tuy nhiên việc cố tình thay đổi này sẽ hình thành phần tử mới mang giá trị <code>undefined</code>.</p> + +<pre class="brush: js">var arr = [1, 2, 3]; +printEntries(arr); + +arr.length = 5; // set array length to 5 while currently 3. +printEntries(arr); + +function printEntries(arr) { + var length = arr.length; + for (var i = 0; i < length; i++) { + console.log(arr[i]); + } + console.log('=== printed ==='); +} + +// 1 +// 2 +// 3 +// === printed === +// 1 +// 2 +// 3 +// undefined +// undefined +// === printed ===</pre> + +<p>Thực sự thì bản chất của <code>length</code> property không thể hiện số phần tử 'defined' có trong mảng. Tham khảo thêm từ <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Relationship_between_length_and_numerical_properties" title="Relationship between length and numerical properties">Relationship between <code>length</code> and numerical properties</a>.</p> + +<p>{{js_property_attributes(1, 0, 0)}}</p> + +<div> +<ul> + <li><code>Writable</code>: Nếu thuộc tính này mang giá trị <code>false</code>, giá trị của thuộc tính sẽ không thể bị thay đổi.</li> + <li><code>Configurable</code>: Nếu thuộc tính này mang giá trị <code>false</code>, tất cả các tác vụ cố tình thay đổi hoặc xoá như <code>Writable</code>, <code>Configurable</code>,hoặc <code>Enumerable </code>sẽ thất bại.</li> + <li><code>Enumerable</code>: Nếu thuộc tính này mang giá trị <code>true</code>, thuộc tính có thể được duyệt thông qua các vòng lập <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for..in</a>.</li> +</ul> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Duyệt_mảng">Duyệt mảng</h3> + +<p>Trong ví dụ sau, việc duyệt một mảng với các phần tử kiểu <code>numbers</code> có thể được thực hiện thông qua <code>length</code>. Tại mỗi bước, giá trị của mảng được gán lại gấp đôi.</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 4, 5]; +var length = numbers.length; +for (var i = 0; i < length; i++) { + numbers[i] *= 2; +} +// numbers is now [2, 4, 6, 8, 10] +</pre> + +<h3 id="Cẳt_mảng">Cẳt mảng</h3> + +<p>Trong phần mô tả ở trên, nếu <code>length</code> có thể dùng để tăng thêm số phần tử trong mảng thì ta có thể dùng <code>length </code>để cắt bớt số phần tử trong mảng. Ví dụ dưới đây minh hoạ cho việc cắt bớt 2 phần tử cuối có trong mảng 5 phần tử.</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 4, 5]; + +if (numbers.length > 3) { + numbers.length = 3; +} + +console.log(numbers); // [1, 2, 3] +console.log(numbers.length); // 3 +</pre> + +<h2 id="Đặc_tả"> Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả </th> + <th scope="col">Tình trạng</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đâu</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích">Tính tương thích</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.length")}}</p> +</div> + +<h2 id="Liên_quan">Liên quan</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/map/index.html b/files/vi/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..fe3b6c1c37 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,316 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>map()</strong></code> giúp tạo ra một mảng mới với các phần tử là kết quả từ việc thực thi một hàm lên từng phần tử của mảng được gọi.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) { + // Trả về element mới cho new_array +}</var>[, <var>thisArg</var>])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm để tạo ra phần tử cho mảng mới, nhận vào ba tham số: + <dl> + <dt> </dt> + <dt><code>currentValue</code></dt> + <dd>Giá trị của phần tử trong mảng đang được xử lý</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>Index của phần tử trong mảng đang được xử lý</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>Mảng đang được gọi với <code>map</code></dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>Giá trị gán cho từ khóa <code>this</code> bên trong <code> callback</code>.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một mảng mới với phần tử là kết quả của hàm <code>callback</code>.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>map</code> sẽ gọi hàm <code>callback</code> lên <strong>từng phần tử </strong>của mảng, theo thứ tự trong mảng, và tạo ra một mảng mới chứa các phần tử kết quả. <code>callback</code> chỉ được gọi cho những vị trí index của mảng được gán giá trị, bao gồm cả <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a>. Nó không được gọi cho những vị trí <strong>index trống</strong> (là các index của mảng chưa bao giờ được khởi tạo, bao gồm index chưa được gán giá trị hoặc đã bị xóa bằng <code>delete</code>).</p> + +<p><code>callback</code> được gọi với ba tham số: giá trị của phần tử, index của phần tử, và chính mảng đang được gọi.</p> + +<p>Nếu tham số <code>thisArg</code> được truyền cho <code>map</code>, nó sẽ được gán cho từ khóa <code>this</code> trong hàm callback. Nếu không, giá trị <code>undefined</code> sẽ được dùng cho <code>this</code> với strict mode. Tóm lại, giá trị của từ khóa <code>this</code> trong hàm <code>callback</code> được xác định tuân theo <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">các quy tắc thông thường để xác định <code>this</code> trong một hàm</a>.</p> + +<p><code>map</code> không làm thay đổi mảng ban đầu mà nó được gọi (mặc dù mảng ban đầu vẫn có thể bị thay đổi trong hàm <code>callback</code>).</p> + +<p>Các phần tử được <code>map()</code> xử lý được xác định từ đầu trước khi <code>callback</code> được gọi lần đầu tiên. Những phần tử mới được thêm vào sau khi <code>map</code> đã bắt đầu chạy sẽ không được <code>callback</code> gọi đến. Trong lúc <code>map</code> đang chạy, nếu những phần tử hiện tại của mảng bị thay đổi, thì giá trị mới của chúng sẽ được truyền cho hàm <code>callback</code> ngay tại thời điểm <code>callback</code> chạy qua. Những phần tử bị xóa sau khi <code>map</code> đã bắt đầu và trước khi đến lượt nó cũng sẽ bị bỏ qua.</p> + +<p>Do thuật toán đã quy định trong đặc tả, nếu như mảng ban đầu đã có sẵn những lỗ trống (index rỗng) thì sau khi được gọi với <code>map</code>, mảng đầu ra cũng sẽ có những index rỗng như mảng ban đầu.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Map_(ánh_xạ)_một_mảng_các_số_thành_một_mảng_các_giá_trị_căn_bậc_hai">Map (ánh xạ) một mảng các số thành một mảng các giá trị căn bậc hai</h3> + +<p>Đoạn code sau sẽ map một mảng các số thành một mảng mới chứa giá trị là căn bậc hai của các số trong mảng ban đầu.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var roots = numbers.map(Math.sqrt); +// mảng roots: [1, 2, 3] +// mảng numbers vẫn là: [1, 4, 9] +</pre> + +<h3 id="Dùng_map_để_format_lại_các_object_trong_mảng">Dùng map để format lại các object trong mảng</h3> + +<p>Đoạn code sau sẽ xử lý một mảng các object và trả về một mảng mới chứa các object đã được format lại:</p> + +<pre class="brush: js">var kvArray = [{key: 1, value: 10}, + {key: 2, value: 20}, + {key: 3, value: 30}]; + +var reformattedArray = kvArray.map(obj =>{ + var rObj = {}; + rObj[obj.key] = obj.value; + return rObj; +}); +// reformattedArray bây giờ là: [{1: 10}, {2: 20}, {3: 30}], + +// kvArray vẫn là: +// [{key: 1, value: 10}, +// {key: 2, value: 20}, +// {key: 3, value: 30}] +</pre> + +<h3 id="Map_một_mảng_các_số_sử_dụng_hàm_có_tham_số">Map một mảng các số sử dụng hàm có tham số</h3> + +<p>Đoạn code sau minh họa cách thức map hoạt động khi <code>callback</code> có sử dụng tham số. Tham số này sẽ có giá trị của từng phần tử của mảng ban đầu khi map duyệt qua mảng này.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var doubles = numbers.map(function(num) { + return num * 2; +}); + +// doubles is now [2, 8, 18] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Sử_dụng_map_một_cách_độc_lập">Sử dụng <code>map</code> một cách độc lập</h3> + +<p>Ví dụ sau sẽ minh họa cách dùng <code>map</code> lên một {{jsxref("String")}} một cách độc lập để trả về một mảng các mã byte trong bảng ASCII đại diện cho từng ký tự của chuỗi.</p> + +<pre class="brush: js">var map = Array.prototype.map; +var a = map.call('Hello World', function(x) { + return x.charCodeAt(0); +}); +// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] +</pre> + +<h3 id="Sử_dụng_map_với_kết_quả_của_querySelectorAll">Sử dụng <code>map</code> với kết quả của <code>querySelectorAll</code></h3> + +<p>Ví dụ sau minh họa cách duyệt qua một tập các object (không phải mảng) trả về từ <code>querySelectorAll</code>. Trong trường hợp này, chúng ta sẽ in ra giá trị của tất cả các option được chọn (của các thẻ select) lên console: </p> + +<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); +var values = Array.prototype.map.call(elems, function(obj) { + return obj.value; +}); +</pre> + +<p>Cách trên có thể được giải quyết đơn giản hơn bằng cách sử dụng {{jsxref("Array.from()")}}.</p> + +<h3 id="Trường_hợp_đặc_biệt">Trường hợp đặc biệt</h3> + +<p><a href="http://www.wirfs-brock.com/allen/posts/166">(ý tưởng từ bài viết này)</a></p> + +<p>Chúng ta hay dùng map với hàm một tham số (tham số đó chính là phần tử được duyệt). Và có một số hàm đặc biệt cũng thường được gọi với một tham số, mặc dù chúng có thêm tham số phụ không bắt buộc. Những thói quen này có thể dẫn đến những kết quả ngoài dự đoán.</p> + +<pre class="brush: js" dir="rtl">// Lấy ví dụ: +['1', '2', '3'].map(parseInt); +// Bạn sẽ nghĩ rằng kết quả là [1, 2, 3] +// Nhưng kết quả lại là [1, NaN, NaN] + +// parseInt thường được dùng với 1 tham số, nhưng nó có thể nhận đến 2 tham số. +// Tham số thứ nhất là một biểu thức giá trị và tham số thứ hai là cơ số +// Với hàm callback của Array.prototype.map, nó sẽ nhận vào 3 tham số: +// phần tử, index, mảng ban đầu +// Tham số thứ 3 sẽ được parseInt bỏ qua, nhưng tham số thứ 2 lại có vai trò +// và sẽ dẫn đến kết quả không mong muốn. + +// Sau đây là kết quả thực thi tại từng phần tử: +// parseInt(string, radix) -> map(parseInt(value, index)) +// lần chạy 1 (index là 0): parseInt('1', 0) // cho ta parseInt('1', 0) -> 1 +// lần chạy 2 (index là 1): parseInt('2', 1) // cho ta parseInt('2', 1) -> NaN +// lần chạy 3 (index là 2): parseInt('3', 2) // cho ta parseInt('3', 2) -> NaN + +function returnInt(element) { + return parseInt(element, 10); +} + +['1', '2', '3'].map(returnInt); // [1, 2, 3] +// Thông qua hàm returnInt, kết quả trả về là mảng các số (như mong muốn) + +// Tương tự như trên, nhưng sử dụng một hàm arrow +['1', '2', '3'].map( str => parseInt(str) ); + +// Một cách nữa đơn giản hơn nhưng tránh được vấn đề hàm nhiều tham số: +['1', '2', '3'].map(Number); // [1, 2, 3] +// Tuy nhiên khác với `parseInt`, cách này sẽ giữ lại định dạng +// số thập phân hoặc ký hiệu mũ từ chuỗi ban đầu +['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] +</pre> + +<p>Một ví dụ khác khi gọi <code>map</code> với <code>parseInt</code> là tham số cho callback:</p> + +<pre class="brush: js">var xs = ['10', '10', '10']; + +xs = xs.map(parseInt); + +console.log(xs); +// Kết quả trả về là 10,NaN,2 như đã lý giải ở trên.</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>map()</code> chỉ được thêm vào đặc tả ECMA-262 với phiên bản lần thứ 5; cho nên nó có thể không tồn tại trong một số hiện thực (implementation) của đặc tả. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script của bạn, cho phép sử dụng hàm <code>map</code> tại những nơi mà nó không được hỗ trợ sẵn. Giải thuật trong polyfill này tương đương với hàm <code>map</code> được mô tả trong đặc tả ECMA-262, 5th edition với điều kiện {{jsxref("Object")}}, {{jsxref("TypeError")}}, và {{jsxref("Array")}} không bị thay đổi và <code>callback.call</code> chính là hàm được định nghĩa trong <code>{{jsxref("Function.prototype.call")}}</code>.</p> + +<div class="note"> +<p>Ghi chú bản dịch: những đoạn comment trong code bên dưới trích từ đặc tả ECMA nên sẽ giữ nguyên.</p> +</div> + +<pre><code>// Production steps of ECMA-262, Edition 5, 15.4.4.19 +// Reference: http://es5.github.io/#x15.4.4.19</code> +if (!Array.prototype.map) { + + Array.prototype.map = function(callback/*, thisArg*/) { + + var T, A, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal + // method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let A be a new array created as if by the expression new Array(len) + // where Array is the standard built-in constructor with that name and + // len is the value of len. + A = new Array(len); + + // 7. Let k be 0 + k = 0; + + // 8. Repeat, while k < len + while (k < len) { + + var kValue, mappedValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Let mappedValue be the result of calling the Call internal + // method of callback with T as the this value and argument + // list containing kValue, k, and O. + mappedValue = callback.call(T, kValue, k, O); + + // iii. Call the DefineOwnProperty internal method of A with arguments + // Pk, Property Descriptor + // { Value: mappedValue, + // Writable: true, + // Enumerable: true, + // Configurable: true }, + // and false. + + // In browsers that support Object.defineProperty, use the following: + // Object.defineProperty(A, k, { + // value: mappedValue, + // writable: true, + // enumerable: true, + // configurable: true + // }); + + // For best browser support, use the following: + A[k] = mappedValue; + } + // d. Increase k by 1. + k++; + } + + // 9. return A + return A; + }; +} +</pre> + +<h2 id="Đặc_Tả">Đặc Tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Định nghĩa lần đầu. Hiện thực trong JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.map")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} object</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/of/index.html b/files/vi/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..fdd6d03d53 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,92 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>Array.of()</strong></code> được dùng để tạo ra một mảng mới với các phần tử được truyền vào thông qua tham số truyền vào.</p> + +<p>Cả <code><strong>Array.of()</strong></code>và <code><strong>Array </strong></code>đều chấp nhận tham số đầu vào là các số nguyên để khởi tạo một mảng mới, tuy nhiên chúng ta cần lưu ý trong trường hợp chỉ truyền vào một giá trị nguyên, <code><strong>Array.of()</strong></code> sẽ tạo ra một mảng số nguyên có một phần tử duy nhất, trong khi <code><strong>Array()</strong></code> ?sẽ tạo ra một mảng có số lượng phần tử rỗng (phần tử rỗng không mang giá trị undefined hoặc null) tương ứng với giá trị số nguyên truyền vào.</p> + +<pre class="brush: js">Array.of(7); // [7] +Array.of(1, 2, 3); // [1, 2, 3] + +Array(7); // [ , , , , , , ] +Array(1, 2, 3); // [1, 2, 3] +</pre> + +<h2 id="Cú_pháp"> Cú pháp</h2> + +<pre class="syntaxbox">Array.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>Các phần tử dùng để khởi tạo mảng</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Kết quả sau khi thực thi sẽ trả về một mảng mới</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Đây là một phương thức chuẩncủa ECMAScript 2015. Có thể tham khảo thêm <a href="https://gist.github.com/rwaldron/1074126"><code>Array.of</code> and <code>Array.from</code> proposal</a> và <a href="https://gist.github.com/rwaldron/3186576"><code>Array.of</code> polyfill</a>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">Array.of(1); // [1] +Array.of(1, 2, 3); // [1, 2, 3] +Array.of(undefined); // [undefined] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Nếu trình duyệt không hỗ trợ <code>Array.of()</code>, có thể gắn đoạn mã JS sau và thực thi nó trước tất cả các đoạn mã JS khác.</p> + +<pre class="brush: js">if (!Array.of) { + Array.of = function() { + return Array.prototype.slice.call(arguments); + }; +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_giữa_các_trình_duyệt">Tính tương thích giữa các trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.of")}}</p> +</div> + +<h2 id="Tham_khảo_thêm">Tham khảo thêm</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.from()")}}</li> + <li>{{jsxref("TypedArray.of()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/pop/index.html b/files/vi/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..b5740406a5 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,96 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - JavaScript + - Mảng +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>pop()</strong></code> xoá phần tử<strong> cuối cùng</strong> của một mảng và trả về phần tử đó. Phương thức này làm thay đổi độ dài của mảng.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.pop()</pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Phần tử bị xoá từ mảng; {{jsxref("undefined")}} nếu mảng rỗng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>The <code>pop</code> method removes the last element from an array and returns that value to the caller.<br> + Phương thức <code>pop</code> xoá phần tử cuối cùng của một mảng và trả về giá trị đó cho lời gọi.</p> + +<p><code>pop</code> is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} ?or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a <code>length</code> property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.</p> + +<p>Nếu bạn gọi <code>pop()</code> trên một mảng rỗng, nó trả về {{jsxref("undefined")}}.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Xoá_phần_tử_cuối_cùng_của_một_mảng">Xoá phần tử cuối cùng của một mảng</h3> + +<p>Đoạn mã sau tạo mảng <code>myFish</code> chứa 4 phần tử, sau đó xoá phần tử cuối cùng.</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; + +var popped = myFish.pop(); + +console.log(myFish); // ['angel', 'clown', 'mandarin' ] + +console.log(popped); // 'sturgeon'</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">?Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Định nghĩa lần đầu. Cài đặt trong JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/push/index.html b/files/vi/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..2b3e6cca4d --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,136 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>push()</strong></code> giúp thêm 1 hay nhiều phần tử vào cuối mảng và trả về chiều dài mới của mảng.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-push.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.push(<var>element1</var>[, ...[, <var>elementN</var>]])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>Các phần tử sẽ thêm vào cuối mảng.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Giá trị mới của thuộc tính {{jsxref("Array.length", "length")}} của mảng mà phương thức được gọi thực thi.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức <code>push</code> giúp thêm các giá trị vào mảng.</p> + +<p><code>push</code> là "intentionally generic". Phương thức này có thể được dùng với {{jsxref("Function.call", "call()")}} hoặc {{jsxref("Function.apply", "apply()")}} trên các đối tượng giống với mảng. Phương thức <code>push</code> phụ thuộc vào thuộc tính <code>length</code> để xác định vị trí bắt đầu thêm các giá trị mới. Nếu thuộc tính <code>length</code> không thể convert thành số, vị trí bắt đầu sẽ là 0. Điều này cũng bao gồm cả trường hợp thuộc tính <code>length</code> không tồn tại, khi đó <code>length</code> sẽ được tạo.</p> + +<p>Các đối tượng tương tự mảng (array-like) như {{jsxref("Global_Objects/String", "strings", "", 1)}}, không thích hợp để áp dụng phương thức này, vì các chuỗi là bất biến.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Thêm_phần_tử_vào_mảng">Thêm phần tử vào mảng</h3> + +<p>Đoạn mã dưới đây tạo mảng <code>sports</code> gồm 2 phần tử, sau đó sẽ thêm 2 phần tử vào cuối mảng này. Biến <code>total</code> có giá trị là chiều dài mới của mảng.</p> + +<pre class="brush: js">var sports = ['soccer', 'baseball']; +var total = sports.push('football', 'swimming'); + +console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] +console.log(total); // 4 +</pre> + +<h3 id="Merge_2_mảng">Merge 2 mảng</h3> + +<p>Ví dụ này sẽ sử dụng {{jsxref("Function.apply", "apply()")}} để thêm tất cả các phần tử từ mảng thứ 2 vào mảng đầu.</p> + +<p><em>Không</em> sử dụng phương thức này nếu mảng thứ 2 (trong ví dụ này là <code>moreVegs</code>) quá lớn, vì số lượng tối đa các tham số mà 1 hàm có thể nhận là giới hạn. Xem thêm chi tiết {{jsxref("Function.apply", "apply()")}}.</p> + +<pre class="brush: js">var vegetables = ['parsnip', 'potato']; +var moreVegs = ['celery', 'beetroot']; + +// Merge the second array into the first one +// Equivalent to vegetables.push('celery', 'beetroot'); +Array.prototype.push.apply(vegetables, moreVegs); + +console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot'] +</pre> + +<h3 id="Sử_dụng_một_đối_tượng_theo_kiểu_tương_tự_mảng">Sử dụng một đối tượng theo kiểu tương tự mảng</h3> + +<p>Như đã để cập ở trên, <code>push</code> là "intentionally generic", và chúng ta có thể lợi dụng điều đó. <code>Array.prototype.push</code> có thể được thực thi trên 1 đối tượng, như ví dụ dưới đây. Chú ý rằng chúng ta không tạo mảng để lưu trữ các đối tượng. Mà thay vào đó chúng ta lưu trữ trên chính bản thân đối tượng bằng cách sử dụng <code>call</code> trên <code>Array.prototype.push</code> để áp dụng phương thức như là đang thao tác với mảng, việc này có thể thực hiện được chính là nhờ cái cách mà JavaScript cho phép chúng ta thiết lập ngữ cảnh thực thi.</p> + +<pre class="brush: js">var obj = { + length: 0, + + addElem: function addElem(elem) { + // obj.length is automatically incremented + // every time an element is added. + [].push.call(this, elem); + } +}; + +// Let's add some empty objects just to illustrate. +obj.addElem({}); +obj.addElem({}); +console.log(obj.length); +// → 2 +</pre> + +<p>Chú ý rằng <code>obj</code> không phải là mảng, phương thức <code>push</code> vẫn tăng giá trị thuộc tính <code>length</code> của <code>obj</code> như khi chúng ta thao tác với 1 mảng thực sự.</p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Định nghĩa lần đầu. Hiện thực trong JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.push")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html b/files/vi/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..c665d37ad3 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,553 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>reduce()</strong></code> dùng để thực thi một hàm lên từng phần tử của mảng (từ trái sang phải) với một biến tích lũy để thu về một giá trị duy nhất.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.reduce(<var>callback[, </var><var>initialValue]</var>)</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm dùng để thực thi với từng phần tử (element) của mảng, nhận vào 04 tham số: + <dl> + <dt><code>accumulator</code></dt> + <dd>Biến tích lũy, truyền giá trị trả về của mỗi lần gọi callback; nó là giá trị tích lũy được trả về trong lần gọi callback trước, hoặc giá trị của tham số <code>initialValue</code>, nếu được cung cấp (xem bên dưới).</dd> + <dt><code>currentValue</code></dt> + <dd>Phần tử trong mảng hiện tại đang được xử lý.</dd> + <dt><code>currentIndex</code>{{optional_inline}}</dt> + <dd>Chỉ mục (index) của phần tử đang được xử lý. Bắt đầu tại 0, nếu giá trị <code>initialValue</code> được cung cấp, và tại 1 nếu không có <code>initialValue</code>.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>Mảng đang được gọi với <code>reduce()</code>.</dd> + </dl> + </dd> + <dt><code>initialValue</code>{{optional_inline}}</dt> + <dd>Giá trị cho tham số thứ nhất (<code>accumulator</code>) của hàm <code>callback</code> trong lần gọi đầu tiên. Nếu giá trị ban đầu này không được cung cấp, phần tử đầu tiên của mảng sẽ được dùng. Do đó, gọi <code>reduce()</code> trên một mảng rỗng và không có giá trị ban đầu sẽ gây ra lỗi.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Giá trị sau khi rút gọn.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>reduce()</code> thực thi hàm <code>callback</code> lên từng phần tử đang tồn tại trong mảng, bỏ qua những lỗ trống không giá trị, và nhận vào 04 tham số:</p> + +<ul> + <li><code>accumulator</code></li> + <li><code>currentValue</code></li> + <li><code>currentIndex</code></li> + <li><code>array</code></li> +</ul> + +<p>Trong lần đầu tiên <code>callback</code> được gọi, <code>accumulator</code> and <code>currentValue</code> có thể có một trong hai giá trị. Nếu tham số <code>initialValue</code> được cung cấp cho <code>reduce()</code>, thì <code>accumulator</code> sẽ bằng <code>initialValue</code>, và <code>currentValue</code> sẽ bằng phần tử đầu tiên của mảng. Nếu không có <code>initialValue</code>, <code>accumulator</code> sẽ bằng phần tử đầu tiên của mảng, và <code>currentValue</code> sẽ bằng phần tử thứ hai.</p> + +<div class="note"> +<p><strong>Ghi chú:</strong> Nếu <code>initialValue</code> không được cung cấp, <code>reduce()</code> sẽ thực thi callback bắt đầu từ index 1, bỏ qua index đầu tiên. Nếu <code>initialValue</code> được cung cấp, index sẽ bắt đầu từ 0.</p> +</div> + +<p>Nếu mảng rỗng, và <code>initialValue</code> không được cung cấp, gọi <code>reduce()</code> sẽ gây ra lỗi {{jsxref("TypeError")}}. Nếu mảng chỉ có một phần tử có giá trị (bất kể vị trí index) đồng thời không có <code>initialValue</code>, hoặc có <code>initialValue</code> nhưng mảng lại rỗng, thì giá trị duy nhất đó sẽ được trả về và <em><code>callback</code> sẽ không được gọi</em>.</p> + +<p>Sẽ an toàn hơn nếu giá trị ban đầu được cung cấp, bởi vì có đến ba khả năng xảy ra nếu không có <code>initialValue</code> như ở ví dụ sau:</p> + +<pre class="brush: js">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); +var maxCallback2 = ( max, cur ) => Math.max( max, cur ); + +// reduce() không có initialValue +[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42 +[ { x: 22 } ].reduce( maxCallback ); // { x: 22 } +[ ].reduce( maxCallback ); // TypeError + +// map/reduce; giải pháp hay hơn, và nó có thể áp dụng được cho mảng rỗng hoặc lớn hơn +[ { x: 22 }, { x: 42 } ].map( el => el.x ) + .reduce( maxCallback2, -Infinity ); +</pre> + +<h3 id="Cách_reduce()_làm_việc">Cách reduce() làm việc</h3> + +<p>Giả sử có một đoạn code với <code>reduce()</code> được hiện thực như sau:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { + return accumulator + currentValue; +}); +</pre> + +<p>Callback sẽ được gọi bốn lần, với giá trị tham số và trả về trong mỗi lần gọi như sau:</p> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">giá trị trả về</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">lần gọi thứ nhất</th> + <td><code>0</code></td> + <td><code>1</code></td> + <td>1</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ hai</th> + <td><code>1</code></td> + <td><code>2</code></td> + <td>2</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>3</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ ba</th> + <td><code>3</code></td> + <td><code>3</code></td> + <td>3</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>6</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ tư</th> + <td><code>6</code></td> + <td><code>4</code></td> + <td>4</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p>Giá trị trả về cho <code>reduce()</code> chính là giá trị trả về của lần gọi callback cuối cùng (<code>10</code>).</p> + +<p>Bạn cũng có thể cung cấp một hàm mũi tên {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} thay vì một hàm đầy đủ. Đoạn code sau đây sẽ cho kết quả giống như đoạn code ở trên:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue ); +</pre> + +<p>Nếu bạn cung cấp giá trị <code>initialValue</code> cho tham số thứ hai của hàm <code>reduce()</code>, thì kết quả sẽ như bên dưới:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { + return accumulator + currentValue; +}, 10); +</pre> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">giá trị trả về</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">lần gọi thứ nhất</th> + <td><code>10</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ hai</th> + <td><code>10</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>11</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ ba</th> + <td><code>11</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>13</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ tư</th> + <td><code>13</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>16</code></td> + </tr> + <tr> + <th scope="row">lần gọi thứ năm</th> + <td><code>16</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + </tbody> +</table> + +<p>Giá trị trả về cho <code>reduce()</code> lần này sẽ là <code>20</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tính_tổng_của_tất_cả_các_phần_tử_của_mảng">Tính tổng của tất cả các phần tử của mảng</h3> + +<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { + return accumulator + currentValue; +}, 0); +// sum is 6 + +</pre> + +<p>Tương tự, nhưng viết bằng hàm arrow function</p> + +<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( + ( accumulator, currentValue ) => accumulator + currentValue, + 0 +);</pre> + +<h3 id="Tính_tổng_các_giá_trị_bên_trong_một_mảng_các_object">Tính tổng các giá trị bên trong một mảng các object</h3> + +<p>Để tính tổng các giá trị nằm bên trong các phần tử là object, bạn <strong>phải</strong> cung cấp một giá trị ban đầu để từng phần tử đều được callback chạy qua (và <code>accumulator</code> luôn luôn là giá trị kiểu số):</p> + +<pre class="brush: js">var initialValue = 0; +var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { + return accumulator + currentValue.x; +},initialValue) + +console.log(sum) // logs 6 +</pre> + +<p>Tương tự, viết bằng arrow function:</p> + +<pre class="brush: js">var initialValue = 0; +var sum = [{x: 1}, {x:2}, {x:3}].reduce( + (accumulator, currentValue) => accumulator + currentValue.x + ,initialValue +); + +console.log(sum) // logs 6</pre> + +<h3 id="Trải_phẳng_một_mảng_chứa_nhiều_mảng_con">Trải phẳng một mảng chứa nhiều mảng con</h3> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + function(accumulator, currentValue) { + return accumulator.concat(currentValue); + }, + [] +); +// flattened is [0, 1, 2, 3, 4, 5] +</pre> + +<p>Tương tự, viết bằng arrow function:</p> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + ( accumulator, currentValue ) => accumulator.concat(currentValue), + [] +); +</pre> + +<h3 id="Đếm_số_lần_xuất_hiện_của_phần_tử_trong_mảng">Đếm số lần xuất hiện của phần tử trong mảng</h3> + +<pre class="brush: js">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; + +var countedNames = names.reduce(function (allNames, name) { + if (name in allNames) { + allNames[name]++; + } + else { + allNames[name] = 1; + } + return allNames; +}, {}); +// countedNames is: +// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } +</pre> + +<h3 id="Nhóm_các_đối_tượng_theo_giá_trị_property_nào_đó">Nhóm các đối tượng theo giá trị property nào đó</h3> + +<pre class="brush: js">var people = [ + { name: 'Alice', age: 21 }, + { name: 'Max', age: 20 }, + { name: 'Jane', age: 20 } +]; + +function groupBy(objectArray, property) { + return objectArray.reduce(function (acc, obj) { + var key = obj[property]; + if (!acc[key]) { + acc[key] = []; + } + acc[key].push(obj); + return acc; + }, {}); +} + +var groupedPeople = groupBy(people, 'age'); +// groupedPeople is: +// { +// 20: [ +// { name: 'Max', age: 20 }, +// { name: 'Jane', age: 20 } +// ], +// 21: [{ name: 'Alice', age: 21 }] +// } +</pre> + +<h3 id="Ghép_các_mảng_con_bên_trong_các_object_sử_dụng_toán_tử_spread_và_initialValue">Ghép các mảng con bên trong các object sử dụng toán tử spread và initialValue</h3> + +<pre class="brush: js">// friends - an array of objects +// where object field "books" - list of favorite books +var friends = [{ + name: 'Anna', + books: ['Bible', 'Harry Potter'], + age: 21 +}, { + name: 'Bob', + books: ['War and peace', 'Romeo and Juliet'], + age: 26 +}, { + name: 'Alice', + books: ['The Lord of the Rings', 'The Shining'], + age: 18 +}]; + +// allbooks - list which will contain all friends' books + +// additional list contained in initialValue +var allbooks = friends.reduce(function(accumulator, currentValue) { + return [...accumulator, ...currentValue.books]; +}, ['Alphabet']); + +// allbooks = [ +// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace', +// 'Romeo and Juliet', 'The Lord of the Rings', +// 'The Shining' +// ]</pre> + +<h3 id="Xóa_các_phần_tử_bị_trùng_trong_mảng">Xóa các phần tử bị trùng trong mảng</h3> + +<pre class="brush: js">let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; +let result = arr.sort().reduce((accumulator, current) => { + const length = accumulator.length + if (length === 0 || accumulator[length - 1] !== current) { + accumulator.push(current); + } + return accumulator; +}, []); +console.log(result); //[1,2,3,4,5] +</pre> + +<h3 id="Chạy_các_Promise_theo_trình_tự">Chạy các Promise theo trình tự</h3> + +<pre class="brush: js">/** + * Runs promises from array of functions that can return promises + * in chained manner + * + * @param {array} arr - promise arr + * @return {Object} promise object + */ +function runPromiseInSequence(arr, input) { + return arr.reduce( + (promiseChain, currentFunction) => promiseChain.then(currentFunction), + Promise.resolve(input) + ); +} + +// promise function 1 +function p1(a) { + return new Promise((resolve, reject) => { + resolve(a * 5); + }); +} + +// promise function 2 +function p2(a) { + return new Promise((resolve, reject) => { + resolve(a * 2); + }); +} + +// function 3 - will be wrapped in a resolved promise by .then() +function f3(a) { + return a * 3; +} + +// promise function 4 +function p4(a) { + return new Promise((resolve, reject) => { + resolve(a * 4); + }); +} + +const promiseArr = [p1, p2, f3, p4]; +runPromiseInSequence(promiseArr, 10) + .then(console.log); // 1200 +</pre> + +<h3 id="Tổ_hợp_các_hàm_và_gọi_chuyền_(piping)">Tổ hợp các hàm và gọi chuyền (piping)</h3> + +<pre class="brush: js">// Building-blocks to use for composition +const double = x => x + x; +const triple = x => 3 * x; +const quadruple = x => 4 * x; + +// Function composition enabling pipe functionality +const pipe = (...functions) => input => functions.reduce( + (acc, fn) => fn(acc), + input +); + +// Composed functions for multiplication of specific values +const multiply6 = pipe(double, triple); +const multiply9 = pipe(triple, triple); +const multiply16 = pipe(quadruple, quadruple); +const multiply24 = pipe(double, triple, quadruple); + +// Usage +multiply6(6); // 36 +multiply9(9); // 81 +multiply16(16); // 256 +multiply24(10); // 240 + +</pre> + +<h3 id="Hiện_thực_lại_map()_sử_dụng_reduce()">Hiện thực lại map() sử dụng reduce()</h3> + +<pre class="brush: js">if (!Array.prototype.mapUsingReduce) { + Array.prototype.mapUsingReduce = function(callback, thisArg) { + return this.reduce(function(mappedArray, currentValue, index, array) { + mappedArray[index] = callback.call(thisArg, currentValue, index, array); + return mappedArray; + }, []); + }; +} + +[1, 2, , 3].mapUsingReduce( + (currentValue, index, array) => currentValue + index + array.length +); // [5, 7, , 10] + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.21 +// Reference: http://es5.github.io/#x15.4.4.21 +// https://tc39.github.io/ecma262/#sec-array.prototype.reduce +if (!Array.prototype.reduce) { + Object.defineProperty(Array.prototype, 'reduce', { + value: function(callback /*, initialValue*/) { + if (this === null) { + throw new TypeError( 'Array.prototype.reduce ' + + 'called on null or undefined' ); + } + if (typeof callback !== 'function') { + throw new TypeError( callback + + ' is not a function'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // Steps 3, 4, 5, 6, 7 + var k = 0; + var value; + + if (arguments.length >= 2) { + value = arguments[1]; + } else { + while (k < len && !(k in o)) { + k++; + } + + // 3. If len is 0 and initialValue is not present, + // throw a TypeError exception. + if (k >= len) { + throw new TypeError( 'Reduce of empty array ' + + 'with no initial value' ); + } + value = o[k++]; + } + + // 8. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kPresent be ? HasProperty(O, Pk). + // c. If kPresent is true, then + // i. Let kValue be ? Get(O, Pk). + // ii. Let accumulator be ? Call( + // callbackfn, undefined, + // « accumulator, kValue, k, O »). + if (k in o) { + value = callback(value, o[k], k, o); + } + + // d. Increase k by 1. + k++; + } + + // 9. Return accumulator. + return value; + } + }); +} +</pre> + +<p>Nếu bạn thực sự cần chức năng này trên những engine JavaScript không hỗ trợ <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, bạn không nên thêm polyfill này vào <code>Array.prototype</code> bởi vì không có cách nào làm cho nó <em>không-duyệt-qua</em> (non-enumerable) được (property mới sẽ xuất hiện trong các vòng lặp for).</p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Định nghĩa lần đầu. Hiện thực trong JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.reduce")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduceRight()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html b/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html new file mode 100644 index 0000000000..7334a47f25 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html @@ -0,0 +1,347 @@ +--- +title: Array.prototype.reduceRight() +slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +tags: + - JavaScr + - Mảng + - Phương thức + - Thuộc tính +translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>reduceRight()</strong></code> đảo ngược các giá trị trong mảng (từ phải sang trái), xử lý và trả về một giá trị duy nhất.</p> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { + return a.concat(b); +}, []); + +// flattened is [4, 5, 2, 3, 0, 1] +</pre> + +<p>Xem thêm {{jsxref("Array.prototype.reduce()")}} cho việc sắp xếp từ trái qua phải.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.reduceRight(<var>callback</var>[, <var>initialValue</var>])</pre> + +<h3 id="Tham_số_truyền_vào">Tham số truyền vào</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm gọi thực thi mỗi giá trị của mảng, truyền vào 4 tham số: + <dl> + <dt><code>previousValue</code></dt> + <dd>Giá trí trả về của hàm callback sau khi xử lý phần tử trước nó hoặc là <code>initialValue, </code>nếu như nó là phần tử đầu tiên (Xem bên dưới.)</dd> + <dt><code>currentValue</code></dt> + <dd>Giá trị hiện tại đang được duyệt.</dd> + <dt><code>index</code></dt> + <dd>Chỉ số vị trí của phần tử trong mảng.</dd> + <dt><code>array</code></dt> + <dd>Mảng phần tử ban đầu.</dd> + </dl> + </dd> + <dt><code>initialValue</code></dt> + <dd>Giá trị không bắt buộc. Đối tượng sử dụng cho phần tử đầu tiền của mảng, khi mà chưa có kết quả nào từ hàm <code>callback </code>trả về.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Giá trị trả về từ việc rút gọn.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>reduceRight</code> xử lý từng phần tử trong mảng, trừ các phần tử vô giá trị (rỗng), truyền vào 4 tham số: giá trị ban đâu (or hoặc giá trị trả về sau khi xử lý một phần tử trước đó), giá trị phần tử hiện tại, vị trí phần tử hiện tại, và giá trị mảng ban đầu.</p> + +<p>Việc xử lý phần tử hiện tại sẽ làm trong dấu (...) :</p> + +<pre class="brush: js">array.reduceRight(function(previousValue, currentValue, index, array) { + // ... xử lý tại đây +}); +</pre> + +<p>Trong lần đầu xử lý, tham số <code>previousValue</code> và <code>currentValue</code> có thể là một trong hai.</p> + +<ol> + <li>Nếu tham sô <code>initialValue</code> được truyền vào <code>reduceRight</code>, thì tham số <code>previousValue</code> sẽ bằng giá trị tham số <code>initialValue (</code>nói cách khác nó chính là<code> initialValue)</code> and <code>currentValue</code> sẽ là giá trị cuối cùng của mảng.</li> + <li>Nếu tham số <code>initialValue</code> không được truyền vào, thì <code>previousValue</code> sẽ là giá trị cuối cùng của mảng và <code>currentValue</code> sẽ là giá trị cuối cùng thứ 2 của mảng ( giá trị thứ 2 tỉnh từ cuối mảng ).</li> +</ol> + +<p>Nếu mảng rỗng và không có tham số initialValue nào được truyền vào thì {{jsxref("TypeError")}} xảy ra. Nếu mảng chỉ có một phần tử (bất kể vị trí) à không có tham số initialValue nào được truyền vào, hoặc nếu <code>initialValue</code> được truyền vào nhưng mảng lại rỗng, giá trị duy nhất sẽ được trả lại mà không cần tới hàm <code>callback</code>.</p> + +<p>Một số ví dụ mô tả luồng hoạt động của <code>reduceRight</code>, bạn có thể xem :</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { + return previousValue + currentValue; +}); +</pre> + +<p>Bảng mô tả cách xử lý phần tử trong mảng ở ví dụ trên như sau:</p> + +<p><em>(*Tên gọi các tham số giữ nguyên để tiện theo dõi)</em></p> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>previousValue</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>index</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">return value</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">lần 1</th> + <td><code>4</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>7</code></td> + </tr> + <tr> + <th scope="row">lần 2</th> + <td><code>7</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>9</code></td> + </tr> + <tr> + <th scope="row">lần 3</th> + <td><code>9</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + <tr> + <th scope="row">lần 4</th> + <td><code>10</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p><code><font face="Open Sans, Arial, sans-serif">Giá trị trả về của hàm </font>reduceRight</code> sẽ là giá trị của lần thực thi cuối cùng (<code>10</code>).</p> + +<p>Và nếu bạn có đưa vào một giá trị <code>initialValue</code>, thì kết quả nó sẽ như thế này :</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { + return previousValue + currentValue; +}, 10); +</pre> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>previousValue</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>index</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">return value</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">first call</th> + <td><code>10</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>14</code></td> + </tr> + <tr> + <th scope="row">second call</th> + <td><code>14</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>17</code></td> + </tr> + <tr> + <th scope="row">third call</th> + <td><code>17</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>19</code></td> + </tr> + <tr> + <th scope="row">fourth call</th> + <td><code>19</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + <tr> + <th scope="row">fifth call</th> + <td><code>20</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + </tbody> +</table> + +<p>Và tất nhiên giá trị trả về của hàm <code>reduceRight </code>sẽ là <code>20</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tính_tổng_các_giá_trị_trong_một_mảng">Tính tổng các giá trị trong một mảng</h3> + +<pre class="brush: js">var sum = [0, 1, 2, 3].reduceRight(function(a, b) { + return a + b; +}); +// sum is 6 +</pre> + +<h3 id="Ghép_nhiều_mảng_thành_một_mảng">Ghép nhiều mảng thành một mảng</h3> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { + return a.concat(b); +}, []); +// flattened is [4, 5, 2, 3, 0, 1] +</pre> + +<h3 id="Sự_khác_nhau_giữa_reduce_và_reduceRight">Sự khác nhau giữa <code>reduce</code> và <code>reduceRight</code></h3> + +<pre class="brush: js">var a = ['1', '2', '3', '4', '5']; +var left = a.reduce(function(prev, cur) { return prev + cur; }); +var right = a.reduceRight(function(prev, cur) { return prev + cur; }); + +console.log(left); // "12345" +console.log(right); // "54321"</pre> + +<h2 id="Polyfill">Polyfill </h2> + +<p><em>Đây là thuật ngữ dùng để chỉ các đoạn code được dùng để cung cấp một chức năng (hoặc công nghệ) của các trình duyệt hiện đại cho các trình duyệt cũ. Thông qua đó, các trang web sử dụng các công nghệ mới (như HTML5) có thể chạy ổn định trên các trình duyệt cũ chưa hỗ trợ.</em></p> + +<p><code>reduceRight</code> đã được thêm vào chuẩn ECMA-262 trong lần sửa đổi thứ 5; do đó có thể nó không xuất hiện trong các trình duyệt chưa hỗ trợ nó . Bạn có thể dùng <code>reduceRight </code>bằng việc thêm đoạn mã sau vào code của bạn với khi làm việc với các trình duyệt không hỗ trợ nó.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.22 +// Reference: http://es5.github.io/#x15.4.4.22 +if ('function' !== typeof Array.prototype.reduceRight) { + Array.prototype.reduceRight = function(callback /*, initialValue*/) { + 'use strict'; + if (null === this || 'undefined' === typeof this) { + throw new TypeError('Array.prototype.reduce called on null or undefined'); + } + if ('function' !== typeof callback) { + throw new TypeError(callback + ' is not a function'); + } + var t = Object(this), len = t.length >>> 0, k = len - 1, value; + if (arguments.length >= 2) { + value = arguments[1]; + } else { + while (k >= 0 && !(k in t)) { + k--; + } + if (k < 0) { + throw new TypeError('Reduce of empty array with no initial value'); + } + value = t[k--]; + } + for (; k >= 0; k--) { + if (k in t) { + value = callback(value, t[k], k, t); + } + } + return value; + }; +} +</pre> + +<h2 id="Điều_khoản">Điều khoản</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("4.0")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="sect1"> </h2> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduce()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/reverse/index.html b/files/vi/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..19e4c5ce6d --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,124 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - JavaScript + - Mảng + - hàm +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p>Hàm <code><strong>reverse()</strong> khi gọi bởi một mảng thì</code> đảo ngược thứ tự của chính mảng đó. Phần tử đầu tiên của mảng trở thành phần tử cuối và ngược lại, phần tử cuối trở thành phần tử đầu tiên của mảng.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>arr</var>.reverse()</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<p>Không.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hàm <code>reverse</code> đảo ngược thứ tự các phần tử của bản thân mảng, thay đổi mảng, và trả về tham chiếu của mảng đó.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Đảo_ngược_thứ_tự_của_một_mảng">Đảo ngược thứ tự của một mảng</h3> + +<p>Ví dụ dưới đây tạo một mảng <code>myArray </code>chứa 3 phần tử, sau đó đảo ngược thứ tự của các phần tử trong mảng.</p> + +<pre class="brush: js">var myArray = ['one', 'two', 'three']; +myArray.reverse(); + +console.log(myArray) // ['three', 'two', 'one'] +</pre> + +<h2 id="Các_đặc_tả">Các đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu. Được cài đặt ở JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_đối_với_các_trình_duyệt">Tính tương thích đối với các trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/shift/index.html b/files/vi/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..19dd4b4aab --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,141 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Array + - JavaScript + - Method + - Mảng + - Nguyên mẫu + - Prototype + - hàm +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +<div>{{JSRef}}</div> + +<p>Hàm <code><strong>shift()</strong></code> sẽ xóa <strong>phần tử đầu tiên</strong> của một mảng và trả về phần tử đó. Hàm này sau khi thực thi sẽ làm thay đổi kích thước của mảng bị tác động.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate"><code><var>arr</var>.shift()</code></pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Phần tử đầu tiên của mảng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hàm <code>shift</code> sẽ xóa phần tử ở vị trí 0 trong mảng và dịch vị trí của các phần tử tiếp theo xuống, sau đó trả về giá trị của phần tử bị xóa. Nếu giá trị của thuộc tính {{jsxref("Array.length", "length")}} bằng 0, giá trị {{jsxref("undefined")}} được trả về.</p> + +<p><code>shift</code> is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a <code>length</code> property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Xóa_bỏ_một_phần_tử_khỏi_một_mảng">Xóa bỏ một phần tử khỏi một mảng</h3> + +<p>Đoạn mã code dưới đây hiển thị mảng <code>myFish</code> trước và sau khi xóa bỏ phần tử đầu tiên của mảng đó. Nó cũng hiển thị phần tử bị xóa bỏ:</p> + +<pre class="brush: js notranslate">var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; + +console.log('myFish before: ' + myFish); +// "myFish before: angel,clown,mandarin,surgeon" + +var shifted = myFish.shift(); + +console.log('myFish after: ' + myFish); +// "myFish after: clown,mandarin,surgeon" + +console.log('Removed this element: ' + shifted); +// "Removed this element: angel"</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Đã cài đặt từ phiên bản JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_với_trình_duyệt">Tương thích với trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Đã hỗ trợ</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Đã hỗ trợ</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm_các_mục_tương_tự">Xem thêm các mục tương tự</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/slice/index.html b/files/vi/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..ee7fd81890 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,249 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>slice()</strong></code> trả về một bản sao tham chiếu (shallow copy) một phần của một mảng dưới dạng một mảng mới nhận các giá trị có chỉ số từ <code>begin</code> dến <code>end</code> (không bao gồm <code>end</code>). Mảng ban đầu không bị thay đổi.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">Mã nguồn của đoạn demo này được lưu ở một repository trên Github. Bạn có thể giúp đỡ cho dự án này bằng cách clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi pull request cho chúng tôi.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.slice() +<var>arr</var>.slice(<em>begin</em>) +<var>arr</var>.slice(<var>begin</var>, <var>end</var>) +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>begin</code> {{optional_inline}}</dt> + <dd>Chỉ số bắt đầu chọn phần tử từ phần tử 0.</dd> + <dd>Nếu chỉ số này là số âm, được xem như tính ngược từ cuối của mảng. <code>slice(-2)</code> chọn hai phần tử cuối cùng của mảng.</dd> + <dd>Nếu <code>begin</code> là không xác định (undefined), <code>slice</code> bắt đầu từ chỉ số <code>0</code>.</dd> +</dl> + +<p> Nếu begin lớn hơn độ dài của mảng, một mảng trống được trả về.</p> + +<dl> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>Chỉ số ngừng chọn phần tử. <code>slice</code> chọn ra các phần tử có chỉ số trước chỉ số <code>end</code>.</dd> + <dd>Ví dụ, <code>slice(1,4)</code> chọn phần thử thứ hai, thứ ba và thứ tư (ở các chỉ số 1, 2, và 3).</dd> + <dd>Chỉ số âm tính ngược từ cuối mảng về. <code>slice(2,-1)</code> chọn các phần tử thứ ba cho đến phần tử sát cuối của mảng, không bao gồm phần từ cuối cùng ở chỉ số -1.</dd> + <dd>Nếu tham số <code>end</code> không được truyền vào, <code>slice</code> chọn đến cuối mảng (<code>arr.length</code>)<code>.</code></dd> + <dd>Nếu <code>end</code> lớn hơn độ dài mảng, <code>slice</code> chỉ chọn đến cuối mảng (<code>arr.length</code>).</dd> +</dl> + +<h3 id="Gia_trị_trả_về">Gia trị trả về</h3> + +<p>Một mảng mới chứa các phần tử được chọn.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>slice</code> không chỉnh sửa mảng ban đầu mà trả về bản sao tham chiếu (shallow copy, chỉ copy một cấp) phần được chọn từ mảng ban đầu. Các phần tử của mảng gốc được copy vào mảng trả về như sau:</p> + +<ul> + <li>Đối với tham chiếu đối tượng, <code>slice</code> sao chép tham chiếu của đối tượng vào mảng mới. Cả mảng ban đầu và mảng mới trả về đều tham chiếu tới chung đối tượng. Nếu đối tượng được tham chiếu thay đổi, cả hai mảng đều nhận sự thay đổi này.</li> + <li>Đối với giá trị kiểu chuỗi, số và bool, (không phải các đối tượng kiểu {{jsxref("String")}}, {{jsxref("Number")}} và {{jsxref("Boolean")}} ), <code>slice</code> sao chép các giá trị vào mảng mới. Những thay đổi đối với các giá trị kiểu chuỗi, số và bool ở mảng này không còn ảnh hưởng tới mảng kia.</li> +</ul> + +<p>Nếu một phần tử được thêm vào một trong hai mảng, mảng còn lại không bị thay đổi.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Trả_về_mảng_con_của_một_mảng">Trả về mảng con của một mảng </h3> + +<pre class="brush: js">var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; +var citrus = fruits.slice(1, 3); + +// fruits có giá trị ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +// citrus có giá trị ['Orange','Lemon'] +</pre> + +<h3 id="Sử_dụng_slice">Sử dụng <code>slice</code></h3> + +<p>Trong ví dụ sau, <code>slice</code> tạo một mảng mới, <code>newCar</code>, từ <code>myCar</code>. Cả hai chứa tham chiếu tới đối tượng <code>myHonda</code>. Khi trường color của đối tượng <code>myHonda</code> đổi sang purple, cả hai mảng đều thấy sự thay đổi này.</p> + +<pre class="brush: js">// Using slice, create newCar from myCar. +var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; +var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']; +var newCar = myCar.slice(0, 2); + +// Display the values of myCar, newCar, and the color of myHonda +// referenced from both arrays. +console.log('myCar = ' + JSON.stringify(myCar)); +console.log('newCar = ' + JSON.stringify(newCar)); +console.log('myCar[0].color = ' + myCar[0].color); +console.log('newCar[0].color = ' + newCar[0].color); + +// Change the color of myHonda. +myHonda.color = 'purple'; +console.log('The new color of my Honda is ' + myHonda.color); + +// Display the color of myHonda referenced from both arrays. +console.log('myCar[0].color = ' + myCar[0].color); +console.log('newCar[0].color = ' + newCar[0].color); +</pre> + +<p>Đoạn mã trên in ra:</p> + +<pre class="brush: js">myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, + 'cherry condition', 'purchased 1997'] +newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] +myCar[0].color = red +newCar[0].color = red +The new color of my Honda is purple +myCar[0].color = purple +newCar[0].color = purple +</pre> + +<h2 id="Các_đối_tượng_giống_kiểu_mảng">Các đối tượng giống kiểu mảng</h2> + +<p><code>slice</code> còn được dùng để thao tác với chuyển các đối tượng giống kiểu mảng (Array-like objects / collections) sang một mảng mới. Bạn chỉ cần gọi phương thức này trên đối tượng đó. Biến {{jsxref("Functions/arguments", "arguments")}} trong một hàm là ví dụ của một đối tượng kiểu mảng.</p> + +<pre class="brush: js">function list() { + return Array.prototype.slice.call(arguments); +} + +var list1 = list(1, 2, 3); // [1, 2, 3] +</pre> + +<p>Để sử dụng phương thức này, sử dụng phương thức.<code>call</code> {{jsxref("Function.prototype")}} để gọi <code>[].slice.call(arguments)</code> thay vì <code>Array.prototype.slice.call</code>. Hoặc đơn giản hơn là {{jsxref("Function.prototype.bind", "bind")}}.</p> + +<pre class="brush: js">var unboundSlice = Array.prototype.slice; +var slice = Function.prototype.call.bind(unboundSlice); + +function list() { + return slice(arguments); +} + +var list1 = list(1, 2, 3); // [1, 2, 3] +</pre> + +<h2 id="Sử_dụng_trên_nhiều_trình_duyệt">Sử dụng trên nhiều trình duyệt</h2> + +<p>Mặc dù các đối tượng trên trình duyệt (ví dụ các đối tượng DOM) không được yêu cầu theo chuẩn phải theo định nghĩa cả Mozilla khi chuyển <code>Array.prototype.slice</code> và IE < 9 không làm thế, các phiên bản IE từ bản 9 hỗ trợ phương thức này. “Shimming” giúp đảm bảo phương thức này được hỗ trợ trên các trình duyệt khác nhau. Vì các trình duyệt ngày nay tiếp tục hỗ trợ tính năng này (IE, Mozilla, Chrome, Safari, and Opera), những nhà phát triển phần mềm đọc (DOM-supporting) mã slice dựa trên shim sẽ không bị nhầm lẫn về ngữ nghĩa; họ có thể tin tưởng dựa trên ngữ nghĩa này để mang lại hành vi được xem là tiêu chuẩn này. (Mã shim sửa IE cho tham số thứ hai của <code>slice()</code> để chuyển ra giá trị {{jsxref("null")}}/{{jsxref("undefined")}} không có trong các phiên bản trước của IE nhưng các trình duyệt ngày nay đều hỗ trợ, kể cả IE >= 9.)</p> + +<pre class="brush: js">/** + * Shim for "fixing" IE's lack of support (IE < 9) for applying slice + * on host objects like NamedNodeMap, NodeList, and HTMLCollection + * (technically, since host objects have been implementation-dependent, + * at least before ES2015, IE hasn't needed to work this way). + * Also works on strings, fixes IE < 9 to allow an explicit undefined + * for the 2nd argument (as in Firefox), and prevents errors when + * called on other DOM objects. + */ +(function () { + 'use strict'; + var _slice = Array.prototype.slice; + + try { + // Can't be used with DOM elements in IE < 9 + _slice.call(document.documentElement); + } catch (e) { // Fails in IE < 9 + // This will work for genuine arrays, array-like objects, + // NamedNodeMap (attributes, entities, notations), + // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), + // and will not fail on other DOM objects (as do DOM elements in IE < 9) + Array.prototype.slice = function(begin, end) { + // IE < 9 gets unhappy with an undefined end argument + end = (typeof end !== 'undefined') ? end : this.length; + + // For native Array objects, we use the native slice function + if (Object.prototype.toString.call(this) === '[object Array]'){ + return _slice.call(this, begin, end); + } + + // For array like object we handle it ourselves. + var i, cloned = [], + size, len = this.length; + + // Handle negative value for "begin" + var start = begin || 0; + start = (start >= 0) ? start : Math.max(0, len + start); + + // Handle negative value for "end" + var upTo = (typeof end == 'number') ? Math.min(end, len) : len; + if (end < 0) { + upTo = len + end; + } + + // Actual expected size of the slice + size = upTo - start; + + if (size > 0) { + cloned = new Array(size); + if (this.charAt) { + for (i = 0; i < size; i++) { + cloned[i] = this.charAt(start + i); + } + } else { + for (i = 0; i < size; i++) { + cloned[i] = this[start + i]; + } + } + } + + return cloned; + }; + } +}()); +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Định nghĩa ban đầu. Xuất hiện ở Javascript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Độ_tương_thích_với_trình_duyệt">Độ tương thích với trình duyệt</h2> + +<div> +<div class="hidden">Bảng độ tương thích trong trang này được tạo ra từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp cho dữ liệu này, hãy gửi một cho chúng tôi một pull request đến github <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a></div> + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/some/index.html b/files/vi/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..bbc279dc5c --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,206 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +tags: + - ECMAScript 5 + - JavaScript + - Mảng + - Phương Thức + - Prototype + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>some()</strong></code> kiểm tra xem có ít nhất một phần tử của mảng thoả điều kiện ở hàm được truyền vào hay không. Kết quả trả về có kiểu <code>Boolean</code>. </p> + +<div class="note"> +<p><strong>Chú ý</strong>: Phương thức này sẽ trả về <code>false</code> nếu mảng rỗng.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/array-some.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.some(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm dùng để kiểm tra từng phần tử, nhận vào ba đối số: + <dl> + <dt><code>element</code></dt> + <dd>Phần tử đang được kiểm tra.</dd> + <dt><code>index</code> {{Optional_inline}}</dt> + <dd>Chỉ mục của phần tử đang được kiểm tra.</dd> + <dt><code>array</code>{{Optional_inline}}</dt> + <dd>Là bản thân mảng đã gọi phương thức <code>some()</code> ở trên.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{Optional_inline}}</dt> + <dd>Được sử dụng làm giá trị <code>this</code> khi thực thi hàm <code>callback</code>.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p><code><strong>true</strong></code> khi hàm <code>callback</code> trả về một giá trị {{Glossary("truthy")}} nếu có ít nhất một phần tử của mảng thoả điều kiện. Ngược lại sẽ trả về <code><strong>false</strong></code>.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức <code>some()</code> thực thi hàm <code>callback</code> một lần và lặp qua từng phần tử của mảng cho đến khi hàm <code>callback</code> trả về một giá trị <em>truthy</em> (tức là <strong><code>true</code></strong> khi được chuyển sang kiểu Boolean). Nếu như có một phần tử thoả mãn, <code>some()</code> sẽ lập tức trả về <code>true</code>. Ngược lại <code>sẽ trả về</code> <code>false</code>. <code>callback</code> được gọi chỉ khi các phần tử của mảng có giá trị.</p> + +<p><code>callback</code> được gọi với ba đối số: giá trị của phần tử, số chỉ mục của phần tử và mảng đang được lặp qua.</p> + +<p>Nếu như tham số <code>thisArg</code> được truyền vào <code>some()</code>, nó sẽ được sử dụng làm giá trị <code>this</code> của <code>callback</code>. Nếu bỏ qua, <code>this</code> sẽ có giá trị {{jsxref("undefined")}}. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p><code>some()</code> không làm thay đổi mảng ban đầu.</p> + +<p>The range of elements processed by <code>some()</code> is set before the first invocation of <code>callback</code>. Elements appended to the array after the call to <code>some()</code> begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will be the value at the time that <code>some()</code> visits that element's index. Elements that are deleted are not visited.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Kiểm_tra_giá_trị_của_các_phần_tử">Kiểm tra giá trị của các phần tử</h3> + +<p>Ví dụ bên dưới đang kiểm tra xem có phần tử nào lớn hơn 10 hay không.</p> + +<pre class="brush: js">function isBiggerThan10(element, index, array) { + return element > 10; +} + +[2, 5, 8, 1, 4].some(isBiggerThan10); // false +[12, 5, 8, 1, 4].some(isBiggerThan10); // true +</pre> + +<h3 id="Kiểm_tra_giá_trị_của_các_phần_tử_sử_dụng_arrow_function">Kiểm tra giá trị của các phần tử sử dụng arrow function</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> làm cho cú pháp trở nên gọn hơn.</p> + +<pre class="brush: js">[2, 5, 8, 1, 4].some(x => x > 10); // false +[12, 5, 8, 1, 4].some(x => x > 10); // true +</pre> + +<h3 id="Kiểm_tra_phần_tử_có_tồn_tại_trong_mảng_hay_không">Kiểm tra phần tử có tồn tại trong mảng hay không</h3> + +<p>Hàm <code>checkAvailability()</code> bên dưới đang mô phỏng lại phương thức <code>includes()</code>, trả về <code>true</code> nếu phần tử có tồn tại trong mảng:</p> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'mango', 'guava']; + +function checkAvailability(arr, val) { + return arr.some(function(arrVal) { + return val === arrVal; + }); +} + +checkAvailability(fruits, 'kela'); // false +checkAvailability(fruits, 'banana'); // true</pre> + +<h3 id="Kiểm_tra_phần_tử_có_tồn_tại_trong_mảng_hay_không_sử_dụng_arrow_function">Kiểm tra phần tử có tồn tại trong mảng hay không sử dụng arrow function</h3> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'mango', 'guava']; + +function checkAvailability(arr, val) { + return arr.some(arrVal => val === arrVal); +} + +checkAvailability(fruits, 'kela'); // false +checkAvailability(fruits, 'banana'); // true</pre> + +<h3 id="Chuyển_giá_trị_bất_kì_sang_kiểu_Boolean">Chuyển giá trị bất kì sang kiểu Boolean</h3> + +<pre class="brush: js">var TRUTHY_VALUES = [true, 'true', 1]; + +function getBoolean(value) { + 'use strict'; + + if (typeof value === 'string') { + value = value.toLowerCase().trim(); + } + + return TRUTHY_VALUES.some(function(t) { + return t === value; + }); +} + +getBoolean(false); // false +getBoolean('false'); // false +getBoolean(1); // true +getBoolean('true'); // true</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>some()</code> was added to the ECMA-262 standard in the 5th edition, and it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>some()</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>fun.call</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.17 +// Reference: http://es5.github.io/#x15.4.4.17 +if (!Array.prototype.some) { + Array.prototype.some = function(fun, thisArg) { + 'use strict'; + + if (this == null) { + throw new TypeError('Array.prototype.some called on null or undefined'); + } + + if (typeof fun !== 'function') { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + for (var i = 0; i < len; i++) { + if (i in t && fun.call(thisArg, t[i], i, t)) { + return true; + } + } + + return false; + }; +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Được đưa vào lần đầu trong JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_của_trình_duyệt">Khả năng tương thích của trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.some")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("TypedArray.prototype.some()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/splice/index.html b/files/vi/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..a942e28e67 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,161 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>splice()</strong></code> thay đổi phần tử của mảng bằng cách xóa phần tử đang tồn tại và/hoặc thêm phần tử mới.</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; + +myFish.splice(2, 0, 'drum'); // chèn 'drum' vào vị trí 2 +// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] + +myFish.splice(2, 1); // xóa 1 phần tử từ vị trí 2 +// myFish is ["angel", "clown","mandarin", "sturgeon"]</pre> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre><var>array</var>.splice(<var>start[</var>, <var>deleteCount[</var>, <var>item1[</var>, <var>item2[</var>, <em>...]]]]</em>)</pre> + +<h3 id="Các_tham_số">Các tham số </h3> + +<dl> + <dt><code>start</code></dt> + <dd>Vị trí để bắt đầu thay đổi mảng (mặc định là 0). Nếu lớn hơn độ dài của mảng, thì chỉ số <code>start</code> được thiết lập bằng độ dài của mảng. Nếu giá trị là âm , thì bắt đầu từ các phần từ cuối mảng (gốc là -1, -n ứng với vị thứ thứ n cuối cùng và viết là array.length - n) và sẽ set giá trị 0 nếu trị tuyệt đối lớn hơn độ dài mảng.</dd> + <dt><code>deleteCount</code> {{optional_inline}}</dt> + <dd>Con số chỉ định số lượng các phần tử sẽ bị xóa.</dd> + <dd>Nếu <code>deleteCount</code> bị bỏ qua hoặc có giá trị lớn hơn hoặc bằng <code>array.length - start</code> (nếu giá trị lớn hơn số phần tử còn lại của mảng, bắt đầu từ <code>start</code>), thì tất cả các phần tử từ vị trí start đến cuối mảng sẽ bị xóa bỏ.</dd> + <dd>Nếu <code>deleteCount</code> bằng 0 hoặc là số âm, không phần tử nào được xóa. Trong trường hợp này bạn sẽ phải xác định ít nhất 1 phần tử mới (xem bên dưới).</dd> + <dt><code>item1, item2, <em>...</em></code> {{optional_inline}}</dt> + <dd>Các phần tử thêm vào mảng, bắt đầu từ chỉ số <code>start</code> . Nếu không có, <code>splice()</code> thì sẽ chỉ xóa các phần tử trong mảng.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Trả về một mảng chứa các phần từ bị xóa. Nếu chỉ có 1 phần từ bị xóa, trả về mảng chứa 1 phần tử. Nếu không có phần tử nào bị xóa, trả về mảng rỗng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Nếu số các phần tử chèn vào khác với số các phần tử bị xóa đi. Mảng mới sẽ có độ dài khác.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Xóa_0_phần_tử_từ_vị_trí_số_2_và_thêm_drum">Xóa 0 phần tử từ vị trí số 2, và thêm "drum"</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2, 0, 'drum'); + +// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] +// removed is [], không có phần tử nào bị xóa +</pre> + +<h3 id="Không_xóa_phần_tử_nào_và_thêm_drum_và_guitar_tại_vị_trí_số_2">Không xóa phần tử nào và thêm "drum" và "guitar" tại vị trí số 2</h3> + + + +<pre><code> myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2, 0, 'drum', 'guitar'); + +// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] +// removed is [], no elements removed</code></pre> + + + +<h3 id="Xóa_1_phần_tử_từ_vị_trí_số_3">Xóa 1 phần tử từ vị trí số 3</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; +var removed = myFish.splice(3, 1); + +// removed is ["mandarin"] +// myFish is ["angel", "clown", "drum", "sturgeon"] +</pre> + +<h3 id="Xóa_1_phần_tử_mảng_từ_vị_trí_số_2_và_thêm_phần_tử_trumpet">Xóa 1 phần tử mảng từ vị trí số 2 , và thêm phần tử "trumpet"</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'sturgeon']; +var removed = myFish.splice(2, 1, 'trumpet'); + +// myFish is ["angel", "clown", "trumpet", "sturgeon"] +// removed is ["drum"]</pre> + +<h3 id="Xóa_2_phần_tử_mảng_từ_vị_trí_số_0_và_thêm_parrot_anemone_và_blue">Xóa 2 phần tử mảng từ vị trí số 0, và thêm "parrot", "anemone" và "blue"</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; +var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); + +// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"] +// removed is ["angel", "clown"]</pre> + +<h3 id="Xóa_2_phần_tử_mảng_từ_vị_trí_số_2">Xóa 2 phần tử mảng từ vị trí số 2 </h3> + +<pre class="brush: js">var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; +var removed = myFish.splice(myFish.length - 3, 2); + +// myFish is ["parrot", "anemone", "sturgeon"] +// removed is ["blue", "trumpet"]</pre> + +<h3 id="Xóa_1_phần_tử_mảng_từ_vị_trí_số_-2">Xóa 1 phần tử mảng từ vị trí số -2</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(-2, 1); + +// myFish is ["angel", "clown", "sturgeon"] +// removed is ["mandarin"]</pre> + +<h3 id="Xóa_mọi_phần_tử_mảng_phía_sau_vị_trí_số_2_(incl.)">Xóa mọi phần tử mảng phía sau vị trí số 2 (incl.)</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2); + +// myFish is ["angel", "clown"] +// removed is ["mandarin", "sturgeon"]</pre> + +<h2 id="Đặc_điểm_kỹ_thuật">Đặc điểm kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả kỹ thuật</th> + <th scope="col">Tình trạng</th> + <th scope="col">Chú ý</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Định nghĩa sơ khai được ghi trong JavaScript 1.2</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.splice")}}</p> +</div> + +<h2 id="Liên_quan">Liên quan</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}} — thêm/xóa phần tử từ vị trí cuối mảng</li> + <li>{{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}} — thêm/xóa phần tử từ vị trí đầu mảng</li> + <li>{{jsxref("Array.prototype.concat()", "concat()")}} — trả về mảng mới là mảng sau khi được nối với (các) mảng hoặc các giá trị khác.</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/sắp_xếp/index.html b/files/vi/web/javascript/reference/global_objects/array/sắp_xếp/index.html new file mode 100644 index 0000000000..1d01c587e0 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/sắp_xếp/index.html @@ -0,0 +1,247 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/Sắp_xếp +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>sort()</strong></code> sẽ sắp xếp các phần tử của mảng ngay tại chỗ (<em><a href="https://en.wikipedia.org/wiki/In-place_algorithm">in place</a></em>) và trả về mảng đó. Kết quả sắp xếp có thể không <a href="https://vi.wikipedia.org/wiki/Thu%E1%BA%ADt_to%C3%A1n_s%E1%BA%AFp_x%E1%BA%BFp#S%E1%BA%AFp_x%E1%BA%BFp_%E1%BB%95n_%C4%91%E1%BB%8Bnh">ổn định</a> (<a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable</a>). Cách sắp xếp mặc định là theo Unicode code point của chuỗi.</p> + +<p>Độ phức tạp về thời gian và không gian của thuật toán sắp xếp sẽ tùy vào cách hiện thực.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-sort.html")}}</div> + + + +<h2 id="Cú_Pháp">Cú Pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.sort(<var>[compareFunction]</var>) +</pre> + +<p> </p> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>compareFunction</code> {{optional_inline}}</dt> + <dd>Hàm dùng để xác định thứ tự sắp xếp. Nếu bỏ qua, mảng sẽ được sắp xếp dựa vào giá trị <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">Unicode</a> code point của từng ký tự của chuỗi được chuyển đổi từ giá trị của phần tử.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Mảng đã sắp xếp. Chú ý mảng này được sắp xếp <em><a href="https://en.wikipedia.org/wiki/In-place_algorithm">in place</a></em>, và không có bản sao được tạo.</p> + +<h2 id="Mô_Tả">Mô Tả</h2> + +<p>Nếu không truyền <code>compareFunction</code> vào, các phần tử sẽ được sẽ được quy đổi về chuỗi kí tự và được so sánh dựa trên thứ tự của chuỗi kí tự đó trong bảng mã Unicode. Chẳng hạn, "Banana" đứng trước "Cherry". Còn nếu so sánh số học, 9 đứng trước 80, nhưng bởi vì các chữ số đã được quy đổi về chuỗi kí tự, nên "80" sẽ đứng trước "9" theo bảng mã Unicode.</p> + +<p>Nếu truyền <code>compareFunction</code> vào, phần tử của mảng sẽ được sắp xếp dựa theo giá trị trả về của hàm so sánh. Nếu <code>a</code> và <code>b</code> là hai phần tử được so sánh, thì:</p> + +<ul> + <li>Nếu <code>compareFunction(a, b)</code> trả về nhỏ hơn 0, đặt chỉ số cho <code>a</code> nhỏ hơn so với chỉ số của <code>b</code>, tức là để <code>a</code> lên trước.</li> + <li>Nếu <code>compareFunction(a, b)</code> trả về 0, giữ nguyên <code>a</code> và <code>b</code>, nhưng tiếp tục so sánh lần lượt các phần tử khác của mảng. Chú ý: quy định của ECMAscript không đảm bảo hành vi này, tương tự đối với tất cả các trình duyệt (ví dụ các phiên bản của Mozilla từ 2003).</li> + <li>Nếu <code>compareFunction(a, b)</code> trả về lớn hơn 0, đặt chỉ số của <code>b</code> nhỏ hơn chỉ số của <code>a</code>, tức là để <code>b</code> lên trước.</li> + <li><code>compareFunction(a, b)</code> luôn phải trả về cùng một giá trị với mỗi cặp phần tử a và b. Nếu kết quả trả về không nhất quán thì thứ tự sắp xếp sẽ không xác định.</li> +</ul> + +<p>Ví dụ đơn giản cho hàm so sánh:</p> + +<pre class="brush: js">function compare(a, b) { + if (a nhỏ hơn b) { + return -1; + } + if (a lớn hơn b) { + return 1; + } + // a bằng b + return 0; +} +</pre> + +<p>Để so sánh giữa các số, chỉ cần lấy <code>a</code> trừ cho <code>b</code>. Hàm dưới đây sẽ sắp xếp mảng theo chiều tăng dần (nếu mảng không chứa <code>Infinity</code> và <code>NaN</code>):</p> + +<pre class="brush: js">function compareNumbers(a, b) { + return a - b; +} +</pre> + +<p>Phương thức <code>sort</code> có thể dùng dễ dàng với {{jsxref("Operators/function", "function expressions", "", 1)}} (và <a href="/en-US/docs/Web/JavaScript/Guide/Closures">closure</a>):</p> + +<pre class="brush: js">var numbers = [4, 2, 5, 1, 3]; +numbers.sort(function(a, b) { + return a - b; +}); +console.log(numbers); + +// [1, 2, 3, 4, 5] +</pre> + +<p>Các Object cũng có thể được sắp xếp với một trong những thuộc tính của chúng.</p> + +<pre class="brush: js">var items = [ + { name: 'Edward', value: 21 }, + { name: 'Sharpe', value: 37 }, + { name: 'And', value: 45 }, + { name: 'The', value: -12 }, + { name: 'Magnetic', value: 13 }, + { name: 'Zeros', value: 37 } +]; + +// ?sắp xếp theo value (giá trị) +items.sort(function (a, b) { + return a.value - b.value; +}); + +// sắp xếp theo name (tên) +items.sort(function(a, b) { + var nameA = a.name.toUpperCase(); // bỏ qua hoa thường + var nameB = b.name.toUpperCase(); // bỏ qua hoa thường + if (nameA < nameB) { + return -1; + } + if (nameA > nameB) { + return 1; + } + + // name trùng nhau + return 0; +});</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<p> </p> + +<h3 id="Tạo_hiển_thị_và_sắp_xếp_một_mảng">Tạo, hiển thị và sắp xếp một mảng</h3> + +<p>Ví dụ sau sẽ tạo bốn mảng và hiển thị chúng ở dạng nguyên bản và dạng đã được sắp xếp. Những mảng số sẽ được sắp xếp bằng cách sử dụng và không sử dụng hàm so sánh.</p> + +<pre class="brush: js">var stringArray = ['Blue', 'Humpback', 'Beluga']; +var numericStringArray = ['80', '9', '700']; +var numberArray = [40, 1, 5, 200]; +var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200]; + +function compareNumbers(a, b) { + return a - b; +} + +console.log('stringArray:', stringArray.join()); +console.log('Sorted:', stringArray.sort()); + +console.log('numberArray:', numberArray.join()); +console.log('Sorted without a compare function:', numberArray.sort()); +console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers)); + +console.log('numericStringArray:', numericStringArray.join()); +console.log('Sorted without a compare function:', numericStringArray.sort()); +console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers)); + +console.log('mixedNumericArray:', mixedNumericArray.join()); +console.log('Sorted without a compare function:', mixedNumericArray.sort()); +console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers)); +</pre> + +<p>Kết quả trả về như phía dưới. Như ta thấy, khi sử dụng hàm so sánh thì dù là ở dạng số hay dạng chuỗi kí tự, mảng luôn được sắp xếp đúng.</p> + +<pre>stringArray: Blue,Humpback,Beluga +Sorted: Beluga,Blue,Humpback + +numberArray: 40,1,5,200 +Sorted without a compare function: 1,200,40,5 +Sorted with compareNumbers: 1,5,40,200 + +numericStringArray: 80,9,700 +Sorted without a compare function: 700,80,9 +Sorted with compareNumbers: 9,80,700 + +mixedNumericArray: 80,9,700,40,1,5,200 +Sorted without a compare function: 1,200,40,5,700,80,9 +Sorted with compareNumbers: 1,5,9,40,80,200,700 +</pre> + +<h3 id="Sắp_xếp_kí_tự_ngoài_mã_ASCII">Sắp xếp kí tự ngoài mã ASCII</h3> + +<p>Để sắp xếp kí tự ngoài ASCII, ví dụ chuỗi kí tự có dấu (e, é, è, a, ä, vân vân), chuỗi kí tự thuộc ngôn ngữ không phải tiếng Anh: hãy dùng {{jsxref("String.localeCompare")}}. Hàm này có thể so sánh các kí tự đó để chúng luôn trả về thứ tự đúng.</p> + +<pre class="brush: js">var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; +items.sort(function (a, b) { + return a.localeCompare(b); +}); + +// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] +</pre> + +<h3 id="Sắp_xếp_cùng_với_map">Sắp xếp cùng với map</h3> + +<p>Hàm <code>compareFunction</code> có thể được gọi nhiều lần trên cùng một phần tử của mảng. Tuỳ thuộc vào bản chất của <code>compareFunction</code>, việc này có thể tốn nhiều chi phí ban đầu. Hàm <code>compareFunction</code> càng phức tạp và càng có nhiều phần tử phải sắp xếp, thì việc sắp xếp càng phải thông minh hơn, như là dùng thêm phương thức <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> chẳng hạn. Ý tưởng là truyền mảng vào một lần để sàng ra những phần tử cần sắp xếp và lưu chúng vào một mảng tạm, sắp xếp mảng tạm ấy rồi sàng lại mảng tạm sẽ ra được thứ tự mong muốn.</p> + +<pre class="brush: js" dir="rtl">// mảng cần sắp xếp +var list = ['Delta', 'alpha', 'CHARLIE', 'bravo']; + +// temporary array holds objects with position and sort-value +var mapped = list.map(function(el, i) { + return { index: i, value: el.toLowerCase() }; +}) + +// sorting the mapped array containing the reduced values +mapped.sort(function(a, b) { + if (a.value > b.value) { + return 1; + } + if (a.value < b.value) { + return -1; + } + return 0; +}); + +// container for the resulting order +var result = mapped.map(function(el){ + return list[el.index]; +}); +</pre> + +<h2 id="Đặc_điểm_kỹ_thuật">Đặc điểm kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Tình trạng</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<p><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 40px;"><strong>Trình duyệt tương thích</strong></span></font></p> + +<div> + + +<p>{{Compat("javascript.builtins.Array.sort")}}</p> +</div> + +<p><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 40px;"><strong>Xem thêm</strong></span></font></p> + +<ul> + <li>{{jsxref("Array.prototype.reverse()")}}</li> + <li>{{jsxref("String.prototype.localeCompare()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html b/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html new file mode 100644 index 0000000000..1c9072af63 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html @@ -0,0 +1,167 @@ +--- +title: Array.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +--- +<div>Hàm <strong>toLocaleString()</strong> trả về 1 chuỗi các phần tử trong mảng. Các phần tử này được chuyển đổi sang kiểu chuỗi nhờ hàm toLocalString và được ngăn cách với nhau bằng một xâu đặc biệt (ví dụ : dấu phẩy (,))</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.toLocaleString([<var>locales[</var>, <var>options]]</var>); +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>locales</code> {{optional_inline}}</dt> + <dd>A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the <code>locales</code> argument, see the {{jsxref("Intl")}} page.</dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd>An object with configuration properties, for numbers see {{jsxref("Number.prototype.toLocaleString()")}}, and for dates see {{jsxref("Date.prototype.toLocaleString()")}}.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A string representing the elements of the array.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_locales_and_options">Using <code>locales</code> and <code>options</code></h3> + +<p>The elements of the array are converted to strings using their <code>toLocaleString</code> methods.</p> + +<ul> + <li><code>Object</code>: {{jsxref("Object.prototype.toLocaleString()")}}</li> + <li><code>Number</code>: {{jsxref("Number.prototype.toLocaleString()")}}</li> + <li><code>Date</code>: {{jsxref("Date.prototype.toLocaleString()")}}</li> +</ul> + +<p>Always display the currency for the strings and numbers in the <code>prices</code> array:</p> + +<pre class="brush: js">var prices = ['¥7', 500, 8123, 12]; +prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }); + +// "¥7,¥500,¥8,123,¥12" +</pre> + +<p>For more examples, see also the {{jsxref("Intl")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} pages.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring +if (!Array.prototype.toLocaleString) { + Object.defineProperty(Array.prototype, 'toLocaleString', { + value: function(locales, options) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var a = Object(this); + + // 2. Let len be ? ToLength(? Get(A, "length")). + var len = a.length >>> 0; + + // 3. Let separator be the String value for the + // list-separator String appropriate for the + // host environment's current locale (this is + // derived in an implementation-defined way). + // NOTE: In this case, we will use a comma + var separator = ','; + + // 4. If len is zero, return the empty String. + if (len === 0) { + return ''; + } + + // 5. Let firstElement be ? Get(A, "0"). + var firstElement = a[0]; + // 6. If firstElement is undefined or null, then + // a.Let R be the empty String. + // 7. Else, + // a. Let R be ? + // ToString(? + // Invoke( + // firstElement, + // "toLocaleString", + // « locales, options » + // ) + // ) + var r = firstElement == null ? + '' : firstElement.toLocaleString(locales, options); + + // 8. Let k be 1. + var k = 1; + + // 9. Repeat, while k < len + while (k < len) { + // a. Let S be a String value produced by + // concatenating R and separator. + var s = r + separator; + + // b. Let nextElement be ? Get(A, ToString(k)). + var nextElement = a[k]; + + // c. If nextElement is undefined or null, then + // i. Let R be the empty String. + // d. Else, + // i. Let R be ? + // ToString(? + // Invoke( + // nextElement, + // "toLocaleString", + // « locales, options » + // ) + // ) + r = nextElement == null ? + '' : nextElement.toLocaleString(locales, options); + + // e. Let R be a String value produced by + // concatenating S and R. + r = s + r; + + // f. Increase k by 1. + k++; + } + + // 10. Return R. + return r; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}</td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sup-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.toLocaleString")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("Intl")}}</li> + <li>{{jsxref("Object.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Number.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date.prototype.toLocaleString()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/tostring/index.html b/files/vi/web/javascript/reference/global_objects/array/tostring/index.html new file mode 100644 index 0000000000..c62919e81e --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/tostring/index.html @@ -0,0 +1,75 @@ +--- +title: Array.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toString +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>toString()</strong></code>trả về một chuỗi string đại diện cho mảng được chỉ định và các phần tử trong mảng đó.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-tostring.html")}}</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.toString()</pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chuỗi string đại diện cho mảng được chỉ định và các phần tử trong mảng đó.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Đối tượng {{jsxref("Array")}} ghi đè phương thức <code>toString</code> của {{jsxref("Object")}}. Đối với các array objects, phương thức <code>toString</code> nối mảng lại và trả về một chuỗi string chứa các phần tử trong mảng và được ngăn cách bởi dấu phẩy.</p> + +<p>Javascript tự động gọi phương thức <code>toString</code> khi một mảng được biểu diễn dưới dạng text hoặc khi một mảng được tham chiếu trong một string concate</p> + +<h3 id="ECMAScript_5_semantics">ECMAScript 5 semantics</h3> + +<p>Bắt đầu từ JavaScript 1.8.5 (Firefox 4), và phù hợp với ngữ nghĩa của ECMAScript 5th, phương thức <code>toString() </code>là phương thức chung và có thể sử dụng với bất cứ object nào. {{jsxref("Object.prototype.toString()")}} sẽ được gọi và giá trị kết quả sẽ được trả về.</p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu. Được triển khai trong JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_với_trình_duyệt_web">Tương thích với trình duyệt web</h2> + +<div> +<div class="hidden">Bảng tương thích trong trang này được tạo từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp dữ liệu, vui lòng kiểm tra <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi pull request cho chúng tôi.</div> + +<p>{{Compat("javascript.builtins.Array.toString")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/unshift/index.html b/files/vi/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..580bd9bca3 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,119 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +<div>{{JSRef}}</div> + +<p>Phương thức unshift() thêm một hoặc nhiều phần tử vào vị trí đầu mảng sau đó trả về chiều dài của mảng mới.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-unshift.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.unshift(<var>element1</var>[, ...[, <var>elementN</var>]])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>Các phần tử được thêm vào đầu mảng.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Trả về độ dài mới của mảng {{jsxref("Array.length", "length")}} sau khi thực hiện thêm phần tử.</p> + +<h2 id="Description">Description</h2> + +<p>Phương thức <code>unshift</code> sẽ thêm vào đầu mảng các giá trị được truyền vào.</p> + +<p><code>unshift</code> là "intentionally generic"; Phương thức này có thể được {{jsxref("Function.call", "gọi", "", 1)}} or {{jsxref("Function.apply", "áp dụng", "", 1)}} đối với các đối tượng giống như mảng. Objects which do not contain a <code>length</code> property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.</p> + +<p>Chú ý rằng, Nếu truyền nhiều phần tử vào cùng lức như một biến, chúng sẽ được thêm vào vị trí đầu tiên của mảng, theo đúng vị trí ban đầu mà chúng được truyền vào. Việc gọi phương thức unshift với n phần tử trong một lần sẽ không trả về cùng kết quả (vị trí các phần tử) so với việc gọi n lần với mỗi lần 1 phần tử.</p> + +<p>Xem ví dụ bên dưới</p> + +<pre class="syntaxbox notranslate">let arr = [4,5,6]; + +arr.unshift(1,2,3); +console.log(arr); +// [<strong>1, 2, 3</strong>, 4, 5, 6] + +arr = [4,5,6]; // resetting the array + +arr.unshift(1); +arr.unshift(2); +arr.unshift(3); + +console.log(arr); +// [<strong>3, 2, 1</strong>, 4, 5, 6] +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_unshift">Using unshift</h3> + +<pre class="brush: js notranslate">let arr = [1, 2]; + +arr.unshift(0); // result of the call is 3, which is the new array length +// arr is [0, 1, 2] + +arr.unshift(-2, -1); // the new array length is 5 +// arr is [-2, -1, 0, 1, 2] + +arr.unshift([-4, -3]); // the new array length is 6 +// arr is [[-4, -3], -2, -1, 0, 1, 2] + +arr.unshift([-7, -6], [-5]); // the new array length is 8 +// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.unshift")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/array/values/index.html b/files/vi/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..9460fdfbc3 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,113 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +<div>{{JSRef}}</div> + +<p>Method <strong><code>values()</code></strong>trả về một <strong><code>Array Iterator</code></strong> object chứa các giá trị của mỗi index trong mảng.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-values.html")}}</div> + +<h2 id="Cú_Pháp">Cú Pháp</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.values()</pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một object {{jsxref("Array")}} lặp lại mới.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_vòng_lặp_for...of_loop">Sử dụng vòng lặp for...of loop</h3> + +<pre class="brush: js notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; +var iterator = arr.values(); + +for (let letter of iterator) { + console.log(letter); +} //"a" "b" "c" "d" "e" +</pre> + +<p><strong>Array.prototype.values</strong> là triển khai mặc định của <strong>Array.prototype[Symbol.iterator]</strong>.</p> + +<pre class="notranslate">Array.prototype.values === Array.prototype[Symbol.iterator] //true</pre> + +<h3 id="Sử_dụng_vòng_lặp_.next">Sử dụng vòng lặp .next()</h3> + +<pre class="brush: js notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; +var iterator = arr.values(); +iterator.next(); // Object { value: "a", done: false } +iterator.next().value; // "b" +iterator.next()["value"]; // "c" +iterator.next(); // Object { value: "d", done: false } +iterator.next(); // Object { value: "e", done: false } +iterator.next(); // Object { value: undefined, done: true } +iteraror.next().value; // undefined </pre> + +<div class="blockIndicator warning"> +<p>Sử dụng một lần: đối tượng trình lặp mảng là một đối tượng sử dụng một lần hoặc tạm thời</p> +</div> + +<p>Ví dụ:</p> + +<pre class="brush: js notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; + var iterator = arr.values(); + for (let letter of iterator) { + console.log(letter); +} //"a" "b" "c" "d" "e" +for (let letter of iterator) { +console.log(letter); +} // undefined +</pre> + +<p><strong>Lý do:</strong> khi <code>next().done=true</code> hoặc <code>currentIndex>length</code> thì vòng lặp <code>for..of</code> kết thúc. Xem tại <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols.</a></p> + +<p><strong>Giá trị</strong>: không có giá trị nào được lưu trữ trong object lặp mảng; thay vào đó, nó lưu trữ địa chỉ của mảng được sử dụng trong quá trình tạo của nó và do đó phụ thuộc vào các giá trị được lưu trữ trong mảng đó.</p> + +<pre class="brush: js notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; +var iterator = arr.values(); +console.log(iterator); // Array Iterator { } +iterator.next().value; // "a" +arr[1]='n'; +iterator.next().value; // "n" +</pre> + +<div class="blockIndicator note"> +<p>nếu các giá trị trong mảng thay đổi thì các giá trị trong mảng lặp cũng thay đổi.</p> +</div> + +<p class="hidden"><strong>TODO</strong>: please write about why we need it, use cases.</p> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Thông số kỹ thuật</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_của_trình_duyệt_web">Tính tương thích của trình duyệt web</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.values")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html b/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..1cf512233b --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,141 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<div>Đối tượng <strong><code>ArrayBuffer</code></strong> được sử dụng để biểu diễn một bộ đệm dữ liệu nhị phân nguyên gốc có độ dài cố định. Ta không thể trực tiếp thay đổi nội dung của một <code>ArrayBuffer</code>; mà thay vào đó là tạo ra một <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> hoặc một đối tượng {{jsxref("DataView")}} đại diện cho bộ đệm với một định dạng cụ thể, và sử dụng nó để đọc và ghi nội dung của bộ đệm.</div> + +<div> </div> + +<div>{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">new ArrayBuffer(length) +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>length</code></dt> + <dd>Kích thước tính theo bytes của bộ đệm mảng cần tạo</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p><code><font face="Verdana, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Là một </span></font>ArrayBuffer</code> mới có kích thước được chỉ định. Nội dung khởi tạo là 0.</p> + +<h3 id="Ngoại_lệ">Ngoại lệ</h3> + +<p>Lỗi {{jsxref("RangeError")}} sẽ được đưa ra nếu <code>length</code> lớn hơn {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) hoặc mang giá trị âm.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hàm dựng <code>ArrayBuffer</code> tạo ra một <code>ArrayBuffer</code> dựa trên chiều dài đã cho tính theo byte</p> + +<h3 id="Lấy_một_mảng_đệm_từ_dữ_liệu_hiện_có">Lấy một mảng đệm từ dữ liệu hiện có</h3> + +<ul> + <li><a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">From a Base64 string</a></li> + <li><a href="/en-US/docs/Web/API/FileReader#readAsArrayBuffer()">From a local file</a></li> +</ul> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt><code>ArrayBuffer.length</code></dt> + <dd>Thuộc tính chiều dài của hàm dựng của <code>ArrayBuffer</code> có giá trị là 1.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>Hàm dựng để tạo ra các đối tượng kế thừa</dd> + <dt>{{jsxref("ArrayBuffer.prototype")}}</dt> + <dd>Cho phép bổ sung các thuộc tính cho tất cả các đối tượng <code>ArrayBuffer</code> .</dd> +</dl> + +<h2 id="Phương_thức">Phương thức</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> + <dd>Trả về <code>true</code> nếu tham số <code>arg</code> là một trong các views của ArrayBuffer, ví dụ như <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> hoặc {{jsxref("DataView")}}. Trả về <code>false</code> trong trường hợp ngược lại.</dd> + <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}</dt> + <dd> + <div class="line" id="file-arraybuffer-transfer-LC6">Trả về một <code>ArrayBuffer</code> nội dung lấy từ dữ liệu của <code>oldBuffer</code> và sau đó được cắt bớt hoặc không mở rộng thông qua <code>newByteLength</code>.</div> + </dd> +</dl> + +<h2 id="Thực_thể">Thực thể</h2> + +<p>Tất cả các thực thể của <code>ArrayBuffer</code> đều kế thừa từ {{jsxref("ArrayBuffer.prototype")}}.</p> + +<h3 id="Thuộc_tính_2">Thuộc tính</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}</p> + +<h3 id="Phương_thức_2">Phương thức</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}</p> + +<dl> + <dt>{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}</dt> + <dd>Cùng chức năng như {{jsxref("ArrayBuffer.prototype.slice()")}}.</dd> +</dl> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<p>Ví dụu sau tạo ra một vùng đệm 8 byte với view của {{jsxref("Global_Objects/Int32Array", "Int32Array")}} ?trỏ đến bộ đệm</p> + +<pre class="brush: js">var buffer = new ArrayBuffer(8); +var view = new Int32Array(buffer);</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>?Thay thế bởi ECMAScript 6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard. Specified that <code>new</code> is required.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + + + +<p>{{Compat("javascript.builtins.ArrayBuffer")}}</p> + +<h2 id="Ghi_chú_thêm_về_tính_tương_thích">Ghi chú thêm về tính tương thích</h2> + +<p>Với ECMAScript 2015, hàm dựng <code>ArrayBuffer</code> cần được khởi tạo với {{jsxref("Operators/new", "new")}}. Việc gọi một hàm dựng <code>ArrayBuffer</code> nhưng một hàm thông thường không có toán tử <code>new</code> sẽ gây ra lỗi {{jsxref("TypeError")}}.</p> + +<pre class="brush: js example-bad">var dv = ArrayBuffer(10); +// TypeError: calling a builtin ArrayBuffer constructor +// without new is forbidden</pre> + +<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> + +<h2 id="Tham_khảo_thêm">Tham khảo thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/date/index.html b/files/vi/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..7e485400e4 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,260 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - JavaScript + - Vietnamese +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +<div>{{JSRef}}</div> + +<p>Tạo ra một thể hiện JavaScript <strong>Date</strong> đại diện cho một khoảnh khắc trong thời gian. Đối tượng ngày được dựa trên giá trị thời gian là số mili giây kể từ ngày 1 tháng 1 năm 1970 UTC.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">new Date(); +new Date(<var>value</var>); +new Date(<var>dateString</var>); +new Date(<var>year</var>, <var>month</var>[, <var>date</var>[, <var>hours</var>[, <var>minutes</var>[, <var>seconds</var>[, <var>milliseconds</var>]]]]]); +</pre> + +<div class="note"> +<p><strong>Lưu ý:</strong> Đối tượng JavaScript Date chỉ có thể được khởi tạo bằng cách gọi JavaScript Date như một constructor: gọi nó như là một hàm thông thường (tức là không có toán tử {{jsxref ("Operators / new", "new")}}) sẽ trả về một chuỗi thay vì một tượng Date; không giống như các kiểu đối tượng JavaScript khác, đối tượng JavaScript Date không có cú pháp rút gọn.</p> +</div> + +<h3 id="Các_tham_số">Các tham số</h3> + +<div class="note"> +<p><strong>Chú ý:</strong> Trường hợp Date được gọi như một hàm khởi tạo với nhiều hơn một đối số, nếu các giá trị lớn hơn phạm vi hợp lý của chúng (ví dụ: 13 được cung cấp như là giá trị tháng hoặc 70 cho giá trị phút) thì giá trị liền kề sẽ được điều chỉnh. Ví dụ, <code>new Date(2013, 13, 1)</code> tương đương với <code>new Date(2014, 1, 1)</code>, cả hai đều tạo ra một ngày cho <code>2014-02-01</code> (lưu ý rằng tháng này là 0). Tương tự cho các giá trị khác: <code>new Date(2013, 2, 1, 0, 70)</code> tương đương với <code>new Date(2013, 2, 1, 1, 10)</code> mà cả hai đều tạo ra một ngày cho <code>2013-03-01T01:10:00</code>.</p> +</div> + +<div class="note"> +<p><strong>Chú ý:</strong> Trường hợp Date được gọi như một hàm khởi tạo với nhiều hơn một đối số, các đối số xác định đại diện cho thời gian địa phương. Nếu UTC là mong muốn, sử dụng Date mới ({{jsxref ("Date.UTC ()", "Date.UTC (...)")}}) với cùng một đối số.</p> +</div> + +<dl> + <dt><code>value</code></dt> + <dd>Giá trị số nguyên đại diện cho số mili giây kể từ 01/01/1970-00:00:00 UTC.</dd> + <dt><code>dateString</code></dt> + <dd>Giá trị chuỗi đại diện cho một ngày. Chuỗi phải ở định dạng được công nhận bới phương thức {{jsxref("Date.parse()")}}. + <div class="note"> + <p><strong>Lưu ý:</strong> Việc phân tách chuỗi ngày với constructor <code>Date</code> (và <code>Date.parse</code>, chúng là tương đương) đôi khi không như mong muốn do sự khác biệt và sự không nhất quán của trình duyệt. Hỗ trợ cho các chuỗi định dạng RFC 2822 chỉ là theo quy ước. Hỗ trợ các định dạng ISO 8601 khác với chuỗi "chỉ có ngày" (ví dụ: "1970-01-01") được coi như là UTC chứ không phải địa phương.</p> + </div> + </dd> + <dt><code>year</code></dt> + <dd>Giá trị số nguyên đại diện cho năm. Các giá trị từ 0 đến 99 ứng với các năm từ 1900 đến 1999.</dd> + <dt><code>month</code></dt> + <dd>Giá trị số nguyên đại diện cho tháng, bắt đầu với 0 cho Tháng Một đến 11 cho Tháng Mười Hai.</dd> + <dt><code>date</code></dt> + <dd>Tùy chọn. Giá trị số nguyên đại diện cho ngày trong tháng.</dd> + <dt><code>hours</code></dt> + <dd>Tùy chọn. Giá trị số nguyên đại diện cho giờ trong ngày.</dd> + <dt><code>minutes</code></dt> + <dd>Tùy chọn. Giá trị số nguyên đại diện cho phần phút của một thời gian.</dd> + <dt><code>seconds</code></dt> + <dd>Tùy chọn. Giá trị số nguyên đại diện cho phần giây của một thời gian.</dd> + <dt><code>milliseconds</code></dt> + <dd>Tùy chọn. Giá trị số nguyên đại diện cho phần mili giây của một thời gian.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<ul> + <li>Nếu không có các đối số được cung cấp, các hàm khởi tạo tạo đối tượng JavaScript <code>Date</code> với ngày và giờ hiện tại theo các cài đặt hệ thống.</li> + <li>Nếu có ít nhất hai đối số được cung cấp, thiếu các đối số được đặt thành 1 (nếu thiếu ngày) hoặc 0 cho tất cả các đối số khác.</li> + <li>Ngày JavaScript được dựa trên giá trị thời gian là mili giây kể từ nửa đêm 01 tháng 1 năm 1970 UTC. Một ngày giữ 86.400.000 mili giây. Phạm vi đối tượng JavaScript <code>Date</code> là -100.000.000 ngày đến 100.000.000 ngày liên quan đến ngày 01 tháng 1 năm 1970 UTC.</li> + <li>Đối tượng JavaScript Date cung cấp hành vi thống nhất giữa các nền tảng. Giá trị thời gian có thể được truyền giữa các hệ thống để tạo ra một ngày đại diện cho cùng một thời điểm trong thời gian.</li> + <li>Đối tượng JavaScript <code>Date</code> hỗ trợ một số phương pháp UTC (phổ quát), cũng như các phương pháp thời gian địa phương. UTC, còn được gọi là <em>Greenwich Mean Time</em> (GMT), nghĩa là thời gian theo World Time Standard (Tiêu chuẩn Thời gian Thế giới). Thời gian địa phương là thời gian được biết đến với máy tính nơi thực hiện lệnh JavaScript.</li> + <li>Gọi JavaScript <code>Date</code> như một hàm (nghĩa là không có toán tử {{jsxref("Operators/new", "new")}}) sẽ trả về một chuỗi đại diện cho ngày và giờ hiện tại.</li> +</ul> + +<h2 id="Các_thuộc_tính">Các thuộc tính</h2> + +<dl> + <dt>{{jsxref("Date.prototype")}}</dt> + <dd>Cho phép thêm thuộc tính vào một đối tượng JavaScript <code>Date</code>.</dd> + <dt><code>Date.length</code></dt> + <dd>Giá trị của <code>Date.length</code> là 7. Đây là số lượng các đối số được xử lý bởi hàm khởi tạo.</dd> +</dl> + +<h2 id="Các_phương_thức">Các phương thức</h2> + +<dl> + <dt>{{jsxref("Date.now()")}}</dt> + <dd>Trả về giá trị số tương ứng với thời gian hiện tại - số mili giây trôi qua kể từ ngày 1 tháng 1 năm 1970, 00:00:00, giờ UTC, với giây phút nhuận được bỏ qua.</dd> + <dt>{{jsxref("Date.parse()")}}</dt> + <dd>Phân tích cú pháp của một chuỗi đại diện ngày tháng và trả về số mili giây kể từ ngày 1 tháng 1 năm 1970, 00:00:00, giờ UTC, với giây phút nhuận được bỏ qua. + <div class="note"> + <p><strong>Note:</strong> Việc phân tách cú pháp với Date.parse rất không chính xác do sự khác biệt giữa trình duyệt và sự không nhất quán..</p> + </div> + </dd> + <dt>{{jsxref("Date.UTC()")}}</dt> + <dd>Chấp nhận các tham số giống với dạng dài nhất của hàm khởi tạo (tức là 2 đến 7) và trả về số mili giây kể từ ngày 1 tháng 1 năm 1970, 00:00:00 giờ UTC, với giây phút nhuận được bỏ qua.</dd> +</dl> + +<h2 id="Thể_hiện_của_JavaScript_Date">Thể hiện của JavaScript <code>Date</code></h2> + +<p>Tất cả thể hiện của <code>Date</code> kế thừa từ {{jsxref("Date.prototype")}}. Đối tượng nguyên mẫu của hàm khởi tạo <code>Date</code> có thể được sửa đổi để ảnh hưởng đến tất cả thể hiện của <code>Date</code>.</p> + +<h3 id="Date.prototype_Methods">Date.prototype Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}</div> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<h3 id="Một_số_cách_để_tạo_một_đối_tượng_Date">Một số cách để tạo một đối tượng <code>Date</code></h3> + +<p>Các ví dụ sau đây cho thấy một số cách để tạo các ngày JavaScript:</p> + +<div class="note"> +<p><strong>Chú ý:</strong> Việc phân tích các chuỗi ngày với constructor Date (và Date.parse, chúng là tương đương) rất không chính xác do sự khác biệt và sự không nhất quán của trình duyệt.</p> +</div> + +<pre class="brush: js">var today = new Date(); +var birthday = new Date('October 30, 1996 15:27:08'); +var birthday = new Date('1996-10-30T15:27:08'); +var birthday = new Date(1996, 10, 30); +var birthday = new Date(1996, 10, 30, 15, 27, 8); +</pre> + +<h3 id="Các_năm_hai_số_ứng_với_1900_-_1999">Các năm hai số ứng với 1900 - 1999</h3> + +<p>Để tạo và lấy các ngày giữa các năm 0 đến 99 các phương thức {{jsxref("Date.prototype.setFullYear()")}} và {{jsxref("Date.prototype.getFullYear()")}} nên được sử dụng.</p> + +<pre class="brush: js">var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT). + +// Phương thức bị phản đối, 98 ứng với 1998 ở đây cũng vậy. +date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT). + +date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST). +</pre> + +<h3 id="Tính_thời_gian_trôi_qua">Tính thời gian trôi qua</h3> + +<p>Các ví dụ sau chỉ ra cách xác định thời gian trôi qua giữa hai ngày JavaScript trong mili giây.</p> + +<p>Do những ngày dài khác nhau (do thay đổi ánh sáng ban ngày), tháng và năm, thể hiện thời gian trôi qua theo đơn vị lớn hơn giờ, phút và giây đòi hỏi phải giải quyết một số vấn đề và cần được nghiên cứu kỹ trước khi cố gắng thử.</p> + +<pre class="brush: js">// using Date objects +var start = Date.now(); + +// the event to time goes here: +doSomethingForALongTime(); +var end = Date.now(); +var elapsed = end - start; // elapsed time in milliseconds +</pre> + +<pre class="brush: js">// using built-in methods +var start = new Date(); + +// the event to time goes here: +doSomethingForALongTime(); +var end = new Date(); +var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds +</pre> + +<pre class="brush: js">// to test a function and get back its return +function printElapsedTime(fTest) { + var nStartTime = Date.now(), + vReturn = fTest(), + nEndTime = Date.now(); + + console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds'); + return vReturn; +} + +yourFunctionReturn = printElapsedTime(yourFunction); +</pre> + +<div class="note"> +<p><strong>Chú ý:</strong> Trong các trình duyệt hỗ trợ {{domxref("window.performance", "API Hiệu suất Web", "", 1)}} tính năng thời gian có độ phân giải cao, {{domxref("Performance.now()")}} có thể cung cấp các phép đo đáng tin cậy và chính xác về thời gian trôi qua hơn {{jsxref("Date.now()")}}.</p> +</div> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc điểm kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu. Được thực hiện trong JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_trình_duyệt">Khả năng tương thích trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Đặc tính</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [2]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [1]</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Đặc tính</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Một số trình duyệt có thể gặp sự cố khi phân tích ngày tháng: <a href="http://dygraphs.com/date-formats.html">3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings</a>.</p> + +<p>[2] <a href="https://msdn.microsoft.com/en-us//library/ie/ff743760(v=vs.94).aspx">ISO8601 Date Format is not supported</a> Trong Internet Explorer 8, và các phiên bản khác có thể có <a href="http://dygraphs.com/date-formats.html">vấn đề chuyển đổi ngày tháng</a>.</p> diff --git a/files/vi/web/javascript/reference/global_objects/date/parse/index.html b/files/vi/web/javascript/reference/global_objects/date/parse/index.html new file mode 100644 index 0000000000..34b139a8f0 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/date/parse/index.html @@ -0,0 +1,202 @@ +--- +title: Date.parse() +slug: Web/JavaScript/Reference/Global_Objects/Date/parse +translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>Date.parse()</code></strong> phân tích cú pháp của một chuỗi đại diện của một ngày và trả về số mili giây kể từ 01 tháng 01 năm 1970, 00:00:00 UTC hoặc NaN nếu chuỗi không nhận dạng được hoặc trong một số trường hợp, chứa các giá trị ngày không hợp lệ (ví dụ 2015-02-31).</p> + +<p>It is not recommended to use <code>Date.parse</code> as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).</p> + +<div>{{EmbedInteractiveExample("pages/js/date-parse.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<p>Direct call:</p> + +<pre class="syntaxbox">Date.parse(<var>dateString</var>) +</pre> + +<p>Implicit call:</p> + +<pre class="syntaxbox">new Date(<var>dateString</var>) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>dateString</code></dt> + <dd>A string representing <a href="#Date_Time_String_Format"> a simplification of the ISO 8601 calendar date extended format</a> (other formats may be used, but results are implementation-dependent).</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, {{jsxref("NaN")}} is returned.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>parse()</code> method takes a date string (such as <code>"2011-10-10T14:48:00"</code>) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the {{jsxref("Date.prototype.setTime()", "setTime()")}} method and the {{jsxref("Global_Objects/Date", "Date")}} object.</p> + +<h3 id="Date_Time_String_Format">Date Time String Format</h3> + +<p>The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format (see <a href="https://tc39.github.io/ecma262/#sec-date-time-string-format">Date Time String Format</a> section in the ECMAScript specification for more details). For example, <code>"2011-10-10"</code> (date-only form), <code>"2011-10-10T14:48:00"</code> (date-time form), or <code>"2011-10-10T14:48:00.000+09:00"</code> (date-time form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.</p> + +<p>While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or <code>NaN</code>.</p> + +<p>Because <code>parse()</code> is a static method of {{jsxref("Date")}}, it is called as <code>Date.parse()</code> rather than as a method of a {{jsxref("Date")}} instance.</p> + +<h3 id="Fall-back_to_implementation-specific_date_formats">Fall-back to implementation-specific date formats</h3> + +<div class="blockIndicator note"> +<p>This section contains implementation-specific behavior that can be inconsistent across implementations.</p> +</div> + +<p>The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause <code>Date.parse()</code> to return {{jsxref("NaN")}}.</p> + +<p>However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in {{jsxref("NaN")}}, depending on the browser and values provided, e.g.:</p> + +<pre class="brush: js">// Non-ISO string with invalid date values +new Date('23/25/2014'); +</pre> + +<p>will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return {{jsxref("NaN")}} in all browsers compliant with ES5 and later:</p> + +<pre class="brush: js">// ISO string with invalid values +new Date('2014-25-23').toISOString(); +// returns "RangeError: invalid date" in all es5 compliant browsers +</pre> + +<p>SpiderMonkey's implementation-specific heuristic can be found in <a href="https://dxr.mozilla.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889"><code>jsdate.cpp</code></a>. The string <code>"10 06 2014"</code> is an example of a non–conforming ISO format and thus falls back to a custom routine. See also this <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6">rough outline</a> on how the parsing works.</p> + +<pre class="brush: js">new Date('10 06 2014'); +</pre> + +<p>will be treated as a local date of 6 October, 2014 and not 10 June, 2014. Other examples:</p> + +<pre class="brush: js">new Date('foo-bar 2014').toString(); +// returns: "Invalid Date" + +Date.parse('foo-bar 2014'); +// returns: NaN +</pre> + +<h3 id="Differences_in_assumed_time_zone">Differences in assumed time zone</h3> + +<div class="blockIndicator note"> +<p>This section contains implementation-specific behavior that can be inconsistent across implementations.</p> +</div> + +<p>Given a non-standard date string of <code>"March 7, 2014"</code>, <code>parse()</code> assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as <code>"2014-03-07"</code>, it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore {{jsxref("Date")}} objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Date.parse()">Using <code>Date.parse()</code></h3> + +<p>The following calls all return <code>1546300800000</code>. The first according to ES5 will imply UTC time, and the others are specifying UTC timezone via the ISO date specification (<code>Z</code> and <code>+00:00</code>)</p> + +<pre class="brush: js">Date.parse("2019-01-01") +Date.parse("2019-01-01T00:00:00.000Z") +Date.parse("2019-01-01T00:00:00.000+00:00") +</pre> + +<p>The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system.</p> + +<pre class="brush: js">Date.parse("2019-01-01T00:00:00") +</pre> + +<h3 id="Non-standard_date_strings">Non-standard date strings</h3> + +<div class="blockIndicator note"> +<p>This section contains implementation-specific behavior that can be inconsistent across implementations.</p> +</div> + +<p>If <code>IPOdate</code> is an existing {{jsxref("Date")}} object, it can be set to August 9, 1995 (local time) as follows:</p> + +<pre class="brush: js">IPOdate.setTime(Date.parse('Aug 9, 1995')); +</pre> + +<p>Some other examples of parsing non–standard date strings:</p> + +<pre class="brush: js">Date.parse('Aug 9, 1995'); +</pre> + +<p>Returns <code>807937200000</code> in time zone GMT-0300, and other values in other time zones, since the string does not specify a time zone and is not ISO format, therefore the time zone defaults to local.</p> + +<pre class="brush: js">Date.parse('Wed, 09 Aug 1995 00:00:00 GMT'); +</pre> + +<p>Returns <code>807926400000</code> no matter the local time zone as GMT (UTC) is provided.</p> + +<pre class="brush: js">Date.parse('Wed, 09 Aug 1995 00:00:00'); +</pre> + +<p>Returns <code>807937200000</code> in time zone GMT-0300, and other values in other time zones, since there is no time zone specifier in the argument and it is not ISO format, so is treated as local.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00 GMT'); +</pre> + +<p>Returns <code>0</code> no matter the local time zone as a time zone GMT (UTC) is provided.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00'); +</pre> + +<p>Returns <code>14400000</code> in time zone GMT-0400, and other values in other time zones, since no time zone is provided and the string is not in ISO format, therefore the local time zone is used.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400'); +</pre> + +<p>Returns <code>14400000</code> no matter the local time zone as a time zone GMT (UTC) is provided.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Simplified ISO 8601 format added.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.parse")}}</p> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<ul> + <li>Firefox 49 {{geckoRelease(49)}} changed the parsing of 2-digit years to be aligned with the Google Chrome browser instead of Internet Explorer. Now, 2-digit years that are less than <code>50</code> are parsed as 21st century years. For example, <code>04/16/17</code>, previously parsed as April 16, 1917, will be April 16, 2017 now. To avoid any interoperability issues or ambiguous years, it is recommended to use the ISO 8601 format like "2017-04-16" ({{bug(1265136)}}).</li> + <li>Google Chrome will accept a numerical string as a valid <code><em>dateString</em></code> parameter. This means that, for instance, while <code>!!Date.parse("42")</code> evaluates to <code>false</code> in Firefox, it evaluates to <code>true</code> in Google Chrome because "42" is interpreted as January 1st, 2042.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.UTC()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/function/call/index.html b/files/vi/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..681b98474b --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,148 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +tags: + - JavaScript + - Phương Thức + - hàm +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>call()</strong></code> gọi một hàm với giá trị của <code>this</code> và các đối số riêng lẻ.</p> + +<div class="note"> +<p><strong>Chú ý:</strong> Mặc dù hàm này có cú pháp gần giống với hàm {{jsxref("Function.prototype.apply", "apply()")}} nhưng có sự khác biệt cơ bản. Hàm <code>call()</code> nhận <strong>nhiều đối số riêng lẻ</strong>, còn hàm <code>apply()</code> nhận <strong>một mảng tập hợp của nhiều đối số.</strong></p> +</div> + +<h2 id="Cú_Pháp">Cú Pháp</h2> + +<pre class="syntaxbox"><code><var>function</var>.call(<var>thisArg</var>, <var>arg1</var>, <var>arg2</var>, ...)</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>Giá trị của <code>this</code> được đưa ra để gọi <em><code>hàm</code></em>. Lưu ý rằng <code>this</code> có thể không phải ?là giá trị thực tế được thấy bởi phương thức: Nếu phương thức là một hàm trong {{jsxref("Functions_and_function_scope/Strict_mode", "non-strict mode", "", 1)}} , giá trị {{jsxref("Global_Objects/null", "null")}} và {{jsxref("Global_Objects/undefined", "undefined")}} sẽ được thay thế với global object và các giá trị sơ khai (primitive) sẽ được chuyển thành các đối tượng (objects).</dd> + <dt><code>arg1, arg2, ...</code></dt> + <dd>Các đối số cho hàm.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Kết quả của của việc gọi hàm với giá trị xác định của <code><strong>this</strong></code> và các đối số.</p> + +<h2 id="Miêu_tả">Miêu tả</h2> + +<p>Một đối tượng <code>this</code> có thể được chỉ định khi gọi một hàm có sẵn. <code>this</code> đề cập đến đối tượng hiện tại (current object), là đối tượng đang gọi (calling object). Với hàm <code>call</code>, bạn có thể viết một phương thức một lần duy nhất và sau đó thừa kế nó trong một đối tương khác mà không phải viết lại phương thức đó cho đối tượng mới.</p> + +<h2 id="Ví_du">Ví du</h2> + +<h3 id="Sử_dung_call_để_chain_constructors_cho_một_đối_tượng">Sử dung <code>call</code> để chain constructors cho một đối tượng</h3> + +<p>Bạn có thể sử dụng hàm <code>call</code> để chain constructors cho một đối tượng giống như trong Java. Trong ví dụ dưới đây, hàm khởi tại của đối tượng <code>Product</code> được định nghĩa với 2 tham số, <code>name</code> và <code>price</code>. Hai hàm <code>Food</code> và <code>Toy</code> gọi <code>Product</code> với tham số <code>this</code> , <code>name</code> và <code>price</code>. Product khởi tạo thuộc tính <code>name</code> và <code>price</code>, cả 2 hàm này định nghĩa <code>category</code>.</p> + +<pre class="brush: js">function Product(name, price) { + this.name = name; + this.price = price; +} + +function Food(name, price) { + Product.call(this, name, price); + this.category = 'food'; +} + +function Toy(name, price) { + Product.call(this, name, price); + this.category = 'toy'; +} + +var cheese = new Food('feta', 5); +var fun = new Toy('robot', 40); +</pre> + +<h3 id="Sử_dung_hàm_call_để_gọi_một_hàm_ẩn_danh_(anonymous_function)"> Sử dung hàm <code>call</code> để gọi một hàm ẩn danh (anonymous function)</h3> + +<p>Trong ví dụ dưới đây, chúng ta tạo một hàm ẩn danh và sử dụng hàm <code>call</code> để gọi hàm đó nhận mọi đối tượng trong một mảng. Mục đích chính của hàm ẩn danh này là thêm tính năng hàm print cho mọi đối tượng, từ đó các đối tượng này có thể in ra vị trí của chúng trong mảng. Việc này có thể không cần thiết nhưng được đưa ra với mục đích ví dụ.</p> + +<pre class="brush: js">var animals = [ + { species: 'Lion', name: 'King' }, + { species: 'Whale', name: 'Fail' } +]; + +for (var i = 0; i < animals.length; i++) { + (function(i) { + this.print = function() { + console.log('#' + i + ' ' + this.species + + ': ' + this.name); + } + this.print(); + }).call(animals[i], i); +} +</pre> + +<h3 id="Sử_dung_hàm_call_để_gọi_hàm_và_đưa_ra_một_giá_trị_cho_đối_tượng_'this'"> Sử dung hàm <code>call</code> để gọi hàm và đưa ra một giá trị cho đối tượng 'this'</h3> + +<p>Trong ví dụ dưới đây khi chúng ta gọi hàm <strong>greet</strong> , giá trị của <strong>this</strong> trong hàm <strong>greet</strong> chính là đối tượng <strong>i.</strong></p> + +<pre class="brush: js">function greet() { + var reply = [this.person, 'Is An Awesome', this.role].join(' '); + console.log(reply); +} + +var i = { + person: 'Douglas Crockford', role: 'Javascript Developer' +}; + +greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer +</pre> + +<h2 id="Thông_số_kỹ_thuật"> Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_với_trình_duyệt_web">Tính tương thích với trình duyệt web</h2> + +<div> +<div class="hidden">Tính tương thích của bảng trong trang này được tạo từ dữ liệu cấu trúc. Nếu bạn muốn đóng góp thêm thông tin và dữ liệu, hãy tới trang <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</div> + +<p>{{Compat("javascript.builtins.Function.call")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Function.prototype.bind()")}}</li> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li> + <p><a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Giới thiệu về hướng đối tượng JavaScript</a></p> + </li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/function/index.html b/files/vi/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..c94856a200 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,150 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - TopicStub + - hàm +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p>Hàm<strong> <code>Function</code></strong> tạo mới một đối tượng <code>Function</code>. Gọi hàm tạo trực tiếp có thể tạo các hàm một cách linh hoạt, nhưng gặp phải các vấn đề về bảo mật và hiệu suất tương tự như {{jsxref("eval")}}.</p> + +<p>Mỗi một JavaScript function thực sự là một đối tượng <code>Function</code>.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Đây là các tên được sử dụng bởi hàm làm tên các tham số chính thức. Mỗi tên của tham số phải là một chuỗi tương ứng với một mã định danh JavaScript hợp lệ hoặc một danh sách các chuỗi tương tự được phân tách bằng dấu phẩy; ví dụ "<code>x</code>", "<code>theValue</code>" hoặc "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>Một chuỗi chứa các câu lệnh JavaScript bao gồm định nghĩa hàm.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Đối tượng <code>Function</code> được tạo ra thông qua hàm <code>Function</code> được chuyển đổi khi hàm được tạo ra. Điều này kém hiệu quả hơn so với việc khai báo một hàm với <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">biểu thức hàm</a> hoặc <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">câu lệnh hàm</a> và gọi nó trong mã của bạn, bởi vì các hàm đó được phân tích cú pháp với phần còn lại của mã. </p> + +<p>Tất cả các tham số truyền cho hàm được coi là tên định danh của các tham số trong hàm, thứ mà sẽ được tạo, theo thứ tự chúng được truyền.</p> + +<p>Gọi <code>Function</code> như là một hàm (không sử dụng toán tử <code>new</code>) có tác dụng tương tự như gọi nó là một hàm thông thường.</p> + +<h2 id="Các_thuộc_tính_và_phương_thức_của_Function">Các thuộc tính và phương thức của <code>Function</code></h2> + +<p>Một đối tượng <code>Function</code> toàn cục không có phương thức hoặc thuộc tính của riêng nó. Tuy nhiên, vì bản thân nó là một hàm, nó thừa hưởng một số phương thức và thuộc tính thông qua {{jsxref("Function.prototype")}}.</p> + +<h2 id="Function_prototype"><code>Function</code> prototype</h2> + +<h3 id="Các_thuộc_tính">Các thuộc tính</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> + +<h3 id="Các_phương_thức">Các phương thức</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> + +<h2 id="Các_thể_hiện_của_Function">Các thể hiện của <code>Function</code></h2> + +<p>Các thể hiện của <code>Function</code> kế thừa các phương thức và thuộc tính từ {{jsxref("Function.prototype")}}. Cũng như tất cả các hàm khác, bạn có thể thay đổi prototype của hàm tạo để thực hiện thay đổi cho tất cả các thể hiện của <code>Function</code>.</p> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<h3 id="Các_tham_số_xác_định_cùng_với_hàm_Function">Các tham số xác định cùng với hàm <code>Function</code></h3> + +<p>Đoạn mã sau tạo ra một đối tượng <code>Function</code> có hai tham số.</p> + +<pre class="brush: js">// Ví dụ này có thể chạy trực tiếp trên JavaScript Console + +// Tạo một hàm gồm hai tham số và trả về tổng của những tham số đó +var adder = new Function('a', 'b', 'return a + b'); + +// Gọi hàm +adder(2, 6); +// > 8 +</pre> + +<p>Những tham số "<code>a</code>" và "<code>b</code>" là các tên tham số chính thức được sử dụng trong thân hàm, "<code>return a + b</code>".</p> + +<h3 id="Sự_khác_biệt_giữa_hàm_Function_constructor_và_định_nghĩa_hàm">Sự khác biệt giữa hàm Function constructor và định nghĩa hàm</h3> + +<p>Các hàm được tạo ra cùng với <code>Function</code> constructor không tạo ra sự khép kín với bối cảnh sáng tạo của chúng; chúng luôn luôn được tạo ra trong phạm vi toàn cục. Khi gọi, chúng sẽ chỉ có thể truy cập đên các biến cục bộ và biến toàn cục của chúng, chứ không phải các biến từ phạm vi mà <code>Function</code> constructor được tạo. Điều này khác với việc sử dụng {{jsxref("eval")}} với mã cho biểu thức hàm.</p> + +<pre class="brush: js">var x = 10; + +function createFunction1() { + var x = 20; + return new Function('return x;'); // |x| trỏ tới |x| toàn cục +} + +function createFunction2() { + var x = 20; + function f() { + return x; // |x| trỏ tới |x| cục bộ ngay bên trên + } + return f; +} + +var f1 = createFunction1(); +console.log(f1()); // 10 +var f2 = createFunction2(); +console.log(f2()); // 20 +</pre> + +<h2 id="Các_thông_số_kỹ_thuật">Các thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu. Được triển khai trong JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_của_trình_duyệt">Tính tương thích của trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function")}}</p> +</div> + +<h2 id="Tham_khảo">Tham khảo</h2> + +<ul> + <li>{{jsxref("Functions", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/function/tosource/index.html b/files/vi/web/javascript/reference/global_objects/function/tosource/index.html new file mode 100644 index 0000000000..32a43d0da2 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/function/tosource/index.html @@ -0,0 +1,65 @@ +--- +title: Function.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Function/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/Function/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>Phương pháp <code><strong>toSource()</strong></code> trả về một chuỗi đại diện cho mã nguồn của đối tượng.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>function</var>.toSource(); +</pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chuỗi đại diện cho mã nguồn của đối tượng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương pháp <code>toSource</code> trả về các giá trị theo</p> + +<ul> + <li>Đối với đối tượng tích hợp {{jsxref("Function")}}, <code><strong>toSource()</strong></code> trả về chuỗi mã nguồn không khả dụng: + + <pre class="brush: js">function Function() { + [native code] +} +</pre> + </li> + <li>Đối với các hàm tùy chỉnh, <code>toSource()</code> trả về nguồn Javascript định nghĩa đối tượng dưới dạng chuỗi. + <pre class="brush: js">// For example: +function hello() { + console.log("Hello, World!"); +} + +hello.toSource(); +</pre> + + <pre class="brush: js">// Results in: +"function hello() { + console.log(\"Hello, World!\"); +}"</pre> + </li> +</ul> + +<p>Phương pháp này thường được gọi cục bộ trong Javascript và không rõ ràng bằng mã. Bạn có thể gọi <strong><code>toSource()</code></strong> trong khi gỡ lỗi để kiểm tra nội dung của một đối tượng.</p> + +<h2 id="Đặc_điểm_chi_tiết">Đặc điểm chi tiết</h2> + +<p>Không phải là một đặc tính chuẩn nào. Ghi rõ trong JavaScript 1.3.</p> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function.toSource")}}</p> +</div> + +<h2 id="Liên_quan">Liên quan</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/generator/index.html b/files/vi/web/javascript/reference/global_objects/generator/index.html new file mode 100644 index 0000000000..a1ed3ecf07 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/generator/index.html @@ -0,0 +1,130 @@ +--- +title: Generator +slug: Web/JavaScript/Reference/Global_Objects/Generator +translation_of: Web/JavaScript/Reference/Global_Objects/Generator +--- +<div>{{JSRef}}</div> + +<p><code><strong>Generator</strong></code> là một object return bởi một {{jsxref("Statements/function*", "generator function", "", 1)}}, nó phù hợp với cả <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable protocol</a> và <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol">iterator protocol</a>.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">function* gen() { + yield 1; + yield 2; + yield 3; +} + +var g = gen(); // "Generator { }"</pre> + +<h2 id="Phương_thức">Phương thức</h2> + +<dl> + <dt>{{jsxref("Generator.prototype.next()")}}</dt> + <dd>Trả về giá trị yielded, được khai báo qua câu lệnh {{jsxref("Operators/yield", "yield")}}.</dd> + <dt>{{jsxref("Generator.prototype.return()")}}</dt> + <dd>Trả về giá trị và kết thúc generator.</dd> + <dt>{{jsxref("Generator.prototype.throw()")}}</dt> + <dd>Quăng lỗi vào generator (đồng thời kết thúc generator, trừ khi được bắt lại trong generator đó).</dd> +</dl> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Một_vòng_lặp_vô_hạn">Một vòng lặp vô hạn</h3> + +<pre class="brush: js">function* idMaker() { + var index = 0; + while(true) + yield index++; +} + +var gen = idMaker(); // "Generator { }" + +console.log(gen.next().value); // 0 +console.log(gen.next().value); // 1 +console.log(gen.next().value); // 2 +// ...</pre> + +<h2 id="Generator_object_cũ">Generator object cũ</h2> + +<p>Firefox (SpiderMonkey) đã hiện thực phiên bản generators đầu tiên trong <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a>, lúc đó dấu sao (*) trong khai báo không bắt buộc (bạn chỉ cần dùng từ khóa <code>yield</code> bên trong hàm). Tuy nhiên, kiểu viết này đã không còn được hổ trợ từ Firefox 58 (released ngày 23, tháng 1, 2018) ({{bug(1083482)}}).</p> + +<h3 id="Các_phương_thức_generator_cũ">Các phương thức generator cũ</h3> + +<dl> + <dt><code>Generator.prototype.next() </code>{{non-standard_inline}}</dt> + <dd>Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. This corresponds to <code>next()</code> in the ES2015 generator object.</dd> + <dt><code>Generator.prototype.close()</code> {{non-standard_inline}}</dt> + <dd>Closes the generator, so that when calling <code>next()</code> an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the <code>return()</code> method in the ES2015 generator object.</dd> + <dt><code>Generator.prototype.send()</code> {{non-standard_inline}}</dt> + <dd>Used to send a value to a generator. The value is returned from the {{jsxref("Operators/yield", "yield")}} expression, and returns a value yielded by the next {{jsxref("Operators/yield", "yield")}} expression. <code>send(x)</code> corresponds to <code>next(x)</code> in the ES2015 generator object.</dd> + <dt><strong><code>Generator.</code></strong><code>prototype.</code><strong><code>throw()</code> </strong> {{non-standard_inline}}</dt> + <dd>Throws an error to a generator. This corresponds to the <code>throw()</code> method in the ES2015 generator object.</dd> +</dl> + +<h3 id="Legacy_generator_example">Legacy generator example</h3> + +<pre class="brush: js">function fibonacci() { + var a = yield 1; + yield a * 2; +} + +var it = fibonacci(); +console.log(it); // "Generator { }" +console.log(it.next()); // 1 +console.log(it.send(10)); // 20 +console.log(it.close()); // undefined +console.log(it.next()); // throws StopIteration (as the generator is now closed) +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hổ_trợ">Trình duyệt hổ trợ</h2> + + + +<p>{{Compat("javascript.builtins.Generator")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<h3 id="Legacy_generators">Legacy generators</h3> + +<ul> + <li>{{jsxref("Statements/Legacy_generator_function", "The legacy generator function", "", 1)}}</li> + <li>{{jsxref("Operators/Legacy_generator_function", "The legacy generator function expression", "", 1)}}</li> + <li>{{jsxref("StopIteration")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol">The legacy Iterator protocol</a></li> +</ul> + +<h3 id="ES2015_generators">ES2015 generators</h3> + +<ul> + <li>{{jsxref("Functions", "Functions", "", 1)}}</li> + <li>{{jsxref("Statements/function", "function")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/index.html b/files/vi/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..58625d24b9 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/index.html @@ -0,0 +1,203 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Objects + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>Chương này bao gồm các chuẩn của JavaScript, đối tượng tích hợp, gồm phương thức và thuộc tính của chúng.</p> + +<p>Thuật ngữ "đối tượng toàn cục" (hay đối tượng tích hợp chuẩn) ở đây không bị nhầm lẫn với <strong>đối tượng toàn cục</strong>. Ở đây, các đối tượng toàn cục đề cập đến <strong>các đối tượng trong phạm vi toàn cục</strong>. Bản thân <strong>đối tượng toàn cục</strong> cũng có thể được truy cập bằng toán tử: {{JSxRef("Toán tử/this", "this")}} trong toàn cục (nhưng chỉ khi ECMAScript 5 không được sử dụng; trong trường hợp đó, nó trả về: {{JSxRef("undefined")}}). Trong thực tế, phạm vi toàn cục <strong>bao gồm</strong> các thuộc tính của đối tượng toàn cục, các thuộc tính được kế thừa (nếu có).</p> + +<div class="onlyinclude"> +<p>Các đối tượng khác trong phạm vi toàn cục cũng được tạo bởi tập lệnh từ người dùng (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">created by the user script</a>) hoặc được cung cấp bởi các ứng dụng máy chủ. Các đối tượng mà máy chủ có sẵn trong trình duyệt được ghi lại trong tài liệu tham khảo API (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Reference">API reference</a>). Để biết thêm thông tin về sự khác biệt giữa <a href="https://developer.mozilla.org/en-US/docs/DOM/DOM_Reference">DOM</a> và <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">JavaScript</a> Core, hãy xem <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h2 id="Đối_tượng_chuẩn_theo_thể_loại">Đối tượng chuẩn theo thể loại</h2> + +<h3 id="Các_thuộc_tính_của_giá_trị">Các thuộc tính của giá trị</h3> + +<p>Những đặc tính toàn cục này trả về một giá trị đơn giản; chúng không có thuộc tính hay phương thức nào.</p> + +<ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} literal</li> +</ul> + +<h3 id="Các_thuộc_tính_chức_năng">Các thuộc tính chức năng</h3> + +<p>Các hàm toàn cục (gọi trên toàn cục chứ không phải trên một đối tượng) trực tiếp trả về kết quả cho người gọi.</p> + +<ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</li> + <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</li> +</ul> + +<h3 id="Các_đối_tượng_cơ_bản">Các đối tượng cơ bản</h3> + +<p>Đây là những đối tượng cơ bản mà tất cả các đối tượng các đều dựa vào. Nó bao gồm đối tượng đại diện cho các đối tượng, hàm, và lỗi chung.</p> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}} {{experimental_inline}}</li> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("EvalError")}}</li> + <li>{{jsxref("InternalError")}}</li> + <li>{{jsxref("RangeError")}}</li> + <li>{{jsxref("ReferenceError")}}</li> + <li>{{jsxref("SyntaxError")}}</li> + <li>{{jsxref("TypeError")}}</li> + <li>{{jsxref("URIError")}}</li> +</ul> + +<h3 id="Số_và_ngày">Số và ngày </h3> + +<p>Đây là các đối tượng cơ sở đại diện cho số, ngày, và các phép toán học.</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> + +<h3 id="Xử_lí_văn_bản">Xử lí văn bản</h3> + +<p>Những đối tượng này đại diện cho chuỗi và hỗ trợ thao tác chúng.</p> + +<p>{{jsxref("String")}}</p> + +<ul> + <li>{{jsxref("RegExp")}}</li> +</ul> + +<h3 id="Mục_lục_các_bộ_sưu_tập">Mục lục các bộ sưu tập</h3> + +<p>Các đối tượng này đại diện cho các bộ sưu tập dữ liệu sắp xếp theo giá trị. Chúng bao gồm các mảng và cấu trúc mảng.</p> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Int8Array")}}</li> + <li>{{jsxref("Uint8Array")}}</li> + <li>{{jsxref("Uint8ClampedArray")}}</li> + <li>{{jsxref("Int16Array")}}</li> + <li>{{jsxref("Uint16Array")}}</li> + <li>{{jsxref("Int32Array")}}</li> + <li>{{jsxref("Uint32Array")}}</li> + <li>{{jsxref("Float32Array")}}</li> + <li>{{jsxref("Float64Array")}}</li> + <li>{{JSxRef("BigInt64Array")}}</li> + <li>{{JSxRef("BigUint64Array")}}</li> +</ul> + +<h3 id="Bộ_sưu_tập_khóa">Bộ sưu tập khóa</h3> + +<p>Các đối tượng này đại diện cho các bộ sưu tập sử dụng với khóa; chúng chứa các phần tử lặp đi lặp lại theo thứ tự chèn.</p> + +<ul> + <li>{{jsxref("Map")}} </li> + <li>{{jsxref("Set")}} </li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}} </li> +</ul> + +<h3 id="Cấu_trúc_dữ_liệu">Cấu trúc dữ liệu</h3> + +<p>Các đối tượng này đại diện và tương tác với các bộ đệm cấu trúc dữ liệu và dữ liệu được mã hóa bởi JavaScript Object Notation (JSON).</p> + + + +<ul> + <li>{{JSxRef("ArrayBuffer")}}</li> + <li>{{JSxRef("SharedArrayBuffer")}} {{Experimental_Inline}}</li> + <li>{{JSxRef("Atomics")}} {{Experimental_Inline}}</li> + <li>{{JSxRef("DataView")}}</li> + <li>{{JSxRef("JSON")}}</li> +</ul> + + + +<h3 id="Kiểm_soát_các_đối_tượng_trừu_tượng">Kiểm soát các đối tượng trừu tượng</h3> + + + +<ul> + <li>{{JSxRef("Promise")}}</li> + <li>{{JSxRef("Generator")}}</li> + <li>{{JSxRef("GeneratorFunction")}}</li> + <li>{{JSxRef("AsyncFunction")}} {{Experimental_Inline}}</li> +</ul> + + + +<h3 id="Sự_phản">Sự phản </h3> + +<ul> + <li>{{JSxRef("Reflect")}}</li> + <li>{{JSxRef("Proxy")}}</li> +</ul> + +<h3 id="Quốc_tế_hóa">Quốc tế hóa</h3> + +<p>Bổ sung vào ECMAScript Core các chức năng phát hiện ngôn ng</p> + + + +<ul> + <li>{{JSxRef("Intl")}}</li> + <li>{{JSxRef("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{JSxRef("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{JSxRef("Global_Objects/ListFormat", "Intl.ListFormat")}}</li> + <li>{{JSxRef("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> + <li>{{JSxRef("Global_Objects/PluralRules", "Intl.PluralRules")}}</li> + <li>{{JSxRef("Global_Objects/RelativeTimeFormat", "Intl.RelativeTimeFormat")}}</li> + <li>{{JSxRef("Global_Objects/Locale", "Intl.Locale")}}</li> +</ul> + + + +<h3 id="WebAssembly">WebAssembly</h3> + + + +<ul> + <li>{{JSxRef("WebAssembly")}}</li> + <li>{{JSxRef("WebAssembly.Module")}}</li> + <li>{{JSxRef("WebAssembly.Instance")}}</li> + <li>{{JSxRef("WebAssembly.Memory")}}</li> + <li>{{JSxRef("WebAssembly.Table")}}</li> + <li>{{JSxRef("WebAssembly.CompileError")}}</li> + <li>{{JSxRef("WebAssembly.LinkError")}}</li> + <li>{{JSxRef("WebAssembly.RuntimeError")}}</li> +</ul> + + + +<h3 id="Khác">Khác</h3> + + + +<ul> + <li>{{JSxRef("Functions/arguments", "arguments")}}</li> +</ul> + + +</div> diff --git a/files/vi/web/javascript/reference/global_objects/infinity/index.html b/files/vi/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..73e388b0d1 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,81 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>Thuộc tính global <code><strong>Infinity</strong></code> là giá trị kiểu số biểu diễn vô cùng.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Infinity </code></pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>Infinity</code> là một thuộc tính của <em>global object</em>, hay nói các khác, là một biến trong global scope.</p> + +<p>Giá trị khởi đầu của <code>Infinity</code> là {{jsxref("Number.POSITIVE_INFINITY")}}. Giá trị <code>Infinity</code> (dương vô cùng) lớn hơn mọi số. Về mặt toán học, giá trị này có biểu hiện giống hệt với vô cùng; chẳng hạn, mọi số dương nhân với <code>Infinity</code> đều bằng <code>Infinity</code>, và mọi số chia cho <code>Infinity</code> đều bằng 0.</p> + +<p>Như đã định nghĩa trong bản đặc tả ECMAScript 5, <code>Infinity</code> là chỉ-đọc (cài đặt trong JavaScript 1.8.5 / Firefox 4).</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">console.log(Infinity ); /* Infinity */ +console.log(Infinity + 1 ); /* Infinity */ +console.log(Math.pow(10, 1000)); /* Infinity */ +console.log(Math.log(0) ); /* -Infinity */ +console.log(1 / Infinity ); /* 0 */ +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu. Cài đặt trong JavaScript 1.3</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Infinity")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/isfinite/index.html b/files/vi/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..a846d37172 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,97 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>Hàm global <code><strong>isFinite()</strong></code> xác định liệu giá trị truyền vào có phải một giá trị hữu hạn hay không. Nếu cần thiết, tham số sẽ được ép kiểu sang số trước.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-isfinite.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">isFinite(<em>testValue</em>)</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>testValue</code></dt> + <dd>Giá trị để kiểm tra tính hữu hạn.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p><strong><code>false</code></strong> nếu đối số là dương hoặc âm {{jsxref("Infinity")}} hay là {{jsxref("NaN")}}; ngoài ra thì trả về <strong><code>true</code></strong>.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>isFinite</code> là hàm top-level và không liên kết với bất cứ object nào.</p> + +<p>Bạn có thể dùng hàm này để xác định liệu một số có phải là hữu hạn hay không. Hàm <code>isFinite</code> kiểm tra giá trị kiểu số truyền trong đối số của nó. Nếu đối số của nó là <code>NaN</code>, dương vô cùng, hoặc âm vô cùng, phương thức này trả về <code>false</code>; ngoài ra, nó trả về <code>true</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">isFinite(Infinity); // false +isFinite(NaN); // false +isFinite(-Infinity); // false + +isFinite(0); // true +isFinite(2e64); // true +isFinite(910); // true + +isFinite(null); // true, sẽ trả về false với phương thức + // chuyên biệt hơn Number.isFinite(null) + +isFinite('0'); // true, sẽ trả về false với phương thức + // chuyên biệt hơn Number.isFinite("0") +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.isFinite")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Number.NaN")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/json/index.html b/files/vi/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..513e41e3ae --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,132 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>JSON</code></strong> object chứa các phương thức để phân giải <a class="external" href="https://json.org/">JavaScript Object Notation</a> ({{glossary("JSON")}}) và chuyển hóa các giá trị sang JSON. Nó có thể được called, hoặc constructed, và aside từ 2 phương thức thuộc tính của nó, nó tự bản thân lại không có chức năng thú vị nào.</span></p> + +<h2 id="Khác_nhau_giữa_JavaScript_and_JSON">Khác nhau giữa JavaScript and JSON</h2> + +<p>JSON là một cú pháp để serializing các object, array, number, string, boolean và {{jsxref("null")}}. Nó dựa trên cú pháp JavaScript nhưng lại khác biệt với JavaScript: một số JavaScript <em>không</em> phải là JSON.</p> + +<dl> + <dt><strong>Objects và Arrays</strong></dt> + <dd>Các tên thuộc tính phải được đặt trong nháy kép; dấu phẩy kéo đuôi <a href="/en-US/docs/Web/JavaScript/Reference/Trailing_commas">trailing commas</a> sẽ không được chấp nhận.</dd> + <dt><strong>Numbers</strong></dt> + <dd>Các số 0 nằm ở đầu sẽ bị cấm. Một dấu chấm thập phân phải được theo sau bởi ít nhất một chữ số. <code>NaN</code> và <code>Infinity</code> cũng không được hỗ trợ.</dd> + <dt><strong>Bất kỳ JSON text nào cũng là một biểu thức JavaScript hợp lệ...</strong></dt> + <dd>...Nhưng chỉ có các JavaScript engines mà đã từng triển khai <a href="https://github.com/tc39/proposal-json-superset">proposal để làm làm tất cả JSON text hợp lệ ECMA-262</a>. Trong các engines mà không triển khai proposal, U+2028 LINE SEPARATOR và U+2029 PARAGRAPH SEPARATOR được cho phép trong các string literals và các property keys trong JSON; nhưng việc sử dụng chúng trong các tính năng này trong các JavaScript string literal sẽ gây ra {{jsxref("SyntaxError")}}.</dd> +</dl> + +<p>Consider this example where {{jsxref("JSON.parse()")}} parses the string as JSON and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval</a></code> executes the string as JavaScript:</p> + +<pre class="brush: js">let code = '"\u2028\u2029"' +JSON.parse(code) // evaluates to "\u2028\u2029" in all engines +eval(code) // throws a SyntaxError in old engines +</pre> + +<p>Other differences include allowing only double-quoted strings and having no provisions for {{jsxref("undefined")}} or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is <a href="https://json5.org/">JSON5</a>, used by the Babel compiler, and the more commonly used <a href="https://en.wikipedia.org/wiki/YAML">YAML</a>.</p> + +<h2 id="Cú_pháp_JSON_đầy_đủ">Cú pháp JSON đầy đủ</h2> + +<p>Cú pháp JSON đầy đủ như sau:</p> + +<pre class="syntaxbox"><var>JSON</var> = <strong>null</strong> + <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong> + <em>or</em> <var>JSONNumber</var> + <em>or</em> <var>JSONString</var> + <em>or</em> <var>JSONObject</var> + <em>or</em> <var>JSONArray</var> + +<var>JSONNumber</var> = <strong>-</strong> <var>PositiveNumber</var> + <em>or</em> <var>PositiveNumber</var> +<var>PositiveNumber</var> = DecimalNumber + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> <var>ExponentPart</var> + <em>or</em> <var>DecimalNumber</var> <var>ExponentPart</var> +<var>DecimalNumber</var> = <strong>0</strong> + <em>or</em> <var>OneToNine</var> <var>Digits</var> +<var>ExponentPart</var> = <strong>e</strong> <var>Exponent</var> + <em>or</em> <strong>E</strong> <var>Exponent</var> +<var>Exponent</var> = <var>Digits</var> + <em>or</em> <strong>+</strong> <var>Digits</var> + <em>or</em> <strong>-</strong> <var>Digits</var> +<var>Digits</var> = <var>Digit</var> + <em>or</em> <var>Digits</var> <var>Digit</var> +<var>Digit</var> = <strong>0</strong> through <strong>9</strong> +<var>OneToNine</var> = <strong>1</strong> through <strong>9</strong> + +<var>JSONString</var> = <strong>""</strong> + <em>or</em> <strong>"</strong> <var>StringCharacters</var> <strong>"</strong> +<var>StringCharacters</var> = <var>StringCharacter</var> + <em>or</em> <var>StringCharacters</var> <var>StringCharacter</var> +<var>StringCharacter</var> = any character + <em>except</em> <strong>"</strong> <em>or</em> <strong>\</strong> <em>or</em> U+0000 through U+001F + <em>or</em> <var>EscapeSequence</var> +<var>EscapeSequence</var> = <strong>\"</strong> <em>or</em> <strong>\/</strong> <em>or</em> <strong>\\</strong> <em>or</em> <strong>\b</strong> <em>or</em> <strong>\f</strong> <em>or</em> <strong>\n</strong> <em>or</em> <strong>\r</strong> <em>or</em> <strong>\t</strong> + <em>or</em> <strong>\u</strong> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> +<var>HexDigit</var> = <strong>0</strong> through <strong>9</strong> + <em>or</em> <strong>A</strong> through <strong>F</strong> + <em>or</em> <strong>a</strong> through <strong>f</strong> + +<var>JSONObject</var> = <strong>{</strong> <strong>}</strong> + <em>or</em> <strong>{</strong> <var>Members</var> <strong>}</strong> +<var>Members</var> = <var>JSONString</var> <strong>:</strong> <var>JSON</var> + <em>or</em> <var>Members</var> <strong>,</strong> <var>JSONString</var> <strong>:</strong> <var>JSON</var> + +<var>JSONArray</var> = <strong>[</strong> <strong>]</strong> + <em>or</em> <strong>[</strong> <var>ArrayElements</var> <strong>]</strong> +<var>ArrayElements</var> = <var>JSON</var> + <em>or</em> <var>ArrayElements</var> <strong>,</strong> <var>JSON</var> +</pre> + +<p>Các khoảng trắng lớn có thể hiện diện ở bất cứ đâu ngoại trừ bên trong một <code>JSONnumber</code> (các số không được chứa khoảng trắng nào) hoặc <code>JSONString</code> (nơi mà nó được interpreted như là một ký tự tương ứng trong một chuỗi, hoặc sẽ gây ra lỗi). Ký tự tab (<a href="http://unicode-table.com/en/0009/">U+0009</a>), carriage return (<a href="http://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="http://unicode-table.com/en/000A/">U+000A</a>), and space (<a href="http://unicode-table.com/en/0020/">U+0020</a>) là những ký tự khoảng trắng duy nhất hợp lệ.</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("JSON.parse()", "JSON.parse(<var>text</var>[, <var>reviver</var>])")}}</dt> + <dd>Phân giải chuỗi <em><code>text</code></em> dưới dạng JSON, tùy chọn thêm việc chuyển hóa giá trị được tạo ra và các thuộc tính của nó, sau đó return giá trị. Bất kì sự vi phạm nào về cú pháp JSON, kể cả những trường hợp liên quan đến sự khác nhau giữa JavaScript và JSON, sẽ dấn đến một {{jsxref("SyntaxError")}} được thrown. Lựa chọn <code>reviver</code> cho phép interpreting những gì mà <code>replacer</code> sử dụng để đại diện cho các kiểu dữ liệu khác.</dd> + <dt>{{jsxref("JSON.stringify()", "JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])")}}</dt> + <dd>Return một chuỗi JSON tương ứng với giá trị được chỉ định, tùy chọn thêm việc bao gồm chỉ các thuộc tính nhất định hoặc thay thế giá trị thuộc tính theo cách user định nghĩa. Mặc định, tất cả các instances của {{jsxref("undefined")}} sẽ được thay thế bằng {{jsxref("null")}}, và các kiểu dữ liệu native không được hỗ trợ khác sẽ bị kiểm duyệt. Tùy chọn <code>replacer</code> cho phép chỉ định các cách thực thi khác.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> +<div> + + +<p>{{Compat("javascript.builtins.JSON")}}</p> +</div> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.toJSON()")}}</li> +</ul> + +<h2 id="Tools">Tools</h2> + +<ul> + <li><a href="http://www.jsondiff.com/">JSON Diff</a> checker</li> + <li><a href="http://jsonbeautifier.org/">JSON Beautifier/editor</a></li> + <li><a href="http://jsonparser.org/">JSON Parser</a></li> + <li><a href="https://tools.learningcontainer.com/json-validator/">JSON Validator</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/loi/index.html b/files/vi/web/javascript/reference/global_objects/loi/index.html new file mode 100644 index 0000000000..a9733ce5b0 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/loi/index.html @@ -0,0 +1,240 @@ +--- +title: Lỗi +slug: Web/JavaScript/Reference/Global_Objects/loi +tags: + - JavaScript + - Lỗi + - Tham chiếu +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +<div>{{JSRef}}</div> + +<div>Hàm <strong><code>Error</code></strong> tạo ra một đối tượng kiểu lỗi. Các thể hiện của đối tượng <code>Error</code> được ném ra khi xảy ra lỗi thực thi. Một đối tượng <code>Error</code> ngoài ra có thể được dùng như là một đối tượng căn bản cho các ngoại lệ do người dùng tự định nghĩa. Xem bên dưới các loại lỗi chuẩn được xây dựng sẵn.</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">new Error([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>message</code></dt> + <dd>Tùy chọn. Một mô tả của lỗi rằng người dùng có thể đọc được.</dd> + <dt><code>fileName</code> {{non-standard_inline}}</dt> + <dd>Tùy chọn. Giá trị của thuộc tính <code>fileName</code> trong quá trình tạo ra đối tượng <code>Error</code>. Các mặc định là tên của tập tin chứa đoạn mã gọi tới hàm <code>Error()</code>. </dd> + <dt><code>lineNumber</code> {{non-standard_inline}}</dt> + <dd>Tuỳ chọn. Giá trị của thuộc tính <code>lineNumber</code> trong quá trình tạo ra đối tượng <code>Error</code>. Các mặc định là số dòng hiện tại đang gọi tới hàm <code>Error()</code>.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Các lỗi thực thi dẫn đến các đối tượng <code>Error</code> được tạo ra và ném đi.</p> + +<p>Trang này ghi lại việc sử dụng đối tượng Error và cách sử dụng nó như là một hàm. Để biết danh sách các thuộc tính và phương thức được kế thừa bởi các thể hiện của <code>Error</code>, xem {{jsxref("Error.prototype")}}.</p> + +<h3 id="Được_sử_dụng_như_là_một_hàm">Được sử dụng như là một hàm</h3> + +<p>Khi <code>Error</code> được sử dụng như là một hàm -- không có từ khoá <code>new</code>, nó sẽ trả về một đối tượng <code>Error</code>. Do đó, gọi hàm <code>Error</code> cũng sẽ tạo ra cùng một đối tượng <code>Error</code> thông qua từ khóa <code>new</code>.</p> + +<pre>// this: +const x = Error('Tôi được tạo ra bằng cách sử dụng gọi hàm!');<code> +// tương tự như this</code> +<code>const y = new Error('Tôi được xây dựng thông qua từ khoá "new"!');</code></pre> + +<h3 id="Các_loại_lỗi">Các loại lỗi</h3> + +<p>Bên cạnh hàm Error, còn có 7 hàm khác làm việc với lỗi trong JavaScript. Đối với ngoại lệ phía client, xem thêm tại <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements#Exception_handling_statements">Các câu lệnh xử lý ngoại lệ.</a></p> + +<dl> + <dt>{{jsxref("EvalError")}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra liên quan đến hàm toàn cục {{jsxref("Global_Objects/eval", "eval()")}}.</dd> + <dt>{{jsxref("InternalError")}} {{non-standard_inline}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra khi một lỗi bên trong bộ máy JavaScript được ném. Ví dụ: "quá nhiều đệ quy".</dd> + <dt>{{jsxref("RangeError")}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra khi một biến số hoặc tham số nằm ngoài phạm vi hợp lệ của nó.</dd> + <dt>{{jsxref("ReferenceError")}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra khi hủy tham chiếu của một tham chiếu không hợp lệ.</dd> + <dt>{{jsxref("SyntaxError")}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra trong khi phân tích cú pháp mã trong {{jsxref("Global_Objects/eval", "eval()")}}.</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra khi một biến hoặc một tham số có kiểu không hợp lệ.</dd> + <dt>{{jsxref("URIError")}}</dt> + <dd>Tạo một thể hiện đại diện cho một lỗi xảy ra khi {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} hoặc {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} truyền các tham số không hợp lệ.</dd> +</dl> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt>{{jsxref("Error.prototype")}}</dt> + <dd>Cho phép thêm các thuộc tính mới vào các thể hiện của <code>Error</code>.</dd> +</dl> + +<h2 id="Phương_thức">Phương thức</h2> + +<p>Một đối tượng <code>Error</code> toàn cục không chứa phương thức riêng của nó, tuy nhiên, nó thừa hưởng các phương thức từ prototype.</p> + +<h2 id="Các_thể_hiện_của_Error">Các thể hiện của Error</h2> + +<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}</div> + +<h3 id="Các_thuộc_tính">Các thuộc tính</h3> + +<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}</div> + +<h3 id="Các_phương_thức">Các phương thức</h3> + +<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}</div> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<h3 id="Ném_một_lỗi_thông_thường">Ném một lỗi thông thường</h3> + +<p>Thông thường bạn tạo ra một đối tượng <code>Error</code> và muốn sử dụng nó cùng tới từ khoá {{jsxref("Statements/throw", "throw")}}. Bạn có thể bẫy lỗi bằng cách sử dụng cú pháp {{jsxref("Statements/try...catch", "try...catch")}}:</p> + +<pre class="brush: js">try { + throw new Error('Whoops!'); +} catch (e) { + console.log(e.name + ': ' + e.message); +} +</pre> + +<h3 id="Xử_lý_một_lỗi_cụ_thể">Xử lý một lỗi cụ thể</h3> + +<p>Bạn có thể chọn cách chỉ xử lý các loại lỗi cụ thể bằng cách kiểm tra loại lỗi với thuộc tính {{jsxref("Object.prototype.constructor", "constructor")}} của lỗi hoặc, nếu bạn đang viết cho các công cụ JavaScript hiện đại, hãy dùng từ khoá {{jsxref("Operators/instanceof", "instanceof")}}:</p> + +<pre class="brush: js">try { + foo.bar(); +} catch (e) { + if (e instanceof EvalError) { + console.log(e.name + ': ' + e.message); + } else if (e instanceof RangeError) { + console.log(e.name + ': ' + e.message); + } + // ... etc +} +</pre> + +<h3 id="Tùy_biến_các_loại_lỗi">Tùy biến các loại lỗi</h3> + +<p>Bạn có thể muốn định nghĩa các loại lỗi của riêng mình được dẫn xuất từ <code>Error</code> để có thể <code>throw new MyError()</code> và sử dụng <code>instanceof MyError</code> để kiểm tra loại lỗi trong trình xử lý ngoại lệ. Điều này làm cho mã xử lý lỗi sạch hơn và nhất quán hơn. Xem "<a href="http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript">Cách tốt để thừa kế hàm Error trong JavaScript là gì?</a>" trên StackOverflow để thảo luận chuyên sâu.</p> + +<h4 id="Tuỳ_biến_lớp_Error_trong_ES6">Tuỳ biến lớp Error trong ES6</h4> + +<div class="warning"> +<p>Babel và các trình biên dịch khác sẽ không xử lý chính xác đoạn mã sau mà không cần <a href="https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend">cấu hình bổ sung</a><a href="/vi/docs/">.</a></p> +</div> + +<div class="note"> +<p>Một số trình duyệt đã thêm hàm CustomError trong ngăn xếp qua cách dùng class trong ES6.</p> +</div> + +<pre class="brush: js">class CustomError extends Error { + constructor(foo = 'bar', ...params) { + // Pass remaining arguments (including vendor specific ones) to parent constructor + super(...params); + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, CustomError); + } + + // Custom debugging information + this.foo = foo; + this.date = new Date(); + } +} + +try { + throw new CustomError('baz', 'bazMessage'); +} catch(e){ + console.log(e.foo); //baz + console.log(e.message); //bazMessage + console.log(e.stack); //stacktrace +}</pre> + +<h4 id="Tuỳ_biến_đối_tượng_trong_ES5">Tuỳ biến đối tượng trong ES5</h4> + +<div class="warning"> +<p><strong>Tất cả</strong> trình duyệt đã thêm hàm CustomError trong ngăn xếp qua cách khai báo chuẩn.</p> +</div> + +<pre class="brush: js">function CustomError(foo, message, fileName, lineNumber) { + var instance = new Error(message, fileName, lineNumber); + instance.foo = foo; + Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); + if (Error.captureStackTrace) { + Error.captureStackTrace(instance, CustomError); + } + return instance; +} + +CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: Error, + enumerable: false, + writable: true, + configurable: true + } +}); + +if (Object.setPrototypeOf){ + Object.setPrototypeOf(CustomError, Error); +} else { + CustomError.__proto__ = Error; +} + + +try { + throw new CustomError('baz', 'bazMessage'); +} catch(e){ + console.log(e.foo); //baz + console.log(e.message) ;//bazMessage +}</pre> + +<h2 id="Các_đặc_điểm_kỹ_thuật">Các đặc điểm kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc điểm kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu. Được triển khai trong JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11', 'Error')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-error-objects', 'Error')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_của_trình_duyệt">Tính tương thích của trình duyệt</h2> + +<div> +<div class="hidden">Bảng tương thích trên trang này được tạo từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp cho dữ liệu, vui lòng xem <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho yêu cầu cho chúng tôi.</div> + +<p>{{Compat("javascript.builtins.Error")}}</p> +</div> + +<h2 id="Tham_khảo">Tham khảo</h2> + +<ul> + <li>{{jsxref("Error.prototype")}}</li> + <li>{{jsxref("Statements/throw", "throw")}}</li> + <li>{{jsxref("Statements/try...catch", "try...catch")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/map/index.html b/files/vi/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..45be246c96 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,263 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ES6 + - JavaScript + - Map + - cách dùng + - hàm +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">Đối tượng <strong><code>Map</code></strong> lưu cặp key-value (khoá - giá trị) theo thứ tự chèn vào của khoá.</span> Bất kỳ giá trị nào (cả đối tượng (objects) và {{Glossary("Primitive", "primitive values")}}) đều có thể sử dụng làm key hoặc value.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">new Map([<em>iterable</em>])</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>Một {{jsxref("Array")}} hoặc <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a> object có các phần tử là cặp key-value (các mảng có 2 phần tử, vd. <code>[[ 1, 'one' ],[ 2, 'two' ]]</code>). Mỗi cặp key-value sẽ được thêm vào <code>Map</code> mới; những giá trị <code>null</code> chuyển thành <code>undefined</code>.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Một <code>Map</code> object duyệt qua các phần tử của nó theo thứ tự chèn vào –– một vòng lặp {{jsxref("Statements/for...of", "for...of")}} trả về một mảng <code>[key, value]</code> cho mỗi lần lặp.</p> + +<h3 id="Key_equality_(so_sánh_key)">Key equality (so sánh key)</h3> + +<p>Key được xác định bằng nhau dựa vào giải thuật "SameValueZero": <code>NaN</code> được xem là giống <code>NaN</code> (mặc dù <code>NaN !== NaN</code>) và tất cả các giá trị khác được xem xét bằng nhau theo toán tử <code>===</code>. Trong đặc tả ECMAScript hiện tại, <code>-0</code> và <code>+0</code> là bằng nhau, cho dù điều này không đúng ở các bản dự thảo trước đó. Xem "Value equality for -0 and 0" trong bảng <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map$translate?tolocale=vi#Browser_compatibility">tương thích trình duyệt</a> để biết thêm chi tiết.</p> + +<h3 id="Objects_and_maps_compared">Objects and maps compared</h3> + +<p>{{jsxref("Object", "Objects")}} tương tự với <code>Maps</code> ở chỗ cả hai đều cho phép bạn đặt keys cho values, lấy các values, xoá các keys và xem có gì được chứa trong một key không. Bởi vì điều này (và bởi vì trước đây không tích hợp các lựa chọn khác), trong lịch sử, <code>Object</code>s đã được dùng như <code>Map</code>s; Tuy vậy, có những điểm khác biệt khiến sử dụng một <code>Map</code> thích hợp hơn trong các trường hợp nhất định: </p> + +<ul> + <li>Keys của một Object là {{jsxref("String", "Strings")}} và {{jsxref("Symbol", "Symbols")}}, trong khi chúng có thể là bất kỳ giá trị nào với Map, bao gồm hàm, objects và primitive.</li> + <li>Các keys trong Map có thứ tự trong khi các keys trong object thì không. Vì thế, khi duyệt qua, Map object trả về keys theo thứ tự chèn vào.</li> + <li>Bạn có thể lấy kích cỡ của một <code>Map</code> dễ dàng qua thuộc tính <code>size</code>, trong khi số thuộc tính trong một <code>Object</code> phải xác định thủ công.</li> + <li>Một <code>Map</code> là một <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a> và do đó có thể được duyệt trực tiếp, trong khi để duyệt qua một <code>Object</code> cần lấy các keys của nó rồi mới duyệt.</li> + <li>Một <code>Object</code> có một prototype, vậy nên có các keys mặc định có thể xung đột với các keys của bạn nếu không cẩn thận. Ở ES5, điều này có thể tránh bằng cách sử dụng <code>map = Object.create(null)</code>, nhưng hiếm khi thực hiện.</li> + <li>Một <code>Map</code> có thể thực thi tốt hơn ở các hoàn cảnh thường xuyên thêm và xoá các cặp keys.</li> +</ul> + +<h2 id="Các_thuộc_tính">Các thuộc tính</h2> + +<dl> + <dt><code>Map.length</code></dt> + <dd>Giá trị của thuộc tính <code>length</code> là 0.</dd> + <dd>Để lấy số phần tử đang có trong mảng, sử dụng {{jsxref("Map.prototype.size")}}.</dd> + <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Map.prototype")}}</dt> + <dd>Represents the prototype for the <code>Map</code> constructor. Allows the addition of properties to all <code>Map</code> objects.</dd> +</dl> + +<h2 id="Map_instances">Map instances</h2> + +<p>?Tất cả <code>Map</code> instances kế thừa từ {{jsxref("Map.prototype")}}.</p> + +<h3 id="Các_thuộc_tính_2">Các thuộc tính</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}</p> + +<h3 id="Các_phương_thức">Các phương thức</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}</p> + +<h2 id="Ví_dụ">?Ví dụ</h2> + +<h3 id="Sử_dụng_Map_object">Sử dụng Map object</h3> + +<pre class="brush: js">var myMap = new Map(); + +var keyString = 'a string', + keyObj = {}, + keyFunc = function() {}; + +// đặt các values +myMap.set(keyString, "value associated with 'a string'"); +myMap.set(keyObj, 'value associated with keyObj'); +myMap.set(keyFunc, 'value associated with keyFunc'); + +myMap.size; // 3 + +// lấy các values +myMap.get(keyString); // "value associated with 'a string'" +myMap.get(keyObj); // "value associated with keyObj" +myMap.get(keyFunc); // "value associated with keyFunc" + +myMap.get('a string'); // "value associated with 'a string'" + // ?vì keyString === 'a string' +myMap.get({}); // undefined, vì keyObj !== {} +myMap.get(function() {}) // undefined, vì keyFunc !== function () {} +</pre> + +<h3 id="Sử_dụng_NaN_làm_Map_keys">Sử dụng NaN làm Map keys</h3> + +<p><code>NaN</code> có thể sử dụng làm một key. Kể cả khi mỗi <code>NaN</code> không bằng chính nó (<code>NaN !== NaN</code> trả về true), ví dụ sau chạy tốt bởi vì các NaNs không phân biệt lẫn nhau:</p> + +<pre class="brush: js">var myMap = new Map(); +myMap.set(NaN, 'not a number'); + +myMap.get(NaN); // "not a number" + +var otherNaN = Number('foo'); +myMap.get(otherNaN); // "not a number" +</pre> + +<h3 id="Duyệt_Maps_với_for..of">Duyệt Maps với for..of</h3> + +<p>Maps có thể được duyệt với vòng lặp <code>for..of</code>:</p> + +<pre class="brush: js">var myMap = new Map(); +myMap.set(0, 'zero'); +myMap.set(1, 'one'); +for (var [key, value] of myMap) { + console.log(key + ' = ' + value); +} +// 0 = zero +// 1 = one + +for (var key of myMap.keys()) { + console.log(key); +} +// 0 +// 1 + +for (var value of myMap.values()) { + console.log(value); +} +// zero +// one + +for (var [key, value] of myMap.entries()) { + console.log(key + ' = ' + value); +} +// 0 = zero +// 1 = one +</pre> + +<h3 id="Duyệt_Maps_với_forEach()">Duyệt Maps với forEach()</h3> + +<p>Maps có thể được duyệt bằng phương thức <code>forEach()</code>:</p> + +<pre class="brush: js">myMap.forEach(function(value, key) { + console.log(key + ' = ' + value); +}); +// Will show 2 logs; first with "0 = zero" and second with "1 = one" +</pre> + +<h3 id="Quan_hệ_với_Array_objects">Quan hệ với Array objects</h3> + +<pre class="brush: js">var kvArray = [['key1', 'value1'], ['key2', 'value2']]; + +// Sử dụng hàm khởi tạo Map để chuyển một 2D key-value Array vào một map +var myMap = new Map(kvArray); + +myMap.get('key1'); // returns "value1" + +// Sử dụng hàm Array.from để chuyển một map vào một 2D key-value Array +console.log(Array.from(myMap)); // Sẽ hiện ra Array giống hệt kvArray + +// Hoặc sử dụng duyệt keys hoặc values và chuyển chúng thành một mảng +console.log(Array.from(myMap.keys())); // Sẽ hiện ["key1", "key2"] +</pre> + +<h3 id="Nhân_bản_(cloning)_và_gộp_(merging)_Maps">Nhân bản (cloning) và gộp (merging) Maps</h3> + +<p>Giống như Arrays, Maps có thể được nhân bản:</p> + +<pre class="brush: js">var original = new Map([ + [1, 'one'] +]); + +var clone = new Map(original); + +console.log(clone.get(1)); // one +console.log(original === clone); // false. Useful for shallow comparison</pre> + +<p>Keep in mind that the <em>data</em> itself is not cloned</p> + +<p>Maps có thể được gộp lại, vẫn đảm bảo các key là duy nhất: </p> + +<pre class="brush: js">var first = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]); + +var second = new Map([ + [1, 'uno'], + [2, 'dos'] +]); + +// Merge two maps. The last repeated key wins. +// Spread operator essentially converts a Map to an Array +var merged = new Map([...first, ...second]); + +console.log(merged.get(1)); // uno +console.log(merged.get(2)); // dos +console.log(merged.get(3)); // three</pre> + +<p>Maps cũng có thể được gộp với Arrays:</p> + +<pre class="brush: js">var first = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]); + +var second = new Map([ + [1, 'uno'], + [2, 'dos'] +]); + +// Merge maps with an array. The last repeated key wins. +var merged = new Map([...first, ...second, [1, 'eins']]); + +console.log(merged.get(1)); // eins +console.log(merged.get(2)); // dos +console.log(merged.get(3)); // three</pre> + +<h3 id="Các_đặc_tả">Các đặc tả</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map-objects', 'Map')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + + + +<p>{{Compat("javascript.builtins.Map")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=697479">Map and Set bug at Mozilla</a></li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets">ECMAScript Harmony proposal</a></li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/math/abs/index.html b/files/vi/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..94c4b859e8 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,108 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +tags: + - JavaScript + - Math + - Phương Thức + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +<div>{{JSRef}}</div> + +<p>Hàm <strong><code>Math.abs()</code></strong> trả về giá trị tuyệt đối của một số như sau</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.abs</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mrow><mo stretchy="false">|</mo><mi>x</mi><mo stretchy="false">|</mo></mrow><mo>=</mo><mrow><mo>{</mo><mtable columnalign="left left"><mtr><mtd><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr><mtr><mtd><mi>0</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>=</mo><mn>0</mn></mtd></mtr><mtr><mtd><mo>-</mo><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr></mtable></mrow></mrow><annotation encoding="TeX">{\mathtt{\operatorname{Math.abs}(z)}} = {|z|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases} </annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-abs.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">Math.abs(<var>x</var>)</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>x</code></dt> + <dd>Loại số liệu.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Giá trị tuyệt đối của số đã cho.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p> </p> + +<p>Do <code>abs()</code> là phương thức tĩnh của <code>Math</code>, nên ta phải khai báo là <code>Math.abs()</code>, thay vì dùng nó như 1 phương thức của đối tượng được tạo ra từ <code>Math</code> (<code>Math</code> không phải hàm tạo).</p> + +<p> </p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Hành_vi_của_Math.abs()">Hành vi của <code>Math.abs()</code></h3> + +<p>Truyền một đối tượng rỗng, một mảng có hơn một giá trị, một chuỗi ký tự không-có-số hay một {{jsxref("undefined")}}/biến rỗng sẽ trả về {{jsxref("NaN")}}. Truyền {{jsxref("null")}}, một chuỗi rỗng hay một mảng rỗng sẽ trả về số 0.</p> + +<pre class="brush: js" dir="rtl">Math.abs('-1'); // 1 +Math.abs(-2); // 2 +Math.abs(null); // 0 +Math.abs(''); // 0 +Math.abs([]); // 0 +Math.abs([2]); // 2 +Math.abs([1,2]); // NaN +Math.abs({}); // NaN +Math.abs('string'); // NaN +Math.abs(); // NaN +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa đầu tiên. Được đưa vào JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.abs")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/math/ceil/index.html b/files/vi/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..09b056af36 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,172 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +tags: + - JavaScript + - Math + - Phương Thức + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +<div>{{JSRef}}</div> + +<p>Hàm <strong><code>Math.ceil()</code></strong> trả về số nguyên nhỏ nhất có giá trị lớn hơn hoặc bằng số đã cho.</p> + +<p><strong>Lưu ý: </strong><code>Math.ceil({{jsxref("null")}})</code> trả về số nguyên 0 và không đưa ra lỗi {{jsxref("NaN")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/math-ceil.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Math.ceil(<var>x</var>)</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>x</code></dt> + <dd>Loại số liệu.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Số nguyên nhỏ nhất có giá trị lớn hơn hoặc bằng số đã cho (bằng tham số).</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Do <code>ceil()</code> là phương thức tĩnh của <code>Math</code>, nên ta phải khai báo là <code>Math.ceil()</code>, thay vì dùng nó như 1 phương thức của đối tượng được tạo ra từ <code>Math</code> (<code>Math</code> không phải hàm tạo).</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Cách_dùng_Math.ceil()">Cách dùng <code>Math.ceil()</code></h3> + +<p>Ví dụ sau minh họa cách dùng <code>Math.ceil()</code> điển hình.</p> + +<pre class="brush: js">Math.ceil(.95); // 1 +Math.ceil(4); // 4 +Math.ceil(7.004); // 8 +Math.ceil(-0.95); // -0 +Math.ceil(-4); // -4 +Math.ceil(-7.004); // -7 +</pre> + +<h3 id="Tinh_chỉ_số_thập_phân">Tinh chỉ số thập phân</h3> + +<pre class="brush: js">// Đóng kín +(function() { + /** + * Tinh chỉ số thập phân của một con số. + * + * @param {String} type Loại điều chỉnh. + * @param {Number} value Số liệu. + * @param {Integer} exp Số mũ (the 10 logarithm of the adjustment base). + * @returns {Number} Giá trị đã chỉnh sửa. + */ + function decimalAdjust(type, value, exp) { + // Nếu exp có giá trị undefined hoặc bằng không thì... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // Nếu value không phải là ố hoặc exp không phải là số nguyên thì... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Làm tròn số thập phân (theo mốc số 5) + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Làm tròn số thập phân (về gần giá trị 0) + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Làm tròn số thập phân (ra xa giá trị 0) + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Chạy hàm round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +// Chạy hàm floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Chạy hàm ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa đầu tiên được đưa vào JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.ceil")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/math/floor/index.html b/files/vi/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..2f660fcf00 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,132 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +<div>{{JSRef}}</div> + +<p>Hàm <strong><code>Math.floor()</code></strong> trả về số nguyên bé hơn hoặc bằng số ban đầu.</p> + +<div>{{EmbedInteractiveExample("pages/js/math-floor.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate">Math.floor(<var>x</var>)</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>x</code></dt> + <dd>Một số.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Số nguyên lớn nhất nhỏ hơn hoặc bằng số đã cho.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Bởi vì <code>floor()</code> là một phương thức tĩnh của <code>Math</code>, bạn luôn sử dụng <code>Math.floor()</code>, thay vì sử dụng như là một phương thức của đối tượng được tạo ra từ <code>Math</code> (<code>Math</code> không phải là một constructor).</p> + +<div class="blockIndicator note"> +<p><strong>Lưu ý: </strong><code>Math.floor(null)</code> trả về 0, không phải {{jsxref("NaN")}}.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_Math.floor">Sử dụng <code>Math.floor()</code></h3> + +<pre class="brush: js notranslate">Math.floor( 45.95); // 45 +Math.floor( 45.05); // 45 +Math.floor( 4 ); // 4 +Math.floor(-45.05); // -46 +Math.floor(-45.95); // -46 +</pre> + +<h3 id="Điều_chỉnh_thập_phân">Điều chỉnh thập phân</h3> + +<pre class="brush: js notranslate">/** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ +function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); +} + +// Decimal round +const round10 = (value, exp) => decimalAdjust('round', value, exp); +// Decimal floor +const floor10 = (value, exp) => decimalAdjust('floor', value, exp); +// Decimal ceil +const ceil10 = (value, exp) => decimalAdjust('ceil', value, exp); + +// Round +round10(55.55, -1); // 55.6 +round10(55.549, -1); // 55.5 +round10(55, 1); // 60 +round10(54.9, 1); // 50 +round10(-55.55, -1); // -55.5 +round10(-55.551, -1); // -55.6 +round10(-55, 1); // -50 +round10(-55.1, 1); // -60 +// Floor +floor10(55.59, -1); // 55.5 +floor10(59, 1); // 50 +floor10(-55.51, -1); // -55.6 +floor10(-51, 1); // -60 +// Ceil +ceil10(55.51, -1); // 55.6 +ceil10(51, 1); // 60 +ceil10(-55.59, -1); // -55.5 +ceil10(-59, 1); // -50 +</pre> + +<h2 id="Quy_cách_kỹ_thuật">Quy cách kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + + + +<p>{{Compat("javascript.builtins.Math.floor")}}</p> + +<h2 id="Xem_thêm">Xem thêm:</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/math/index.html b/files/vi/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..bfaa405142 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,196 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math</code></strong> is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.</p> + +<h2 id="Description">Description</h2> + +<p>Unlike the other global objects, <code>Math</code> is not a constructor. All properties and methods of <code>Math</code> are static. You refer to the constant pi as <code>Math.PI</code> and you call the sine function as <code>Math.sin(x)</code>, where <code>x</code> is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd>Euler's constant and the base of natural logarithms, approximately 2.718.</dd> + <dt>{{jsxref("Math.LN2")}}</dt> + <dd>Natural logarithm of 2, approximately 0.693.</dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd>Natural logarithm of 10, approximately 2.303.</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>Base 2 logarithm of E, approximately 1.443.</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>Base 10 logarithm of E, approximately 0.434.</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>Ratio of the circumference of a circle to its diameter, approximately 3.14159.</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd>Square root of 2, approximately 1.414.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<div class="note"> +<p>Note that the trigonometric functions (<code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, <code>atan2()</code>) expect or return angles in radians. To convert radians to degrees, divide by <code>(Math.PI / 180)</code>, and multiply by this to convert the other way.</p> +</div> + +<div class="note"> +<p>Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.</p> +</div> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> + <dd>Returns the absolute value of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> + <dd>Returns the arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}</dt> + <dd>Returns the hyperbolic arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> + <dd>Returns the arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}</dt> + <dd>Returns the hyperbolic arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> + <dd>Returns the arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}</dt> + <dd>Returns the hyperbolic arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> + <dd>Returns the arctangent of the quotient of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}</dt> + <dd>Returns the cube root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> + <dd>Returns the smallest integer greater than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}</dt> + <dd>Returns the number of leading zeroes of a 32-bit integer.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> + <dd>Returns the cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}</dt> + <dd>Returns the hyperbolic cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> + <dd>Returns E<sup>x</sup>, where <var>x</var> is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}</dt> + <dd>Returns subtracting 1 from <code>exp(x)</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> + <dd>Returns the largest integer less than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}</dt> + <dd>Returns the nearest <a href="http://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}</dt> + <dd>Returns the square root of the sum of squares of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}</dt> + <dd>Returns the result of a 32-bit integer multiplication.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of <code>1 + x</code> for a number x.</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}</dt> + <dd>Returns the base 10 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}</dt> + <dd>Returns the base 2 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> + <dd>Returns the largest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> + <dd>Returns the smallest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> + <dd>Returns base to the exponent power, that is, <code>base<sup>exponent</sup></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>Returns a pseudo-random number between 0 and 1.</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> + <dd>Returns the value of a number rounded to the nearest integer.</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}</dt> + <dd>Returns the sign of the x, indicating whether x is positive, negative or zero.</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> + <dd>Returns the sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}</dt> + <dd>Returns the hyperbolic sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> + <dd>Returns the positive square root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> + <dd>Returns the tangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}</dt> + <dd>Returns the hyperbolic tangent of a number.</dd> + <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> + <dd>Returns the string <code>"Math"</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}</dt> + <dd>Returns the integer part of the number x, removing any fractional digits.</dd> +</dl> + +<h2 id="Extending_the_Math_object">Extending the <code>Math</code> object</h2> + +<p>As with most of the built-in objects in JavaScript, the <code>Math</code> object can be extended with custom properties and methods. To extend the <code>Math</code> object, you do not use <code>prototype</code>. Instead, you directly extend <code>Math</code>:</p> + +<pre>Math.propName = propValue; +Math.methodName = methodRef;</pre> + +<p>For instance, the following example adds a method to the <code>Math</code> object for calculating the <em>greatest common divisor</em> of a list of arguments.</p> + +<pre class="brush: js">/* Variadic function -- Returns the greatest common divisor of a list of arguments */ +Math.gcd = function() { + if (arguments.length == 2) { + if (arguments[1] == 0) + return arguments[0]; + else + return Math.gcd(arguments[1], arguments[0] % arguments[1]); + } else if (arguments.length > 2) { + var result = Math.gcd(arguments[0], arguments[1]); + for (var i = 2; i < arguments.length; i++) + result = Math.gcd(result, arguments[i]); + return result; + } +};</pre> + +<p>Try it:</p> + +<pre class="brush: js">console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8', 'Math')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html b/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..cefbcccb04 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,101 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt +tags: + - JavaScript + - Math + - Phương Thức + - Tham khảo + - Toán +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +<div>{{JSRef}}</div> + +<p>Hàm <strong><code>Math.sqrt()</code></strong> trả về giá trị căn bậc hai, that is</p> + +<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>≥</mo><mn>0</mn><mo>,</mo><mstyle mathvariant="monospace"><mrow><mi>M</mi><mi>a</mi><mi>t</mi><mi>h</mi><mo>.</mo><mi>s</mi><mi>q</mi><mi>r</mi><mi>t</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><msqrt><mi>x</mi></msqrt><mo>=</mo><mtext>trị tuyệt đối của</mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mo>≥</mo><mn>0</mn><mspace width="thickmathspace"></mspace><mtext>tương ứng</mtext><mspace width="thickmathspace"></mspace><msup><mi>y</mi><mn>2</mn></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-sqrt.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Math.sqrt(<var>x</var>)</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>x</code></dt> + <dd>Một con số</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Căn bậc hai của số cung cấp. Nếu hàm nhận giá trị, {{jsxref("NaN")}} sẽ bị trả về.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Nếu <code>x</code> là con số âm, <code>Math.sqrt()</code> sẽ trả về {{jsxref("NaN")}}.</p> + +<p>Do <code>sqrt()</code> là phương thức tĩnh của <code>Math</code>, ta phải dùng theo cách này <code>Math.sqrt()</code>, thay vì dùng dưới dạng phương thức của đối tượng <code>Math</code> mà bạn tạo ra (<code>Math</code> không phải là một hàm khởi tạo, constructor).</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Dùng_Math.sqrt">Dùng <code>Math.sqrt()</code></h3> + +<pre class="brush: js">Math.sqrt(9); // 3 +Math.sqrt(2); // 1.414213562373095 + +Math.sqrt(1); // 1 +Math.sqrt(0); // 0 +Math.sqrt(-1); // NaN +Math.sqrt(-0); // -0 +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu. Tích hợp trong JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.sqrt")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Math.cbrt()")}}</li> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.pow()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/nan/index.html b/files/vi/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..cf7be92a59 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,97 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +tags: + - JavaScript + - Tham khảo + - Thuộc tính +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>Thuộc tính <em>global</em> <code><strong>NaN</strong></code> có giá trị đại diện cho khái niệm Not-A-Number (Không-phải-Số).</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>NaN</code></pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>NaN</code> là thuộc tính của đối tượng <em>global</em>.</p> + +<p>Giá trị khởi tạo của <code>NaN</code> là Not-A-Number — giống như giá trị của {{jsxref("Number.NaN")}}. Với các trình duyệt hiện đại, <code>NaN</code> không thể cấu hình được, không có thuộc tính được-viết. Kể cả khi được phép thì vẫn phải tránh việc ghi đè lên nó.</p> + +<p>Người ta hiếm khi dùng <code>NaN</code> trong viết chương trình. Nó được dùng làm giá trị trả về khi việc tính toán của các hàm {{jsxref("Math")}} thất bại (<code>Math.sqrt(-1)</code>) hoặc khi hàm phân tích phải dữ liệu số sai (<code>parseInt("là lá la")</code>).</p> + +<h3 id="Kiểm_thử_phép_so_sánh_NaN">Kiểm thử phép so sánh <code>NaN</code></h3> + +<p>Không thể thực hiện phép so sánh bằng (thông qua <code>==</code>, <code>!=</code>, <code>===</code>, và <code>!==</code>) <code>NaN</code> với bất kỳ giá trị nào khác, bao gồm cả một giá trị <code>NaN</code> khác. Hãy dùng {{jsxref("Number.isNaN()")}} hoặc {{jsxref("Global_Objects/isNaN", "isNaN()")}} để xác định rõ ràng đó có phải là <code>NaN</code> hay không. Hoặc làm thử một phép so sánh bản thân: <code>NaN</code>, và chỉ <code>NaN</code>, sẽ so sánh không cân bằng với chính nó.</p> + +<pre class="brush: js">NaN === NaN; // false (sai) +Number.NaN === NaN; // false +isNaN(NaN); // true (đúng) +isNaN(Number.NaN); // true + +function valueIsNaN(v) { return v !== v; } +valueIsNaN(1); // false +valueIsNaN(NaN); // true +valueIsNaN(Number.NaN); // true +</pre> + +<p>Tuy nhiên, lưu ý rằng có khác biệt giữa <code>isNaN()</code> và <code>Number.isNaN()</code>: <code>isNaN()</code> sẽ trả về giá trị <code>true</code> (đúng) nếu như giá trị hiện tại là <code>NaN</code> hoặc nó sẽ thành <code>NaN</code> sau khi bị ép số hóa dữ liệu, còn với <code>Number.isNaN()</code> thì dữ liệu trả về là <code>true</code> chỉ khi giá trị hiện tại là <code>NaN</code>.</p> + +<pre class="brush: js">isNaN('hello world'); // trả về giá trị 'true'. +Number.isNaN('hello world'); // trả về giá trị 'false'. +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa đầu tiên. Được đưa vào JavaScript 1.3</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + + + +<p>{{Compat("javascript.builtins.NaN")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.NaN")}}</li> + <li>{{jsxref("Number.isNaN()")}}</li> + <li>{{jsxref("isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/index.html b/files/vi/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..24b3e1b756 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,216 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - Number + - Reference + - Vietnamese +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p>Đối tượng JavaScript <strong>Number </strong>là một đối tượng bao bọc cho phép bạn làm việc với các giá trị số. Một đối tượng <strong>Number</strong> có thể được tạo ra sử dụng hàm khởi tạo Number().</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">new Number(value);</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Giá trị số của đối tượng được tạo ra.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Các sử dụng chính cho đối tượng Number là:</p> + +<ul> + <li>Nếu đối số không thể chuyển đổi được sang một số, nó trả về {{jsxref("NaN")}}.</li> + <li>Trong một ngữ cảnh không phải constructor (vd, không dùng toán tử {{jsxref("Operators/new", "new")}}), <font face="Consolas, Liberation Mono, Courier, monospace">Number có thể được sử dụng để thực hiện chuyển đổi kiểu</font>.</li> +</ul> + +<h2 id="Các_thuộc_tính">Các thuộc tính</h2> + +<dl> + <dt>{{jsxref("Number.EPSILON")}}</dt> + <dd>Khoảng cách nhỏ nhất giữa hai số có thể biểu thị được.</dd> + <dt>{{jsxref("Number.MAX_SAFE_INTEGER")}}</dt> + <dd><font><font>Các số an toàn tối đa trong JavaScript (</font></font><code>2<sup>53</sup> - 1)</code></dd> + <dt>{{jsxref("Number.MAX_VALUE")}}</dt> + <dd>Đại diện cho giá trị số lớn nhất.</dd> + <dt>{{jsxref("Number.MIN_SAFE_INTEGER")}}</dt> + <dd><font><font>Các số an toàn tối thiểu trong JavaScript</font></font> (<code>-(2<sup>53</sup> - 1)</code>).</dd> + <dt>{{jsxref("Number.MIN_VALUE")}}</dt> + <dd>Đại diện cho giá trị số nhỏ nhất - nghĩa là số dương gần với không nhất (không thực sự bằng không).</dd> + <dt>{{jsxref("Number.NaN")}}</dt> + <dd>Giá trị đặc biệt "không phải là một số".</dd> + <dt>{{jsxref("Number.NEGATIVE_INFINITY")}}</dt> + <dd>Giá trị đặc biệt đại diện cho âm vô cùng; được trả về khi tràn.</dd> + <dt>{{jsxref("Number.POSITIVE_INFINITY")}}</dt> + <dd>Giá trị đặc biệt đại diện cho dương vô cùng; được trả về khi tràn.</dd> + <dt>{{jsxref("Number.prototype")}}</dt> + <dd> + <p>Cho phép thêm các thuộc tính cho đối tượng Number</p> + </dd> +</dl> + +<h2 id="Các_phương_thức">Các phương thức</h2> + +<dl> + <dt>{{jsxref("Number.isNaN()")}}</dt> + <dd>Xác định giá trị được truyền là NaN.</dd> + <dt>{{jsxref("Number.isFinite()")}}</dt> + <dd>Xác định giá trị được truyền là một số hữu hạn.</dd> + <dt>{{jsxref("Number.isInteger()")}}</dt> + <dd>Xác định giá trị được truyền là một số nguyên.</dd> + <dt>{{jsxref("Number.isSafeInteger()")}}</dt> + <dd>Xác định giá trị được truyền là một số an toàn (số giữa <code>-(2<sup>53</sup> - 1)</code> và <code>2<sup>53</sup> - 1</code>).</dd> + <dt><s class="obsoleteElement">{{jsxref("Number.toInteger()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Được sử dụng để đánh giá giá trị được truyền và chuyển đổi nó sang một số nguyên (or {{jsxref("Global_Objects/Infinity", "Infinity")}}), nhưng đã được loại bỏ.</s></dd> + <dt>{{jsxref("Number.parseFloat()")}}</dt> + <dd>Giá trị cũng giống như {{jsxref("parseFloat", "parseFloat()")}} của đối tượng toàn cầu.</dd> + <dt>{{jsxref("Number.parseInt()")}}</dt> + <dd>Giá trị cũng giống như {{jsxref("parseInt", "parseInt()")}} của đối tượng toàn cầu.</dd> +</dl> + +<h2 id="Các_thể_hiện_của_Number"><code>Các thể hiện của Number</code></h2> + +<p>Tất cả các thể hiện của Number được kế thừa từ {{jsxref("Number.prototype")}}. Các đối tượng nguyên mẫu (prototype) của hàm khởi tạo Number có thể được sửa đổi để ảnh hưởng đến tất cả các thể hiện của Number.</p> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<h3 id="Sử_dụng_đối_tượng_Number_để_gán_các_giá_trị_cho_các_biến_số.">Sử dụng đối tượng Number để gán các giá trị cho các biến số.</h3> + +<p>Ví dụ sau sử dụng các thuộc tính của đối tượng Number để gán các giá trị cho các biến số khác nhau:</p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN;</pre> + +<h3 id="Phạm_vi_số_nguyên_của_Number">Phạm vi số nguyên của Number</h3> + +<p>Ví dụ sau cho thấy các giá trị số nguyên tối thiểu và tối đa có thể được biểu diễn dưới dạng đối tượng Number:</p> + +<pre class="brush: js">var biggestInt = 9007199254740992; +var smallestInt = -9007199254740992; +</pre> + +<p>Khi phân tích cú pháp dữ liệu đã được tuần tự hóa thành JSON, các giá trị số nguyên vượt ra khỏi phạm vi này có thể được dự kiến sẽ bị hỏng khi trình phân tích cú pháp JSON ép buộc chúng với kiểu Số. Sử dụng {{jsxref ("String")}} thay vào đó là một giải pháp khả thi.</p> + +<h3 id="Sử_dụng_Number_để_chuyển_đổi_một_đối_tượng_Date">Sử dụng Number để chuyển đổi một đối tượng Date</h3> + +<p>Ví dụ sau chuyển đổi một đối tượng {{jsxref("Date")}} sang một giá trị số sử dụng Number như là một hàm:</p> + +<pre class="brush: js">var d = new Date('October 30, 1996 13:46:36'); +console.log(Number(d)); +</pre> + +<p>Kết quả: 846657996000.</p> + +<h3 id="Chuyển_đổi_chuỗi_dạng_số_sang_số">Chuyển đổi chuỗi dạng số sang số</h3> + +<pre class="brush: js">Number("123") // 123 +Number("") // 0 +Number(" ") // 0 +Number("0x11") // 17 +Number("0b11") // 3 +Number("0o11") // 9 +Number("foo") // NaN +Number("100a") // NaN +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc điểm kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa ban đầu. Được thực hiện trong JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Đã thêm các phương pháp và thuộc tính mới: {{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_trình_duyệt">Khả năng tương thích trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Đặc tính</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Đặc tính</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>The {{jsxref("Math")}} đối tượng toàn cầu</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html b/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..907227aa76 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,88 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>Number.isFinite()</code></strong> xác định liệu giá trị truyền vào có phải một giá trị hữu hạn hay không.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">Number.isFinite(v<var>alue</var>)</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Giá trị để kiểm tra tính hữu hạn.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Giá trị {{jsxref("Boolean")}} cho biết liệu giá trị truyền vào có phải hữu hạn hay không.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>So sánh với hàm global {{jsxref("isFinite", "isFinite()")}}, phương thức này không ép kiểu tham số truyền vào thành kiểu số. Nghĩa là chỉ những giá trị có kiểu số, đồng thời có giá trị hữu hạn, mới trả về <code>true</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">Number.isFinite(Infinity); // false +Number.isFinite(NaN); // false +Number.isFinite(-Infinity); // false + +Number.isFinite(0); // true +Number.isFinite(2e64); // true + +Number.isFinite('0'); // false, sẽ thành true nếu dùng + // global isFinite('0') +Number.isFinite(null); // false, sẽ thành true nếu dùng + // global isFinite(null) +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (Number.isFinite === undefined) Number.isFinite = function(value) { + return typeof value === 'number' && isFinite(value); +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Number.isFinite")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>Đối tượng {{jsxref("Number")}} mà phương thức thuộc về.</li> + <li>The global function {{jsxref("isFinite")}}.</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html b/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html new file mode 100644 index 0000000000..522ff1945a --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html @@ -0,0 +1,88 @@ +--- +title: Number.isInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>Number.isInteger()</code></strong> xác định xem giá trị truyền vô có phải là một integer hay không.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Number.isInteger(v<var>alue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Giá trị cần kiểm tra xem nó có phải là một integer hay không.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Nếu giá trị mà bạn truyền vô trong phương thức này là một integer, kết quả trả về sẽ là <code>true</code>, ngược lại thì trả về<code> false</code>. Nếu giá trị đó là<font face="consolas, Liberation Mono, courier, monospace"> </font>{{jsxref("NaN")}} hoặc các giá trị Infinity thì đương nhiên vẫn trả về<code> false</code>.</p> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<pre class="brush: js">Number.isInteger(0); // true +Number.isInteger(1); // true +Number.isInteger(-100000); // true + +Number.isInteger(0.1); // false +Number.isInteger(Math.PI); // false + +Number.isInteger(Infinity); // false +Number.isInteger(-Infinity); // false +Number.isInteger("10"); // false +Number.isInteger(true); // false +Number.isInteger(false); // false +Number.isInteger([1]); // false +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isInteger = Number.isInteger || function(value) { + return typeof value === "number" && + isFinite(value) && + Math.floor(value) === value; +}; +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isinteger', 'Number.isInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p>{{Compat("javascript.builtins.Number.isInteger")}}</p> + +<div> </div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>Các đối tượng thuộc {{jsxref("Number")}}.</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/isnan/index.html b/files/vi/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..a4497d6dae --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,99 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>Number.isNaN()</code></strong> (NaN viết tắt cho Not a Number) xác định xem giá trị đó có <em><strong>chính xác</strong></em> là {{jsxref("NaN")}} hay không. Một phiên bản khác của phương thức này, nhưng nằm trong phạm vi global đó là: {{jsxref("isNaN", "isNaN()")}}.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Number.isNaN(v<var>alue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Giá trị truyền vô để kiểm tra xem nó có phải chính xác là {{jsxref("NaN")}} hay không.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Cả hai phương pháp operator so sánh bằng, đó là {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} và {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} đề trả ra <code>false</code> khi chúng ta kiểm tra giá trị {{jsxref("NaN")}}<em>là</em> {{jsxref("NaN")}} ví dụ: NaN === NaN, (đáng lẽ ra là true đúng không ?, nhưng thực tế giá trị NaN này không thể được xác định bằng cách này.), phương thức <code>Number.isNaN()</code> được tạo ra để làm việc này. Phương pháp này đưa ra 1 giải pháp để xác định NaN, NaN là một giá trị mà không thể so sánh với chính nó để kiểm tra như các giá trị khác trong JavaScript.</p> + +<p>{{jsxref("isNaN", "isNaN()")}} là phương thức kiểm tra NaN trong phạm vi global, lưu ý là <code>Number.isNaN()</code> không giống như<code> isNaN() </code>trong global, <code>Number.isNaN() </code>xác định chính xác {{jsxref("NaN")}} đó có phải là giá trị {{jsxref("NaN")}} của Number hay không. Vì, chỉ có NaN thật sự mới đưa ra được giá trị true khi mang vô phương thức này. Khác với global, miễn cái gì không phải là số thì cũng trả ra giá trị là true.</p> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<pre class="brush: js">Number.isNaN(NaN); // true +Number.isNaN(Number.NaN); // true +Number.isNaN(0 / 0) // true + +// e.g. these would have been true with global isNaN() +Number.isNaN("NaN"); // false +Number.isNaN(undefined); // false +Number.isNaN({}); // false +Number.isNaN("blabla"); // false + +// These all return false +Number.isNaN(true); +Number.isNaN(null); +Number.isNaN(37); +Number.isNaN("37"); +Number.isNaN("37.37"); +Number.isNaN(""); +Number.isNaN(" "); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isNaN = Number.isNaN || function(value) { + return typeof value === "number" && isNaN(value); +} + +// Or +Number.isNaN = Number.isNaN || function(value) { + return value !== value; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{Compat("javascript.builtins.Number.isNaN")}}</div> + +<div> </div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html b/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html new file mode 100644 index 0000000000..f49bf8d30e --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html @@ -0,0 +1,94 @@ +--- +title: Number.isSafeInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>Number.isSafeInteger()</code></strong> xác định xem giá trị truyền vào có phải một số nằm trong khoảng của <dfn>số nguyên an toàn</dfn> hay không.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<p>Số nguyên an toàn là số nguyên mà</p> + +<ul> + <li>có thể được biểu diễn chính xác theo chuẩn số nguyên độ chính xác kép IEEE-754, và</li> + <li>cách biểu diễn theo chuẩn IEEE-754 đó không thể bằng kết quả của một phép làm tròn số nguyên khác theo chuẩn biểu diễn IEEE-754.</li> +</ul> + +<p>Chẳng hạn, <code>2<sup>53</sup> - 1</code> là một số nguyên an toàn: nó có thể hiển thị chính xác, và không có số nguyên nào có thể làm tròn đến nó với bất cứ chế độ làm tròn theo chuẩn IEEE-754. Ngoài ra, <code>2<sup>53</sup></code> <em>không phải</em> là một số nguyên an toàn: nó có thể được biểu diễn chính xác theo chuẩn IEEE-754, nhưng số nguyên <code>2<sup>53</sup> + 1</code> không thể hiển thị chính xác theo chuẩn IEEE-754 mà thay vào đó được làm tròn về <code>2<sup>53</sup></code> theo kiểu làm tròn về số gần nhất và làm tròn về không. Số nguyên an toàn nằm trong đoạn từ <code>-(2<sup>53</sup> - 1)</code> đến <code>2<sup>53</sup> - 1</code> (± <code>9007199254740991</code>hoặc ±9,007,199,254,740,991).</p> + +<p>Xử lý giá trị lớn hơn hoặc nhỏ hơn ~9 triệu tỉ với độ chính xác toàn vẹn yêu cầu sử dụng <a href="https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic">thư viện số học độ chính xác bất kì</a>. Xem <a href="http://floating-point-gui.de/">What Every Programmer Needs to Know about Floating Point Arithmetic</a> để biết thêm thông tin về cách biểu diễn số thực dấu phẩy động.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Number.isSafeInteger(<var>testValue</var>)</code> +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>testValue</code></dt> + <dd>Giá trị để kiểm tra có phải số nguyên an toàn hay không.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>{{jsxref("Boolean")}} cho biết liệu giá trị truyền vào có phải là số nguyên an toàn hay không.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">Number.isSafeInteger(3); // true +Number.isSafeInteger(Math.pow(2, 53)); // false +Number.isSafeInteger(Math.pow(2, 53) - 1); // true +Number.isSafeInteger(NaN); // false +Number.isSafeInteger(Infinity); // false +Number.isSafeInteger('3'); // false +Number.isSafeInteger(3.1); // false +Number.isSafeInteger(3.0); // true +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isSafeInteger = Number.isSafeInteger || function (value) { + return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; +}; +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Number.isSafeInteger")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>Đối tượng {{jsxref("Number")}}.</li> + <li>{{jsxref("Number.MIN_SAFE_INTEGER")}}</li> + <li>{{jsxref("Number.MAX_SAFE_INTEGER")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html b/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html new file mode 100644 index 0000000000..7ae2ab0657 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html @@ -0,0 +1,71 @@ +--- +title: Number.MAX_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +--- +<div>{{JSRef}}</div> + +<p>Hằng <strong><code>Number.MAX_SAFE_INTEGER</code></strong> biểu diễn giá trị số nguyên an toàn lớn nhất trong JavaScript (<code>2<sup>53</sup> - 1</code>).</p> + +<div>{{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hằng <code>MAX_SAFE_INTEGER</code> có giá trị là <code>9007199254740991</code>(9,007,199,254,740,991 hay là ~9 triệu tỉ). Nguyên do đằng sau con số đó là do JavaScript sử dụng <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">số thực dấu phẩy động độ chính xác kép</a> được đặc tả trong chuẩn <a href="http://en.wikipedia.org/wiki/IEEE_floating_point">IEEE 754</a> và chỉ có thể biểu diễn an toàn các số trong khoảng <code>-(2<sup>53</sup> - 1)</code> và <code>2<sup>53</sup> - 1</code>.</p> + +<p>An toàn trong ngữ cảnh này ám chỉ khả năng biểu diễn cũng như so sánh số nguyên một cách chính xác. Chẳng hạn,<code>Number.MAX_SAFE_INTEGER+1 === Number.MAX_SAFE_INTEGER+2</code> sẽ trả về true, theo toán học thì là sai. Xem {{jsxref("Number.isSafeInteger()")}} để biết thêm chi tiết.</p> + +<p>Bởi vì <code>MAX_SAFE_INTEGER</code> là một thuộc tính tĩnh của {{jsxref("Number")}}, bạn thường dùng nó bằng <code>Number.MAX_SAFE_INTEGER</code>, thay vì tự tạo ra thuộc tính cho object {{jsxref("Number")}}.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">Number.MAX_SAFE_INTEGER // 9007199254740991 +Number.MAX_SAFE_INTEGER * Number.EPSILON // 2 bởi vì đối với số thực dấu phẩy động, giá trị thực tế chính là the decimal trailing "1" + // ngoại trừ trường hợp có độ chính xác subnormal như là zero (0) +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (!Number.MAX_SAFE_INTEGER) { + Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991 +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Number.MAX_SAFE_INTEGER")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.MIN_SAFE_INTEGER")}}</li> + <li>{{jsxref("Number.isSafeInteger()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html b/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html new file mode 100644 index 0000000000..4a3ecf1a76 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html @@ -0,0 +1,61 @@ +--- +title: Number.MIN_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Number.MIN_SAFE_INTEGER</code></strong> biểu diễn giá trị số nguyên an toàn lớn nhất trong JavaScript (<code>-(2<sup>53</sup> - 1)</code>).</p> + +<div>{{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hằng <code>MAX_SAFE_INTEGER</code> có giá trị là <code>-9007199254740991</code>(-9,007,199,254,740,991 hay là khoảng âm 9 triệu tỉ). Nguyên do đằng sau con số đó là do JavaScript sử dụng <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">số thực dấu phẩy động độ chính xác kép</a> được đặc tả trong chuẩn <a href="http://en.wikipedia.org/wiki/IEEE_floating_point">IEEE 754</a> và chỉ có thể biểu diễn an toàn các số trong khoảng <code>-(2<sup>53</sup> - 1)</code> và <code>2<sup>53</sup> - 1</code>. Xem {{jsxref("Number.isSafeInteger()")}} để biết thêm chi tiết.</p> + +<p>Bởi vì <code>MIN_SAFE_INTEGER</code> là một thuộc tính tĩnh của {{jsxref("Number")}}, bạn thường dùng nó bằng <code>Number.MIN_SAFE_INTEGER</code>, thay vì tự tạo ra thuộc tính cho object {{jsxref("Number")}}.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">Number.MIN_SAFE_INTEGER // -9007199254740991 +-(Math.pow(2, 53) - 1) // -9007199254740991 +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Number.MIN_SAFE_INTEGER")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.MAX_SAFE_INTEGER")}}</li> + <li>{{jsxref("Number.isSafeInteger()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/nan/index.html b/files/vi/web/javascript/reference/global_objects/number/nan/index.html new file mode 100644 index 0000000000..daf2661d0a --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/nan/index.html @@ -0,0 +1,63 @@ +--- +title: Number.NaN +slug: Web/JavaScript/Reference/Global_Objects/Number/NaN +tags: + - JavaScript + - Number + - Thuộc tính +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN +--- +<div>{{JSRef}}</div> + +<p>Thuộc tính <strong><code>Number.NaN</code></strong> đại diện cho khái niệm Not-A-Number (Không-phải-Số). Tương đương với {{jsxref("NaN")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-nan.html")}}</div> + +<p>Ta không phải tạo đối tượng {{jsxref("Number")}} để truy cập vào thuộc tính tĩnh này (dùng cú pháp <code>Number.NaN</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số kỹ thuật</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa đầu tiên. Được đưa vào JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.nan', 'Number.NaN')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trên_trình_duyệt">Tính tương thích trên trình duyệt</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.NaN")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>Đối tượng global {{jsxref("NaN")}}.</li> + <li>Đối tượng {{jsxref("Number")}} sở hữu thuộc tính này.</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html new file mode 100644 index 0000000000..75e87a4657 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html @@ -0,0 +1,96 @@ +--- +title: Number.NEGATIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +--- +<div>{{JSRef}}</div> + +<p>Thuộc tính <strong><code>Number.NEGATIVE_INFINITY</code></strong> biểu diễn giá trị âm của Infinity (âm vô cực).</p> + +<div>{{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.<</p> + +<p>Bạn không cần tạo đối tượng {{jsxref("Number")}} để truy cập vào đối tượng này (hãy dùng <code>Number.NEGATIVE_INFINITY</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Giá trị của <code>Number.NEGATIVE_INFINITY</code> cũng giống như giá trị âm của thuộc tính {{jsxref("Infinity")}} của global object.</p> + +<p>Giá trị này hành xử hơi khác so với âm vô cực trong toán học:</p> + +<ul> + <li>Bất cứ giá trị dương nào, bao gồm cả {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, nhân với <code>NEGATIVE_INFINITY</code> trả ra <code>NEGATIVE_INFINITY</code>.</li> + <li>Bất cứ giá trị âm nào, bao gồm cả <code>NEGATIVE_INFINITY</code>, nhân với <code>NEGATIVE_INFINITY</code> trả ra {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.</li> + <li>Bất cứ giá trị dương nào chia cho <code>NEGATIVE_INFINITY</code> trả ra âm 0.</li> + <li>Bất cứ giá trị âm nào chia cho <code>NEGATIVE_INFINITY</code> trả ra dương 0.</li> + <li>0 nhân với <code>NEGATIVE_INFINITY</code> trả ra {{jsxref("NaN")}}.</li> + <li>{{jsxref("NaN")}} nhân với <code>NEGATIVE_INFINITY</code> is {{jsxref("NaN")}}.</li> + <li><code>NEGATIVE_INFINITY</code> chia cho bất cứ giá trị âm nào ngoại trừ <code>NEGATIVE_INFINITY</code>, trả ra ra {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.</li> + <li><code>NEGATIVE_INFINITY</code> chia cho bất cứ giá trị dương nào ngoại trừ {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}} trả ra <code>NEGATIVE_INFINITY</code>.</li> + <li><code>NEGATIVE_INFINITY</code> chia cho cả <code>NEGATIVE_INFINITY</code> hay {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, đều trả về {{jsxref("NaN")}}.</li> +</ul> + +<p>Bạn có thể dùng thuộc tính <code>Number.NEGATIVE_INFINITY</code> để xác định điều kiện xem có trả về số hữu hạn hay không. Chú ý, ngoài ra, {{jsxref("isFinite")}} sẽ hợp với trường hợp này hơn.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_NEGATIVE_INFINITY">Sử dụng <code>NEGATIVE_INFINITY</code></h3> + +<p>Trong ví dụ sau đây, biến <code>smallNumber</code> được gán giá trị nhỏ hơn giá trị nhỏ nhất. Khi lệnh {{jsxref("Statements/if...else", "if")}} được thực thi, <code>smallNumber</code> có giá trị <code>-Infinity</code>, nên <code>smallNumber</code> được gán lại giá trị dễ kiểm soát hơn trước khi tiếp tục.</p> + +<pre class="brush: js">var smallNumber = (-Number.MAX_VALUE) * 2; + +if (smallNumber === Number.NEGATIVE_INFINITY) { + smallNumber = returnFinite(); +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu. Cài đặt trong JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Global_Objects/Infinity", "Infinity")}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html b/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html new file mode 100644 index 0000000000..54b2db905e --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html @@ -0,0 +1,96 @@ +--- +title: Number.POSITIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +translation_of: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +--- +<div>{{JSRef}}</div> + +<p>Thuộc tính <strong><code>Number.POSITIVE_INFINITY</code></strong> biểu diễn giá trị dương Infinity (dương vô cùng).</p> + +<div>{{EmbedInteractiveExample("pages/js/number-positive-infinity.html")}}</div> + +<p class="hidden">Tài nguyên dùng cho bài viết này được lưu trữ trong một kho của GitHub. Nếu bạn muốn đóng góp cho nó, hãy clone lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một pull request.</p> + +<p>Bạn không cần tạo đối tượng{{jsxref("Number")}} để truy cập vào đối tượng này (hãy dùng <code>Number.POSITIVE_INFINITY</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Giá trị của <code>Number.POSITIVE_INFINITY</code> cũng giống như giá trị dương của thuộc tính {{jsxref("Infinity")}} của global object.</p> + +<p>Giá trị này hành xử hơi khác so với vô cùng trong toán học:</p> + +<ul> + <li>Bất cứ giá trị dương nào, bao gồm cả <code>POSITIVE_INFINITY</code>, nhân với <code>POSITIVE_INFINITY</code> trả ra <code>POSITIVE_INFINITY</code>.</li> + <li>Bất cứ giá trị âm nào, bao gồm cả {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}, nhân với <code>POSITIVE_INFINITY</code> trả ra {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}.</li> + <li>Bất cứ giá trị dương nào chia cho <code>POSITIVE_INFINITY</code> trả ra dương 0.</li> + <li>Bất cứ giá trị âm nào chia cho <code>POSITIVE_INFINITY</code> trả ra âm 0.</li> + <li>0 nhân với <code>POSITIVE_INFINITY</code> trả ra {{jsxref("NaN")}}.</li> + <li>{{jsxref("Global_Objects/NaN", "NaN")}} nhân với <code>POSITIVE_INFINITY</code> trả ra {{jsxref("NaN")}}.</li> + <li><code>POSITIVE_INFINITY</code>, chia cho bất cứ giá trị âm nào ngoại trừ {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}, trả ra {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}.</li> + <li><code>POSITIVE_INFINITY</code>, chia cho bất cứ giá trị dương nào ngoại trừ <code>POSITIVE_INFINITY</code>, trả ra <code>POSITIVE_INFINITY</code>.</li> + <li><code>POSITIVE_INFINITY</code>, chia cho cả {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}} hay <code>POSITIVE_INFINITY</code>, đều ra {{jsxref("NaN")}}.</li> +</ul> + +<p>Bạn có thể dùng thuộc tính <code>Number.POSITIVE_INFINITY</code> để xác định điều kiện xem có trả về số hữu hạn hay không. Chú ý, ngoài ra, {{jsxref("isFinite")}} sẽ hợp với trường hợp này hơn.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_POSITIVE_INFINITY">Sử dụng <code>POSITIVE_INFINITY</code></h3> + +<p>Trong ví dụ sau đây, biến <code>bigNumber</code> được gán giá trị lớn hơn giá trị lớn nhất. Khi lệnh {{jsxref("Statements/if...else", "if")}} được thực thi, <code>bigNumber</code> có giá trị <code>Infinity</code>, nên <code>bigNumber</code> được gán lại giá trị dễ kiểm soát hơn trước khi tiếp tục.</p> + +<pre class="brush: js">var bigNumber = Number.MAX_VALUE * 2; + +if (bigNumber == Number.POSITIVE_INFINITY) { + bigNumber = returnFinite(); +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu. Cài đặt trong JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.6', 'Number.POSITIVE_INFINITY')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">Bảng trình duyệt hỗ trợ trong trang này được sinh từ cấu trúc dữ liệu. Nếu bạn muốn đóng góp cho khối dữ liệu, hãy xem qua <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi cho chúng tôi pull request.</p> + +<p>{{Compat("javascript.builtins.Number.POSITIVE_INFINITY")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("isFinite", "isFinite()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/assign/index.html b/files/vi/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..2f5b00f1ec --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,259 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +tags: + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object.assign()</code></strong> được sử dụng để sao chép các giá trị của tất cả thuộc tính có thể liệt kê từ một hoặc nhiều đối tượng nguồn đến một đối tượng đích. Nó sẽ trả về đối tượng đích đó.</p> + +<p>{{EmbedInteractiveExample("pages/js/object-assign.html")}}</p> + +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">Object.assign(<var>target</var>, ...<var>sources</var>)</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>target</code></dt> + <dd>Đối tượng đích</dd> + <dt><code>sources</code></dt> + <dd>Các đối tượng nguồn</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>(Các) Đối tượng đích</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Các thuộc tính trong đối tượng đích sẽ bị ghi lại bởi các thuộc tính trong đối tượng nguồn nếu chúng có cùng key. Tương tự, các thuộc tính nguồn sau sẽ ghi đè lên những thuộc tính nguồn trước. </p> + +<p>Phương thức <code>Object.assign()</code> chỉ sao chép những giá trị <em>liệt kê được</em> và và các thuộc tính <em>của bản thân</em> nó đến đối tượng đích. Nó sử dụng <code>[[Get]]</code> trên nguồn và <code>[[Set]]</code> trên đích, vì vậy nó sẽ gọi các hàm getter và setter. Vì lý do đó nó <em>chỉ định</em> thuộc tính so với việc chỉ sao chép hoặc xác đinh các thuộc tính mới. Điều này có thể khiến nó không phù hợp khi gộp các thuộc tính mới vào một nguyên mẫu (prototype) nếu các nguồn gộp chứa các getter. Để sao chép các thuộc tính xác định, bao gồm cả khả năng đếm được vào trong các nguyên mẫu thì nên sử dụng {{jsxref("Object.getOwnPropertyDescriptor()")}} và {{jsxref("Object.defineProperty()")}} để thay thế.</p> + +<p>Các thuộc tính {{jsxref("String")}} và {{jsxref("Symbol")}} đều được sao chép.</p> + +<p>Trong trường hợp có một lỗi, như việc một thuộc tính không được phép ghi đè, một {{jsxref("TypeError")}} sẽ sinh ra, và đối tượng đích có thể được thay đổi nếu có bất kỳ thuộc tính nào đã được thêm vào trước khi lỗi được sinh ra.</p> + +<p>Chú ý rằng <code>Object.assign()</code> không ném ra một {{jsxref("null")}} hoặc {{jsxref("undefined")}}.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sao_chép_một_object">Sao chép một object</h3> + +<pre class="brush: js">var obj = { a: 1 }; +var copy = Object.assign({}, obj); +console.log(copy); // { a: 1 } +</pre> + +<h3 id="Deep_Clone" name="Deep_Clone">Cảnh báo về Deep Clone</h3> + +<p>Với deep cloning, chúng ta cần sử dụng những lựa chọn khác khác bởi vì <code>Object.assign()</code> sao chép các giá trị thuộc tính. Nếu giá trị nguồn là tham chiếu đến một object, nó chỉ sao chép gía trị tham chiếu đó. </p> + +<pre class="brush: js">function test() { + 'use strict'; + + let a = { b: {c: 4} , d: { e: {f: 1} } }; + let g = Object.assign({}, a); + let h = JSON.parse(JSON.stringify(a)); + console.log(JSON.stringify(g.d)); // { e: { f: 1 } } + g.d.e = 32; + console.log('g.d.e set to 32.'); // g.d.e set to 32. + console.log(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } } + console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } } + console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: { f: 1 } } } + h.d.e = 54; + console.log('h.d.e set to 54.'); // h.d.e set to 54. + console.log(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } } + console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } } + console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: 54 } } +} + +test();</pre> + +<h3 id="Gộp_các_object">Gộp các object</h3> + +<pre class="brush: js">var o1 = { a: 1 }; +var o2 = { b: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign(o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 } +console.log(o1); // { a: 1, b: 2, c: 3 }, object đích tự nó bị thay đổi.</pre> + +<h3 id="Gộp_các_đối_tượng_với_cùng_giá_trị">Gộp các đối tượng với cùng giá trị</h3> + +<pre class="brush: js">var o1 = { a: 1, b: 1, c: 1 }; +var o2 = { b: 2, c: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign({}, o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 }</pre> + +<p>Các giá trị được ghi đè bởi các đối tượng khác mà chúng có chung các thuộc tính sau đó theo thứ tự các tham số.</p> + +<h3 id="Sao_chép_thuộc_tính_symbol-typed">Sao chép thuộc tính symbol-typed</h3> + +<pre class="brush: js">var o1 = { a: 1 }; +var o2 = { [Symbol('foo')]: 2 }; + +var obj = Object.assign({}, o1, o2); +console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 trên Firefox) +Object.getOwnPropertySymbols(obj); // [Symbol(foo)] +</pre> + +<h3 id="Các_thuộc_tính_trên_chuỗi_nguyên_mẫu_và_các_thuộc_tính_không_có_khả_năng_đếm_được_thì_không_thể_sao_chép.">Các thuộc tính trên chuỗi nguyên mẫu và các thuộc tính không có khả năng đếm được thì không thể sao chép. </h3> + +<pre class="brush: js">var obj = Object.create({ foo: 1 }, { // foo ở trên mắt xích prototype của obj. + bar: { + value: 2 // bar chứa thuộc tính không liệt kê được. + }, + baz: { + value: 3, + enumerable: true // baz chứa thuộc tính liệt kê được. + } +}); + +var copy = Object.assign({}, obj); +console.log(copy); // { baz: 3 } +</pre> + +<h3 id="Các_giá_trị_nguyên_thủy_sẽ_được_gói_thành_các_đối_tượng.">Các giá trị nguyên thủy sẽ được gói thành các đối tượng.</h3> + +<pre class="brush: js">var v1 = 'abc'; +var v2 = true; +var v3 = 10; +var v4 = Symbol('foo'); + +var obj = Object.assign({}, v1, null, v2, undefined, v3, v4); +// Sự nguyên bản sẽ bị gói lại, null và undefined sẽ bị bỏ qua. +// Ghi chú,chỉ có string wrapper mới có thuộc tính liệt kê được. +console.log(obj); // { "0": "a", "1": "b", "2": "c" } +</pre> + +<h3 id="Các_ngoại_lệ_sẽ_làm_gián_đoạn_quá_trình_sao_chép.">Các ngoại lệ sẽ làm gián đoạn quá trình sao chép.</h3> + +<pre class="brush: js">var target = Object.defineProperty({}, 'foo', { + value: 1, + writable: false +}); // target.foo chỉ read-only + +Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); +// TypeError: "foo" là read-only +// Trường hợp ngoại lệ được tạo ra khi gán target.foo + +console.log(target.bar); // 2, nguồn thứ nhất được sao chép thành công +console.log(target.foo2); // 3, đặc tính thứ nhất của nguồn thứ 2 được chép thành công. +console.log(target.foo); // 1, ngoại lệ được ném ra +console.log(target.foo3); // undefined, phương thức gán đã hoàn tất, foo3 sẽ không bị sao chép +console.log(target.baz); // undefined, nguồn thứ ba cũng không bị sao chép +</pre> + +<h3 id="Sao_chép_các_trình_truy_cập_accessor">Sao chép các trình truy cập (accessor)</h3> + +<pre class="brush: js">var obj = { + foo: 1, + get bar() { + return 2; + } +}; + +var copy = Object.assign({}, obj); +console.log(copy); +// { foo: 1, bar: 2 }, giá trị của copy.bar là giá trị return của getter của obj.bar. + +// Đây là function gán sao chép toàn bộ các mô tả. +function completeAssign(target, ...sources) { + sources.forEach(source => { + let descriptors = Object.keys(source).reduce((descriptors, key) => { + descriptors[key] = Object.getOwnPropertyDescriptor(source, key); + return descriptors; + }, {}); + // Mặc định thì Object.assign sao chép cả Symbol thống kê được luôn + Object.getOwnPropertySymbols(source).forEach(sym => { + let descriptor = Object.getOwnPropertyDescriptor(source, sym); + if (descriptor.enumerable) { + descriptors[sym] = descriptor; + } + }); + Object.defineProperties(target, descriptors); + }); + return target; +} + +var copy = completeAssign({}, obj); +console.log(copy); +// { foo:1, get bar() { return 2 } } +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p> {{Glossary("Polyfill","polyfill")}} không hỗ trợ các thuộc tính symbol, kể từ ES5 thì cũng không còn symbol nữa:</p> + +<pre class="brush: js">if (typeof Object.assign != 'function') { + Object.assign = function(target, varArgs) { // .length của function là 2 + 'use strict'; + if (target == null) { // TypeError nếu undefined hoặc null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Bỏ qua nếu undefined hoặc null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} +</pre> + +<h2 id="Đặc_tính_kỹ_thuật">Đặc tính kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div>{{Compat("javascript.builtins.Object.assign")}}</div> + +<div id="compat-mobile"></div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..c96b3f7527 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,228 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>Object.defineProperties()</strong></code> định nghĩa hoặc thay đổi tức thì các thuộc tính của một đối tượng, sau đó trả lại đối tượng đó.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Object.defineProperties(<var>obj</var>, <var>props</var>)</code></pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>Đối tượng được định nghĩa hoặc thay đổi các thuộc tính.</dd> + <dt><code>props</code></dt> + <dd>Đối tượng mà các thuộc tính có thể liệt kê (enumerable) của riêng nó sẽ cấu thành các bộ mô tả (descriptor) cho các thuộc tính được định nghĩa hoặc sửa đổi. Các bộ mô tả thuộc tính (property descriptors) có trong các đối tượng bao gồm hai loại chính: các bộ mô tả dữ liệu (data descriptors) và các bộ mô tả truy cập (accessor descriptors) (xem {{jsxref("Object.defineProperty()")}} để biết thêm chi tiết). Các bộ mô tả bao gồm các khóa sau:</dd> + <dd> + <dl> + <dt><code>configurable</code></dt> + <dd><code>true</code> if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.<br> + <strong>Defaults to <code>false</code>.</strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> if and only if this property shows up during enumeration of the properties on the corresponding object.<br> + <strong>Defaults to <code>false</code>.</strong></dd> + </dl> + + <dl> + <dt><code>value</code></dt> + <dd>The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>true</code> if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.<br> + <strong>Defaults to <code>false</code>.</strong></dd> + </dl> + + <dl> + <dt><code>get</code></dt> + <dd>A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + <dt><code>set</code></dt> + <dd>A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + </dl> + </dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Đối tượng được truyền khi gọi phương thức.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>Object.defineProperties</code>, in essence, defines all properties corresponding to the enumerable own properties of <code>props</code> on the object <code>obj</code> object.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">var obj = {}; +Object.defineProperties(obj, { + 'property1': { + value: true, + writable: true + }, + 'property2': { + value: 'Hello', + writable: false + } + // etc. etc. +}); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Assuming a pristine execution environment with all names and properties referring to their initial values, <code>Object.defineProperties</code> is almost completely equivalent (note the comment in <code>isCallable</code>) to the following reimplementation in JavaScript:</p> + +<pre class="brush: js;highlight:[8]">function defineProperties(obj, properties) { + function convertToDescriptor(desc) { + function hasProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function isCallable(v) { + // NB: modify as necessary if other values than functions are callable. + return typeof v === 'function'; + } + + if (typeof desc !== 'object' || desc === null) + throw new TypeError('bad desc'); + + var d = {}; + + if (hasProperty(desc, 'enumerable')) + d.enumerable = !!desc.enumerable; + if (hasProperty(desc, 'configurable')) + d.configurable = !!desc.configurable; + if (hasProperty(desc, 'value')) + d.value = desc.value; + if (hasProperty(desc, 'writable')) + d.writable = !!desc.writable; + if (hasProperty(desc, 'get')) { + var g = desc.get; + + if (!isCallable(g) && typeof g !== 'undefined') + throw new TypeError('bad get'); + d.get = g; + } + if (hasProperty(desc, 'set')) { + var s = desc.set; + if (!isCallable(s) && typeof s !== 'undefined') + throw new TypeError('bad set'); + d.set = s; + } + + if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) + throw new TypeError('identity-confused descriptor'); + + return d; + } + + if (typeof obj !== 'object' || obj === null) + throw new TypeError('bad obj'); + + properties = Object(properties); + + var keys = Object.keys(properties); + var descs = []; + + for (var i = 0; i < keys.length; i++) + descs.push([keys[i], convertToDescriptor(properties[keys[i]])]); + + for (var i = 0; i < descs.length; i++) + Object.defineProperty(obj, descs[i][0], descs[i][1]); + + return obj; +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>Edge</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile("11.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Tham_khảo">Tham khảo</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..87c16604ea --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,483 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>Object.defineProperty()</strong></code> định nghĩa ngay một thuộc tính mới trên một đối tượng, hoặc thay đổi một thuộc tính đã có trên một đối tượng, và trả về đối tượng đó.</p> + +<div class="note"> +<p><strong>Lưu ý:</strong> Bạn có thể gọi phương thức ngay trên {{jsxref("Object")}} hơn là trên một thể hiện của kiểu <code>Object</code>.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</code></pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>Object cần định nghĩa thuộc tính.</dd> + <dt><code>prop</code></dt> + <dd>Tên của thuộc tính sẽ định nghĩa hoặc sửa đổi.</dd> + <dt><code>descriptor</code></dt> + <dd>Mô tả cho thuộc tính được định nghĩa hoặc sửa đổi.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Object đã được truyền vào hàm.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, values added using <code>Object.defineProperty()</code> are immutable.</p> + +<p>Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A <em><dfn>data descriptor</dfn></em> is a property that has a value, which may or may not be writable. An <em><dfn>accessor descriptor</dfn></em> is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.</p> + +<p>Both data and accessor descriptors are objects. They share the following optional keys:</p> + +<dl> + <dt><code>configurable</code></dt> + <dd><code>true</code> if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.<br> + <strong>Defaults to <code>false</code>.</strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> if and only if this property shows up during enumeration of the properties on the corresponding object.<br> + <strong>Defaults to <code>false</code>.</strong></dd> +</dl> + +<p>A data descriptor also has the following optional keys:</p> + +<dl> + <dt><code>value</code></dt> + <dd>The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>true</code> if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.<br> + <strong>Defaults to <code>false</code>.</strong></dd> +</dl> + +<p>An accessor descriptor also has the following optional keys:</p> + +<dl> + <dt><code>get</code></dt> + <dd>A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. When the property is accessed, this function is called without arguments and with <code>this</code> set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property.<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + <dt><code>set</code></dt> + <dd>A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. When the property is assigned to, this function is called with one argument (the value being assigned to the property) and with <code>this</code> set to the object through which the property is assigned.<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> +</dl> + +<p>If a descriptor has neither of <code>value</code>, <code>writable</code>, <code>get</code> and <code>set</code> keys, it is treated as a data descriptor. If a descriptor has both <code>value</code> or <code>writable</code> and <code>get</code> or <code>set</code> keys, an exception is thrown.</p> + +<p>Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze the {{jsxref("Object.prototype")}} upfront, specify all options explicitly, or point to {{jsxref("null")}} with {{jsxref("Object.create", "Object.create(null)")}}.</p> + +<pre class="brush: js">// using __proto__ +var obj = {}; +var descriptor = Object.create(null); // no inherited properties +// not enumerable, not configurable, not writable as defaults +descriptor.value = 'static'; +Object.defineProperty(obj, 'key', descriptor); + +// being explicit +Object.defineProperty(obj, 'key', { + enumerable: false, + configurable: false, + writable: false, + value: 'static' +}); + +// recycling same object +function withValue(value) { + var d = withValue.d || ( + withValue.d = { + enumerable: false, + writable: false, + configurable: false, + value: null + } + ); + d.value = value; + return d; +} +// ... and ... +Object.defineProperty(obj, 'key', withValue('static')); + +// if freeze is available, prevents adding or +// removing the object prototype properties +// (value, get, set, enumerable, writable, configurable) +(Object.freeze || Object)(Object.prototype); +</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<p>If you want to see how to use the <code>Object.defineProperty</code> method with a <em>binary-flags-like</em> syntax, see <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">additional examples</a>.</p> + +<h3 id="Creating_a_property">Creating a property</h3> + +<p>When the property specified doesn't exist in the object, <code>Object.defineProperty()</code> creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are inputted.</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +// Example of an object property added +// with defineProperty with a data property descriptor +Object.defineProperty(o, 'a', { + value: 37, + writable: true, + enumerable: true, + configurable: true +}); +// 'a' property exists in the o object and its value is 37 + +// Example of an object property added +// with defineProperty with an accessor property descriptor +var bValue = 38; +Object.defineProperty(o, 'b', { + // Using shorthand method names (ES2015 feature). + // This is equivalent to: + // get: function() { return bValue; }, + // set: function(newValue) { bValue = newValue; }, + get() { return bValue; }, + set(newValue) { bValue = newValue; }, + enumerable: true, + configurable: true +}); +o.b; // 38 +// 'b' property exists in the o object and its value is 38 +// The value of o.b is now always identical to bValue, +// unless o.b is redefined + +// You cannot try to mix both: +Object.defineProperty(o, 'conflict', { + value: 0x9f91102, + get() { return 0xdeadbeef; } +}); +// throws a TypeError: value appears +// only in data descriptors, +// get appears only in accessor descriptors +</pre> + +<h3 id="Modifying_a_property">Modifying a property</h3> + +<p>When the property already exists, <code>Object.defineProperty()</code> attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its <code>configurable</code> attribute set to <code>false</code> the property is said to be “non-configurable”. It is not possible to change any attribute of a non-configurable accessor property. For data properties, it is possible to modify the value if the property is writable, and it is possible to change <code>writable</code> attribute from <code>true</code> to <code>false</code>. It is not possible to switch between data and accessor property types when the property is non-configurable.</p> + +<p>A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (except <code>value</code> and <code>writable</code>, if permitted) unless the current and new values are the same.</p> + +<h4 id="Writable_attribute">Writable attribute</h4> + +<p>When the <code>writable</code> property attribute is set to <code>false</code>, the property is said to be “non-writable”. It cannot be reassigned.</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +Object.defineProperty(o, 'a', { + value: 37, + writable: false +}); + +console.log(o.a); // logs 37 +o.a = 25; // No error thrown +// (it would throw in strict mode, +// even if the value had been the same) +console.log(o.a); // logs 37. The assignment didn't work. + +// strict mode +(function() { + 'use strict'; + var o = {}; + Object.defineProperty(o, 'b', { + value: 2, + writable: false + }); + o.b = 3; // throws TypeError: "b" is read-only + return o.b; // returns 2 without the line above +}()); +</pre> + +<p>As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.</p> + +<h4 id="Enumerable_attribute">Enumerable attribute</h4> + +<p>The <code>enumerable</code> property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + value: 1, + enumerable: true +}); +Object.defineProperty(o, 'b', { + value: 2, + enumerable: false +}); +Object.defineProperty(o, 'c', { + value: 3 +}); // enumerable defaults to false +o.d = 4; // enumerable defaults to true + // when creating a property by setting it + +for (var i in o) { + console.log(i); +} +// logs 'a' and 'd' (in undefined order) + +Object.keys(o); // ['a', 'd'] + +o.propertyIsEnumerable('a'); // true +o.propertyIsEnumerable('b'); // false +o.propertyIsEnumerable('c'); // false +</pre> + +<h4 id="Configurable_attribute">Configurable attribute</h4> + +<p>The <code>configurable</code> attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than <code>value</code> and <code>writable</code>) can be changed.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + get() { return 1; }, + configurable: false +}); + +Object.defineProperty(o, 'a', { + configurable: true +}); // throws a TypeError +Object.defineProperty(o, 'a', { + enumerable: true +}); // throws a TypeError +Object.defineProperty(o, 'a', { + set() {} +}); // throws a TypeError (set was undefined previously) +Object.defineProperty(o, 'a', { + get() { return 1; } +}); // throws a TypeError +// (even though the new get does exactly the same thing) +Object.defineProperty(o, 'a', { + value: 12 +}); // throws a TypeError + +console.log(o.a); // logs 1 +delete o.a; // Nothing happens +console.log(o.a); // logs 1 +</pre> + +<p>If the <code>configurable</code> attribute of <code>o.a</code> had been <code>true</code>, none of the errors would be thrown and the property would be deleted at the end.</p> + +<h3 id="Adding_properties_and_default_values">Adding properties and default values</h3> + +<p>It is important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using <code>Object.defineProperty()</code>, as shown in the example below.</p> + +<pre class="brush: js">var o = {}; + +o.a = 1; +// is equivalent to: +Object.defineProperty(o, 'a', { + value: 1, + writable: true, + configurable: true, + enumerable: true +}); + +// On the other hand, +Object.defineProperty(o, 'a', { value: 1 }); +// is equivalent to: +Object.defineProperty(o, 'a', { + value: 1, + writable: false, + configurable: false, + enumerable: false +}); +</pre> + +<h3 id="Custom_Setters_and_Getters">Custom Setters and Getters</h3> + +<p>The example below shows how to implement a self-archiving object. When <code>temperature</code> property is set, the <code>archive</code> array gets a log entry.</p> + +<pre class="brush: js">function Archiver() { + var temperature = null; + var archive = []; + + Object.defineProperty(this, 'temperature', { + get() { + console.log('get!'); + return temperature; + }, + set(value) { + temperature = value; + archive.push({ val: temperature }); + } + }); + + this.getArchive = function() { return archive; }; +} + +var arc = new Archiver(); +arc.temperature; // 'get!' +arc.temperature = 11; +arc.temperature = 13; +arc.getArchive(); // [{ val: 11 }, { val: 13 }] +</pre> + +<p>In this example, a getter always returns the same value.</p> + +<pre class="brush: js">var pattern = { + get() { + return 'I always return this string, ' + + 'whatever you have assigned'; + }, + set() { + this.myname = 'this is my name string'; + } +}; + +function TestDefineSetAndGet() { + Object.defineProperty(this, 'myproperty', pattern); +} + +var instance = new TestDefineSetAndGet(); +instance.myproperty = 'test'; +console.log(instance.myproperty); +// I always return this string, whatever you have assigned + +console.log(instance.myname); // this is my name string +</pre> + +<h3 id="Inheritance_of_properties">Inheritance of properties</h3> + +<p>If an accessor property is inherited, its <code>get</code> and <code>set</code> methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.</p> + +<pre class="brush: js">function myclass() { +} + +var value; +Object.defineProperty(myclass.prototype, "x", { + get() { + return value; + }, + set(x) { + value = x; + } +}); + +var a = new myclass(); +var b = new myclass(); +a.x = 1; +console.log(b.x); // 1 +</pre> + +<p>This can be fixed by storing the value in another property. In <code>get</code> and <code>set</code> methods, <code>this</code> points to the object which is used to access or modify the property.</p> + +<pre class="brush: js">function myclass() { +} + +Object.defineProperty(myclass.prototype, "x", { + get() { + return this.stored_x; + }, + set(x) { + this.stored_x = x; + } +}); + +var a = new myclass(); +var b = new myclass(); +a.x = 1; +console.log(b.x); // undefined +</pre> + +<p>Unlike accessor properties, value properties are always set on the object itself, not on a prototype. However, if a non-writable value property is inherited, it still prevents from modifying the property on the object.</p> + +<pre class="brush: js">function myclass() { +} + +myclass.prototype.x = 1; +Object.defineProperty(myclass.prototype, "y", { + writable: false, + value: 1 +}); + +var a = new myclass(); +a.x = 2; +console.log(a.x); // 2 +console.log(myclass.prototype.x); // 1 +a.y = 2; // Ignored, throws in strict mode +console.log(a.y); // 1 +console.log(myclass.prototype.y); // 1 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.defineProperty")}}</p> +</div> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<h3 id="Redefining_the_length_property_of_an_Array_object">Redefining the <code>length</code> property of an <code>Array</code> object</h3> + +<p>It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array, it's possible to change the {{jsxref("Array.length", "length")}} property's value or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.</p> + +<p>Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.</p> + +<p>Versions of Chrome which implement <code>Object.defineProperty()</code> in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.</p> + +<p>Versions of Safari which implement <code>Object.defineProperty()</code> ignore a <code>length</code> value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.</p> + +<p>Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you <em>can</em> rely on it, <a href="http://whereswalden.com/2013/08/05/new-in-firefox-23-the-length-property-of-an-array-can-be-made-non-writable-but-you-shouldnt-do-it/">there's really no good reason to do so</a>.</p> + +<h3 id="Internet_Explorer_8_specific_notes">Internet Explorer 8 specific notes</h3> + +<p>Internet Explorer 8 implemented a <code>Object.defineProperty()</code> method that could <a class="external" href="https://msdn.microsoft.com/en-us/library/dd229916%28VS.85%29.aspx">only be used on DOM objects</a>. A few things need to be noted:</p> + +<ul> + <li>Trying to use <code>Object.defineProperty()</code> on native objects throws an error.</li> + <li>Property attributes must be set to some values. The <code>configurable</code>, <code>enumerable</code> and <code>writable</code> attributes should all be set to <code>true</code> for data descriptor and <code>true</code> for <code>configurable</code>, <code>false</code> for <code>enumerable</code> for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.</li> + <li>Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li>{{jsxref("Object.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}}</li> + <li>{{jsxref("Object.prototype.watch()")}}</li> + <li>{{jsxref("Object.prototype.unwatch()")}}</li> + <li>{{jsxref("Operators/get", "get")}}</li> + <li>{{jsxref("Operators/set", "set")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">Additional <code>Object.defineProperty</code> examples</a></li> + <li>{{jsxref("Reflect.defineProperty()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html b/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html new file mode 100644 index 0000000000..d1e533fceb --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html @@ -0,0 +1,156 @@ +--- +title: Object.getOwnPropertyNames() +slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Object.getOwnPropertyNames()</code></strong> phuong thuc nay tra ve mang (including non-enumerable properties except for those which use Symbol) found directly in a given object.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-getownpropertynames.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="brush: js">Object.getOwnPropertyNames(<var>obj</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><var>obj</var></code></dt> + <dd>The object whose enumerable and non-enumerable properties are to be returned.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>An array of strings that corresponds to the properties found directly in the given object.</p> + +<h2 id="Description">Description</h2> + +<p><code>Object.getOwnPropertyNames()</code> returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object <code><var>obj</var></code>. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a {{jsxref("Statements/for...in", "for...in")}} loop (or by {{jsxref("Object.keys()")}}) over the properties of the object. The ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Object.getOwnPropertyNames">Using <code>Object.getOwnPropertyNames()</code></h3> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; +console.log(Object.getOwnPropertyNames(arr).sort()); +// logs ["0", "1", "2", "length"] + +// Array-like object +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.getOwnPropertyNames(obj).sort()); +// logs ["0", "1", "2"] + +// Logging property names and values using Array.forEach +Object.getOwnPropertyNames(obj).forEach( + function (val, idx, array) { + console.log(val + ' -> ' + obj[val]); + } +); +// logs +// 0 -> a +// 1 -> b +// 2 -> c + +// non-enumerable property +var my_obj = Object.create({}, { + getFoo: { + value: function() { return this.foo; }, + enumerable: false + } +}); +my_obj.foo = 1; + +console.log(Object.getOwnPropertyNames(my_obj).sort()); +// logs ["foo", "getFoo"] +</pre> + +<p>If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}}).</p> + +<p>Items on the prototype chain are not listed:</p> + +<pre class="brush: js">function ParentClass() {} +ParentClass.prototype.inheritedMethod = function() {}; + +function ChildClass() { + this.prop = 5; + this.method = function() {}; +} +ChildClass.prototype = new ParentClass; +ChildClass.prototype.prototypeMethod = function() {}; + +console.log( + Object.getOwnPropertyNames( + new ChildClass() // ["prop", "method"] + ) +); +</pre> + +<h3 id="Get_non-enumerable_properties_only">Get non-enumerable properties only</h3> + +<p>This uses the {{jsxref("Array.prototype.filter()")}} function to remove the enumerable keys (obtained with {{jsxref("Object.keys()")}}) from a list of all keys (obtained with <code>Object.getOwnPropertyNames()</code>) thus giving only the non-enumerable keys as output.</p> + +<pre class="brush: js">var target = myObject; +var enum_and_nonenum = Object.getOwnPropertyNames(target); +var enum_only = Object.keys(target); +var nonenum_only = enum_and_nonenum.filter(function(key) { + var indexInEnum = enum_only.indexOf(key); + if (indexInEnum == -1) { + // Not found in enum_only keys, + // meaning that the key is non-enumerable, + // so return true so we keep this in the filter + return true; + } else { + return false; + } +}); + +console.log(nonenum_only); +</pre> + +<h2 id="Notes">Notes</h2> + +<p>In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be coerced to an object.</p> + +<pre class="brush: js">Object.getOwnPropertyNames('foo'); +// TypeError: "foo" is not an object (ES5 code) + +Object.getOwnPropertyNames('foo'); +// ["0", "1", "2", "length"] (ES2015 code) +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.getownpropertynames', 'Object.getOwnPropertyNames')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Object.getOwnPropertyNames")}}</p> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<p>Prior to Firefox 28, <code>Object.getOwnPropertyNames</code> did not see unresolved properties of {{jsxref("Error")}} objects. This has been fixed in later versions (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=724768">bug 724768</a>).</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.prototype.hasOwnProperty()")}}</li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Array.forEach()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/index.html b/files/vi/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..06fd8ef967 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,213 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p>The <code><strong>Object</strong></code> constructor creates an object wrapper.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.</dd> + <dt><code>value</code></dt> + <dd>Any value.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>The <code>Object</code> constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.</p> + +<p>When called in a non-constructor context, <code>Object</code> behaves identically to <code>new Object()</code>.</p> + +<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Properties_of_the_Object_constructor">Properties of the <code>Object</code> constructor</h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Has a value of 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Allows the addition of properties to all objects of type Object.</dd> +</dl> + +<h2 id="Methods_of_the_Object_constructor">Methods of the <code>Object</code> constructor</h2> + +<dl> + <dt>{{jsxref("Object.assign()")}} {{experimental_inline}}</dt> + <dd>Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Creates a new object with the specified prototype object and properties.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Adds the named property described by a given descriptor to an object.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Adds the named properties described by the given descriptors to an object.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}} {{experimental_inline}}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}} {{experimental_inline}}</dt> + <dd>Compares if two values are distinguishable (ie. the same)</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable properties.</dd> + <dt>{{jsxref("Object.observe()")}} {{experimental_inline}}</dt> + <dd>Asynchronously observes changes to an object.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property)</dd> +</dl> + +<h2 id="Object_instances_and_Object_prototype_object"><code>Object</code> instances and <code>Object</code> prototype object</h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Object_given_undefined_and_null_types">Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>The following examples store an empty <code>Object</code> object in <code>o</code>:</p> + +<pre class="brush: js">var o = new Object(); +</pre> + +<pre class="brush: js">var o = new Object(undefined); +</pre> + +<pre class="brush: js">var o = new Object(null); +</pre> + +<h3 id="Using_Object_to_create_Boolean_objects">Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>The following examples store {{jsxref("Boolean")}} objects in <code>o</code>:</p> + +<pre class="brush: js">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/observe/index.html b/files/vi/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..f9074ea94e --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,193 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +tags: + - ECMAScript7 + - Experimental + - JavaScript + - Method + - Object +translation_of: Archive/Web/JavaScript/Object.observe +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object.observe()</code></strong> được sử dụng để đồng bộ quan sát những thay đổi cho một đối tượng. Nó cung cấp một dòng thay đổi trong thứ tự mà chúng xảy ra.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code>Object.observe(<var>obj</var>, <var>callback</var>[, <var>acceptList</var>])</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>Đối tượng được quan sát.</dd> + <dt><code>callback</code></dt> + <dd>Hàm được gọi mỗi lần có thay đổi trong <code>obj</code>, với những tham số sau: + <dl> + <dt><code>changes</code></dt> + <dd>Một mảng các đối tượng mô tả sự thay đổi. Mỗi đối tượng chứa các thuộc tính: + <ul> + <li><strong><code>name</code></strong>: Tên thuộc tính đã thay đổi.</li> + <li><strong><code>object</code></strong>: Đối tượng được thay đổi.</li> + <li><strong><code>type</code></strong>: Một chuỗi cho biết loại thay đổi đang diễn ra. Có thể là <code>"add"</code>, <code>"update"</code>, hoặc <code>"delete"</code>.</li> + <li><strong><code>oldValue</code></strong>: Chỉ có cho loại <code>"update"</code> và <code>"delete"</code>. Cho biết giá trị trước khi thay đổi.</li> + </ul> + </dd> + </dl> + </dd> + <dt><code>acceptList</code></dt> + <dd>Danh sách các loại thay đổi được quan sát. Nếu bỏ qua, mặc định là <code>["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"]</code>.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hàm<code> callback</code> được gọi mỗi khi có thay đổi trong <code>obj</code>, với một mảng các đối tượng chứa thông tin về sự thay đổi.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Ghi_lại_tất_cả_sáu_loại_thay_đổi_khác_nhau">Ghi lại tất cả sáu loại thay đổi khác nhau</h3> + +<pre class="brush: js">var obj = { + foo: 0, + bar: 1 +}; + +Object.observe(obj, function(changes) { + console.log(changes); +}); + +obj.baz = 2; +// [{name: 'baz', object: <obj>, type: 'add'}] + +obj.foo = 'hello'; +// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}] + +delete obj.baz; +// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}] + +Object.defineProperty(obj, 'foo', {writable: false}); +// [{name: 'foo', object: <obj>, type: 'reconfigure'}] + +Object.setPrototypeOf(obj, {}); +// [{name: '__proto__', object: <obj>, type: 'setPrototype', oldValue: <prototype>}] + +Object.seal(obj); +// [ +// {name: 'foo', object: <obj>, type: 'reconfigure'}, +// {name: 'bar', object: <obj>, type: 'reconfigure'}, +// {object: <obj>, type: 'preventExtensions'} +// ] +</pre> + +<h3 id="Ràng_buộc_dữ_liệu">Ràng buộc dữ liệu</h3> + +<pre class="brush: js">// Mô hình user +var user = { + id: 0, + name: 'Brendan Eich', + title: 'Mr.' +}; + +// Lời chào tới user +function updateGreeting() { + user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!'; +} +updateGreeting(); + +Object.observe(user, function(changes) { + changes.forEach(function(change) { + // Bất kỳ khi nào tên hoặc danh hiệu thay đổi, gọi updateGreeting() + if (change.name === 'name' || change.name === 'title') { + updateGreeting(); + } + }); +}); +</pre> + +<h3 id="Loại_thay_đổi_tùy_chỉnh">Loại thay đổi tùy chỉnh</h3> + +<pre class="brush: js">// Một điểm trên một mặt phẳng +var point = {x: 0, y: 0, distance: 0}; + +function setPosition(pt, x, y) { + // Thực hiện thay đổi tùy chỉnh + Object.getNotifier(pt).performChange('reposition', function() { + var oldDistance = pt.distance; + pt.x = x; + pt.y = y; + pt.distance = Math.sqrt(x * x + y * y); + return {oldDistance: oldDistance}; + }); +} + +Object.observe(point, function(changes) { + console.log('Distance change: ' + (point.distance - changes[0].oldDistance)); +}, ['reposition']); + +setPosition(point, 3, 4); +// Distance change: 5 +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<p><a href="https://github.com/arv/ecmascript-object-observe">Strawman proposal for ECMAScript 7</a>.</p> + +<h2 id="Khả_năng_tương_thích_trình_duyệt">Khả năng tương thích trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("23")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Android</th> + <th>Chrome dành cho Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("23")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Object.unobserve()")}} {{experimental_inline}}</li> + <li>{{jsxref("Array.observe()")}} {{experimental_inline}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/tostring/index.html b/files/vi/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..78a46f1272 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,128 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>toString()</strong></code> trả về một chuỗi đại diện cho object.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>obj</var>.toString()</code></pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chuỗi đại diện cho object.</p> + +<h2 id="Miêu_tả">Miêu tả</h2> + +<p>Mỗi object có 1 phương thức <code>toString()</code>. Phương thức này được tự động gọi khi object được biểu diễn dưới dạng text hoặc trong bối cảnh mà một chuỗi được mong đợi để trả về. Mặc định, phương thức <code>toString()</code> được kế thừa cho tất cả object khi tất cả object được kế thừa từ <code>Object</code>. Nếu phương thức này không bị ghi đè bởi một object đã được tuỳ chỉnh, phương thức này trả về "[object <em>type</em>]", trong đó <code><em>type </em></code>là kiểu của object. Phần code theo sau mô tả điều này:</p> + +<pre class="brush: js">var o = new Object(); +o.toString(); // returns [object Object] +</pre> + +<div class="note"> +<p><strong>Note:</strong> Kể từ JavaScript 1.8.5, <code>toString()</code> khi được gọi trong {{jsxref("null")}} sẽ trả về <code>[object <em>Null</em>]</code>, và {{jsxref("undefined")}} sẽ trả về <code>[object <em>Undefined</em>]</code>, như đã được định nghĩa trong 5th Edition of ECMAScript and a subsequent Errata. Tham khảo {{anch("Using_toString()_to_detect_object_class", "Using_toString()_to_detect_object_class")}}.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Ghi_đè_phương_thức_mặc_định_toString">Ghi đè phương thức mặc định <code>toString</code></h3> + +<p>Bạn có thể tạo một hàm để thay thể phương thức mặc định <code>toString()</code>. Phương thức mặc định <code>toString()</code> không có tham số truyền vào và sẽ trả về một chuỗi. Phương thức <code>toString()</code> bạn tự tạo có thể trả về bất kì giá trị gì bạn muốn, nhưng sẽ tốt hơn nếu nó mang thông tin về object.</p> + +<p>Phần code sau đây định nghĩa kiểu <code>Dog</code> object và tạo ra <code>theDog</code>, một object của kiểu <code>Dog</code>:</p> + +<pre class="brush: js">function Dog(name, breed, color, sex) { + this.name = name; + this.breed = breed; + this.color = color; + this.sex = sex; +} + +theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female'); +</pre> + +<p>Nếu bạn gọi phương thức <code>toString()</code> trên object tuỳ chỉnh này, nó sẽ trả về giá trị mặc định được kế thừa từ {{jsxref("Object")}}:</p> + +<pre class="brush: js">theDog.toString(); // returns [object Object] +</pre> + +<p>Phần code sau đây tạo ra và gán <code>dogToString()</code> để ghi đè lên phương thức mặc định <code>toString()</code>. Hàm này sẽ tạo một chuỗi chứa tên, giống, màu và giới tính của object, theo dạng "<code>property = value;</code>".</p> + +<pre class="brush: js">Dog.prototype.toString = function dogToString() { + var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; + return ret; +} +</pre> + +<p>Với phần code ở phía trên, mỗi khi <code>theDog</code> được sử dụng để trả về một chuỗi, JavaScript sẽ tự động gọi hàm <code>dogToString()</code>, trả về kết quả sau:</p> + +<pre class="brush: js">"Dog Gabby is a female chocolate Lab" +</pre> + +<h3 id="Sử_dụng_toString_để_xác_định_lớp_đối_tượng">Sử dụng <code>toString()</code> để xác định lớp đối tượng</h3> + +<p><code>toString()</code> có thể được sử dụng với tất cả object và cho phép bạn xác định lớp của object đó. Để sử dụng <code>Object.prototype.toString()</code> với mọi đối tượng, bạn cần gọi {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} trên object đó, truyền vào object mà bạn muốn vào tham số đầu tiên hay còn được gọi là <code>thisArg</code>.</p> + +<pre class="brush: js">var toString = Object.prototype.toString; + +toString.call(new Date); // [object Date] +toString.call(new String); // [object String] +toString.call(Math); // [object Math] + +// Since JavaScript 1.8.5 +toString.call(undefined); // [object Undefined] +toString.call(null); // [object Null] +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Call on {{jsxref("null")}} returns <code>[object <em>Null</em>]</code>, and {{jsxref("undefined")}} returns <code>[object <em>Undefined</em>]</code></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_với_trình_duyệt">Tính tương thích với trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.toString")}}</p> +</div> + +<h2 id="Tham_khảo_thêm">Tham khảo thêm</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> + <li>{{jsxref("Symbol.toPrimitive")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/object/valueof/index.html b/files/vi/web/javascript/reference/global_objects/object/valueof/index.html new file mode 100644 index 0000000000..44a440e1f6 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/valueof/index.html @@ -0,0 +1,108 @@ +--- +title: Object.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>valueOf()</strong></code> trả về giá trị nguyên thuỷ(primitive value) của object đang được nói tới.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>object</var>.valueOf()</code></pre> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Giá trị nguyên thuỷ(primitive value) của object đang được nói tới.</p> + +<h2 id="Miêu_tả">Miêu tả</h2> + +<p>JavaScript gọi phương thức <code>valueOf</code> để chuyển đổi một object sang một giá trị nguyên thuỷ. Bạn hiếp khi cần gọi phương thức <code>valueOf</code> bởi chính bạn; JavaScript tự động gọi nó khi gặp phải một object ở chỗ mà một giá trị nguyên thuỷ cần được trả về.</p> + +<p>Mặc định, phương thức <code>valueOf</code> được kế thừa cho mọi object khi mà mọi object đó được kế thừa từ {{jsxref("Object")}}. Mọi core-object được tạo sẵn để ghi đè phương thức này để trả về giá trị phù hợp. Nếu một object ko có giá trị nguyên thuỷ, valueOf sẽ trả về chính object đó.</p> + +<p>Bạn có thể sử dụng <code>valueOf</code> trong code của bạn để chuyển đổi một object được tạo sẵn thành một giá trị nguyên thuỷ. Khi bạn tạo một object tuỳ chỉnh, bạn có thể ghi đè <code>Object.prototype.valueOf()</code> để gọi phương thức tuỳ chỉnh thay vì phương thức mặc định {{jsxref("Object")}}.</p> + +<h3 id="Ghi_đè_valueOf_cho_object_tuỳ_chỉnh">Ghi đè <code>valueOf</code> cho object tuỳ chỉnh</h3> + +<p>Bạn có thể tạo một hàm để được gọi thay thể cho phương thức <code>valueOf</code>. Hàm của bạn phải không nhận tham số nào cả.</p> + +<p>Giả sử bạn có một object loại <code>MyNumberType</code> và bạn muốn tạo một phương thức <code>valueOf</code> cho nó. Phần code sau đây gán một hàm định nghĩa bới người dùng cho phương thức <code>valueOf</code> của object:</p> + +<pre class="brush: js">MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; };</pre> + +<p> </p> + +<p>Với phần code phía trên, mỗi khi một object loại <code>MyNumberType</code> được sử dụng trong bối cảnh mà nó cần được biểu diễn bởi một giá trị nguyên thuỷ, JavaScript sẽ tự động gọi hàm đã được viết trên đây.</p> + +<p>Một phương thức <code>valueOf</code> của object thường được gọi bởi JavaScript, nhưng bạn có thể tự gọi nó bằng cách sau:</p> + +<pre class="brush: js">myNumberType.valueOf()</pre> + +<div class="note"> +<p><strong>Note:</strong> Objects in string contexts convert via the {{jsxref("Object.toString", "toString()")}} method, which is different from {{jsxref("String")}} objects converting to string primitives using <code>valueOf</code>. All objects have a string conversion, if only "<code>[object <em>type</em>]</code>". But many objects do not convert to number, boolean, or function.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_valueOf">Sử dụng <code>valueOf</code></h3> + +<pre class="brush: js">function MyNumberType(n) { + this.number = n; +} + +MyNumberType.prototype.valueOf = function() { + return this.number; +}; + +var myObj = new MyNumberType(4); +myObj + 3; // 7 +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.4', 'Object.prototype.valueOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tính_tương_thích_trình_duyệt">Tính tương thích trình duyệt</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.valueOf")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> + <li>{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("Symbol.toPrimitive")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/promise/all/index.html b/files/vi/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..403b8b5161 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,121 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>Promise.all(iterable)</strong></code> trả ra một Promise mới và promise mới này chỉ được kết thúc khi tất cả các promise trong <code><strong>iterable </strong></code>kết thúc hoặc có một promise nào đó xử lý thất bại. Kết quả của promise mới này là một mảng chứa kết quả của tất cả các promise theo đúng thứ tự hoặc kết quả lỗi của promise gây lỗi.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>Promise.all(iterable)</var>;</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt>iterable</dt> + <dd>Một đối tượng có thể duyệt lặp. Ví dụ như một mảng {{jsxref("Array")}}. Để hiểu thêm về đối tượng có thể duyệt lặp, bạn có thể xem tại đây <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a>.</dd> +</dl> + +<h3 id="Đầu_ra">Đầu ra</h3> + +<p>Kết quả trả ra là một {{jsxref("Promise")}}. Promise này chỉ được kết thúc khi mà tất cả các promise trong interable truyền vào được kết thúc hoặc một promise nào đó thất bại.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><strong>Promise.all </strong>sẽ lưu kết quả trả ra của tất cả các promise bằng một mảng theo đúng thứ tự của các promise đầu vào. Bạn lưu ý là thứ tự của các promise đầu vào chứ không phải là thứ tự kết thúc cả các promise. Ngoài ra, với các phần tử đầu vào không phải là một Promise, thì nó sẽ được coi là một giá trị trả ra và được trả với phương thức {{jsxref("Promise.resolve")}}. Tức là nó được đóng gói với 1 promise mới chứa kết quả là chính nó. </p> + +<p>Nếu một promise nào đó bị lỗi, thì Promise.all sẽ bị kết thúc với mã lỗi của promise lỗi đó ngay lập tức. Trong trường hợp này, tất cả các promise khác dù đã kết thúc hay chưa thì đều không được quan tâm nữa.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_Promise.all">Sử dụng <code>Promise.all</code></h3> + +<p><code>Promise.all</code> đợi tất cả các promise kết thúc, hoặc một promise nào đó thât bại.</p> + +<pre class="brush: js">var p1 = Promise.resolve(3); +var p2 = 1337; +var p3 = new Promise((resolve, reject) => { + setTimeout(resolve, 100, "foo"); +}); + +Promise.all([p1, p2, p3]).then(values => { + console.log(values); // [3, 1337, "foo"] +});</pre> + +<h3 id="Promise.all_kết_thúc_ngay_khi_có_lỗi"><code>Promise.all</code> kết thúc ngay khi có lỗi</h3> + +<p><code>Promise.all</code> sẽ bị kết thúc lỗi ngay khi có một promise nào đó bị lỗi.</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(resolve, 1000, "one"); +}); +var p2 = new Promise((resolve, reject) => { + setTimeout(resolve, 2000, "two"); +}); +var p3 = new Promise((resolve, reject) => { + setTimeout(resolve, 3000, "three"); +}); +var p4 = new Promise((resolve, reject) => { + setTimeout(resolve, 4000, "four"); +}); +var p5 = new Promise((resolve, reject) => { + reject("reject"); +}); + +Promise.all([p1, p2, p3, p4, p5]).then(values => { + console.log(values); +}, reason => { + console.log(reason) +}); + +//From console: +//"reject" + +// Evenly, it's possible to use .catch +Promise.all([p1, p2, p3, p4, p5]).then(values => { + console.log(values); +}).catch(reason => { + console.log(reason) +}); + +//From console: +//"reject" + +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> + +<p>{{Compat}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.race()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/promise/catch/index.html b/files/vi/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..0564b81afd --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,136 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong>catch()</strong> trả ra một <code>Promise</code> để xử lý trường hợp xử lý của ta thất bại. Nó cũng giống như {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} nhưng chỉ được gọi khi thao tác của ta thất bại.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>p.catch(onRejected)</var>; + +p.catch(function(reason) { + // rejection +}); +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt>onRejected</dt> + <dd>Một hàm {{jsxref("Function")}} được gọi khi mà <code>Promise</code> của ta thất bại. Hàm này có một tham số đầu vào là: + <dl> + <dt><code>reason</code></dt> + <dd>Lý do lỗi.</dd> + </dl> + </dd> +</dl> + +<h3 id="Trả_ra">Trả ra</h3> + +<p>Một {{jsxref("Promise")}} mới.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thước <code>catch</code> rất hữu ích cho việc xử lý các lỗi xảy ra trong 1 Promise hoặc một chuỗi Promise có quan hệ thứ tự với nhau (đợi nhau).</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_phương_thức_catch">Sử dụng phương thức catch</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + resolve('Success'); +}); + +p1.then(function(value) { + console.log(value); // "Success!" + throw 'oh, no!'; +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); + +// The following behaves the same as above +p1.then(function(value) { + console.log(value); // "Success!" + return Promise.reject('oh, no!'); +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); +</pre> + +<h3 id="Lấy_mã_lỗi_khi_ném_lỗi">Lấy mã lỗi khi ném lỗi</h3> + +<pre class="brush: js">// Throwing an error will call the catch method most of the time +var p1 = new Promise(function(resolve, reject) { + throw 'Uh-oh!'; +}); + +p1.catch(function(e) { + console.log(e); // "Uh-oh!" +}); + +// Errors thrown inside asynchronous functions will act like uncaught errors +var p2 = new Promise(function(resolve, reject) { + setTimeout(function() { + throw 'Uncaught Exception!'; + }, 1000); +}); + +p2.catch(function(e) { + console.log(e); // This is never called +}); + +// Errors thrown after resolve is called will be silenced +var p3 = new Promise(function(resolve, reject) { + resolve(); + throw 'Silenced Exception!'; +}); + +p3.catch(function(e) { + console.log(e); // This is never called +});</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> + +<p>{{Compat}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/promise/finally/index.html b/files/vi/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..a8796382a2 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,95 @@ +--- +title: Promise.prototype.finally() +slug: Web/JavaScript/Reference/Global_Objects/Promise/finally +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>finally()</strong></code> trả về một {{jsxref("Promise")}}. Một khi <em>promise</em> được thực hiện (<em>settle</em>), dù kết quả là <em>fulfilled</em> hay <em>rejected</em>, thì hàm <em>callback</em> đã chỉ định sẽ được thực thi. Đây là cách để làm cho một đoạn code phải được thực thi sau khi <code>Promise</code> hoàn thành, dù kết quả là fulfilled hay rejected.</p> + +<p>Cách này giúp bạn tránh phải viết những dòng code trùng lặp giữa hai phương thức xử lý {{jsxref("Promise.then", "then()")}} và {{jsxref("Promise.catch", "catch()")}}.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>p.finally(onFinally)</var>; + +p.finally(function() { + // settled (fulfilled or rejected) +}); +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>onFinally</code></dt> + <dd>Một {{jsxref("Function")}} được gọi khi <code>Promise</code> được thực hiện</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Return a {{jsxref("Promise")}} whose <code>finally</code> handler is set to the specified function, <code>onFinally</code>.</p> + +<h2 id="Description">Description</h2> + +<p>Phương thức <code>finally()</code> hữu ích khi bạn muốn xử lý công việc sau khi promise được thực hiện.</p> + +<p>Phương thức <code>finally()</code> cũng tương tự như việc gọi <code>.then(onFinally, onFinally)</code> , tuy nhiên có một số sự khác biệt:</p> + +<ul> + <li>Khi tạo một hàm inline, bạn có thể gán nó một lần, thay vì phải định nghĩa tới hai lần, hoặc phải tạo thêm biến cho nó.</li> + <li>Một callback <code style="letter-spacing: -0.00333rem;">finally</code><span style="letter-spacing: -0.00333rem;"> sẽ không nhận tham số nào, vì không có cách xác đáng nào để biết liệu promise đã fulfilled hay bị rejected. Bạn dùng tới hàm này trong trường hợp bạn không quan tâm đến kết quả khi fulfilled, hay lý do khi reject. Vậy nên, không dùng tới thì bạn không cần phải truyền vào.</span></li> + <li>Không như <code>Promise.resolve(2).then(() => {}, () => {})</code> (sẽ được resolve với <code>undefined</code>), <code>Promise.resolve(2).finally(() => {})</code> sẽ được resolve với <code>2</code>.</li> + <li>Tương tự, không như <code>Promise.reject(3).then(() => {}, () => {})</code> (sẽ được fulfill với <code>undefined</code>), <code>Promise.reject(3).finally(() => {})</code> sẽ bị reject với <code>3</code>.</li> +</ul> + +<div class="note"> +<p><strong>Note:</strong> Một <code>throw</code> (hoặc trả về một promise bị reject) trong callback <code>finally</code> sẽ reject cái promise mới với lý do reject được chỉ định khi gọi <code>throw()</code>.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">let isLoading = true; + +fetch(myRequest).then(function(response) { + var contentType = response.headers.get("content-type"); + if(contentType && contentType.includes("application/json")) { + return response.json(); + } + throw new TypeError("Oops, we haven't got JSON!"); + }) + .then(function(json) { /* process your JSON further */ }) + .catch(function(error) { console.log(error); }) + .finally(function() { isLoading = false; }); + +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://github.com/tc39/proposal-promise-finally">TC39 proposal</a></td> + <td>Stage 4</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.finally")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> + <li>{{jsxref("Promise.prototype.catch()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/promise/index.html b/files/vi/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..9b069daf74 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p><strong><code>Promise</code></strong> là một đối tượng đặc biệt dùng cho các xử lý bất đồng bộ. Nó đại diện cho một xử lý bất đồng bộ và chứa kết quả cũng như các lỗi xảy ra từ xử lý bất đồng bộ đó.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">new Promise(executor); +new Promise(function(resolve, reject) { ... } );</pre> + +<h3 id="Tham_số_đầu_vào">Tham số đầu vào</h3> + +<dl> + <dt>executor</dt> + <dd>Một hàm có 2 tham số đầu vào là 2 hàm phản hồi <code>resolve</code> và <code>reject</code>. Hàm <code>resolve </code>sẽ được gọi khi xử lý thành công, còn <code>reject</code> sẽ được gọi khi xử lý thất bại. </dd> + <dd>* Chú ý: 2 hàm phản hồi này rất dễ bị nhầm lẫn với phong cách của hàm phản hồi của Node.js. Với Node.js hàm phản hồi lỗi thường là tham số đầu tiên, còn Promise thì ngược lại.</dd> + <dd>Hàm <code>executor</code> sẽ được gọi ngay khi Promise được gọi tới, tức là nó còn được chạy trước cả hàm khởi tạo trả ra kết quả của Promise. Sau khi xử lý kết thúc tùy theo tình huống mà hàm phản hồi <code>resolve</code> hoặc <code>reject</code> sẽ được gọi tới. Trường hợp xử lý thành công thì hàm <code>resolve</code> sẽ được gọi tới để trả ra kết quả. Còn trường hợp thất bại thì hàm <code>reject</code> sẽ được gọi tới để trả ra mã lỗi thực thi.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Một <code><strong>Promise</strong></code> có thể như một proxy đại diện cho một giá trị mà ta không cần phải biết ngay khi khởi tạo. Bằng các sử dụng <code><strong>Promise</strong></code> ta có thể kết hợp với các hàm xử lý khác để sử dụng kết quả sau khi thực thi xử lý bất đồng bộ mà nó đang đại diện. Vì vậy mà ta có thể lập trình bất đồng bộ gần giống với kiểu lập trình đồng bộ - tức là đợi xử lý bất đồng bộ xong mới thực thi các thao tác mà cần sử dụng tới kết quả của xử lý đó. Để có thể làm được việc đó thay vì trả ra kết quả của việc xử lý đồng bộ, <code><strong>Promise</strong></code> sẽ trả ra một <em>promise</em> khác. Bằng promise mới này ta lại có thể lặp lại việc sử dụng kết quả của thao tác xử lý lúc trước để làm đầu vào cho các thao tác xử lý lúc sau.</p> + +<p>Tại mỗi thời điểm <code>Promise</code> sẽ có thể ở một trong các trạng thái sau:</p> + +<ul> + <li><em>pending</em>: Trạng thái chờ xử lý kết thúc. Trạng thái này chính là trạng thái ban đầu của Promise, nó thể hiện rằng thao tác xử lý của ta chưa kết thúc.</li> + <li><em>fulfilled</em>: Trạng thái xử lý thành công. Trạng thái này thể hiện rằng thao tác xử lý của ta đã kết thúc và thành công.</li> + <li><em>rejected</em>: Trạng thái xử lý thất bại. Trạng thái này thể hiện thao tác xử lý đã kết thúc và thất bại.</li> +</ul> + +<p>Như vậy một Promise khi ở trạng thái pending sẽ được chuyển thành trạng thái <em>fulfilled</em> với kết quả thành công hoặc trạng thái <em>rejected</em> kèm với mã lỗi xảy ra khi xử lý kết thúc. Sau khi xử lý kết thúc, bất kể trạng thái được chuyển thành là thành công hay thất bại thì các hàm xử lý được đính kèm sẽ được gọi thực thi. Để đính kèm một hàm cho Promise, ta có thể sử dụng <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> cho trường hợp thành công và <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}} cho trường hợp xử lý thất bại.</code></p> + +<p><code><font face="Open Sans, Arial, sans-serif">Hàm đính kèm xử lý </font>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> và <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> sẽ trả ra một promise khác nên thao tác hậu xử lý bằng hàm đính kèm có thể được chuyển tiếp kiểu xử lý chuỗi (chained). Cụ thể hơn ta có thể xem hình dưới đây.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png"></p> + +<p>Như hình minh họa hoạt động của Promise trên, ta có thể thấy khi khởi tạo Promise sẽ có trạng thái là pending. Sau khi xử lý kết thúc, tùy theo kết quả xử lý mà trạng thái sẽ là fullfil hoặc reject. Lúc đó các hàm đính kèm sẽ được thực thi thông qua hàm <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> hoặc <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code>. Chính các hàm này lại trả ra một Promise khác nên ta có thể xử lý một loạt các thao tác phía sau một cách chuyển tiếp.</p> + +<p> </p> + +<div class="note"> +<p><strong>Đừng nhầm lẫn với:</strong> một số ngôn ngữ khác như Scheme cũng có khái niệm “promises” - nhưng khái niệm này để chỉ thị một thao tác được gọi thực thi sau. Còn, Promises trong JavaScript biểu diễn các thao tác bất đồng bộ mà đã được thực thi (thao tác bất đồng bộ này được gọi ngay khi ta gọi Promise - ngay cả trước khi hàm khởi tạo của Promise được gọi tới) và có thể đính kèm các hàm hậu xử lý sau khi xử lý bất đồng bộ mà nó biểu diễn kết thúc. Nếu bạn muốn dùng các thao tác kiểu thi sau như vậy thì có thể sử dụng hàm mũi tên (<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a>) không có tham số đầu vào, như: <code>f = () => <em>expression</em></code> để tạo một hàm được gọi sau, và sử dụng <code>f()</code> để thực thi nó.</p> +</div> + +<div class="note"> +<p><strong>Lưu ý</strong>: Promise được gọi kết thúc (<em>settled) </em>khi và chỉ khi nó ở trạng thái fulfilled (thành công) hoặc rejected (thất bại). Đôi lúc có thể bạn thấy đâu đó nói rằng Promise được giải quyết xong (<em>resolved)</em> để ám chỉ rằng Promise được kết thúc, lúc đó đừng nhầm lẫn là nó được kết thúc thành công vì nó chỉ đơn giản là nói tới Promise đã được kết thúc mà thôi. Để biết rõ hơn về các thuật ngữ liên quan tới Promise, bạn có thể tham khảo bài viết này: <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a>.</p> +</div> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>Thuộc tính length này luôn có giá trị là 1 (số lượng của tham số khởi tạo).</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd>Biểu diễn prototype cho hàm khởi tạo <code>Promise</code>.</dd> +</dl> + +<h2 id="Phương_thức">Phương thức</h2> + +<dl> + <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> + <dd>Phương thức này được sử dụng khi ta cần đợi một tập các Promise kết thúc. Trả ra một promise đại diện cho tất cả các kết quả thu được từ các promise nằm trong iterable sau khi tất cả các promise này kết thúc xử lý thành công. Hoặc, trả ra một promise đại diện cho lỗi thực thi ngay khi một promise nào đó kết thúc lỗi, khi đó promise được trả ra cũng sẽ ở trạng thái lỗi. Khi tất cả các promise trong iterable kết thúc thành công thì promise trả ra cũng ở trạng thái thành công với kết quả là một mảng chứa tất cả các kết quả của các promise đã thực thi theo đúng thứ tự trong iterable. Còn khi một promise nào đó xảy ra lỗi thì promise được trả ra cũng sẽ ở trạng thái lỗi và chứa mã lỗi của promise đầu tiên gây lỗi đó.</dd> + <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> + <dd>Trả ra một promise ngay sau khi một trong các promise trong iterable kết thúc xử lý. Tức là dù kết quả thu được là lỗi hay thành công thì ta cũng sẽ trả ngay ra một promise mới và promise mới này sẽ chứa kết quả của promise được kết thúc đầu tiên.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.reject", "Promise.reject(reason)")}}</dt> + <dd>Trả ra một promise trạng thái lỗi với mã lỗi mà hàm xử lý trả ra. Hàm này sẽ được gọi tới khi hàm xử lý của ta bị lỗi (thất bại).</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.resolve", "Promise.resolve(value)")}}</dt> + <dd>Trả ra một promise thành công với kết quả mà hàm xử lý trả ra. </dd> +</dl> + +<h2 id="Nguyên_mẫu_Promise">Nguyên mẫu <code>Promise</code></h2> + +<h3 id="Thuộc_tính_2">Thuộc tính</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p> + +<h3 id="Phương_thức_2">Phương thức</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tạo_một_Promise">Tạo một Promise</h3> + +<pre class="brush: html hidden"><button id="btn">Tạo một Promise!</button> +<div id="log"></div> +</pre> + +<p>Ví dụ nhỏ này sẽ mô tả cơ chế của một <code>Promise</code>. Hàm <code>testPromise()</code> sẽ được gọi tới mỗi khi ta click vào {{HTMLElement("button")}}. Ta sẽ sử dụng {{domxref("window.setTimeout()")}} để thiết lập giá trị kết thúc cho nó. Hàm xử lý này sẽ đếm (bắt đầu từ 1) sau mỗi khoảng thời gian ngẫu nhiên từ 1 tới 3 giây.</p> + +<p>Hàm hậu xử lý đính kèm ở đây chỉ đơn giản là một hàm log lại các giá trị được trả ra và được gán bằng cách sử dụng hàm {{jsxref("Promise.prototype.then()","p1.then()")}}.</p> + +<pre class="brush: js">'use strict'; +var promiseCount = 0; + +function testPromise() { + var thisPromiseCount = ++promiseCount; + + var log = document.getElementById('log'); + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Started (<small>Sync code started</small>)<br/>'); + + // Tạo một Promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s) + var p1 = new Promise( + // The resolver function is called with the ability to resolve or + // reject the promise + function(resolve, reject) { + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise started (<small>Async code started</small>)<br/>'); + // This is only an example to create asynchronism + window.setTimeout( + function() { + // We fulfill the promise ! + resolve(thisPromiseCount); + }, Math.random() * 2000 + 1000); + } + ); + + // We define what to do when the promise is resolved/fulfilled with the then() call, + // and the catch() method defines what to do if the promise is rejected. + p1.then( + // Log the fulfillment value + function(val) { + log.insertAdjacentHTML('beforeend', val + + ') Promise fulfilled (<small>Async code terminated</small>)<br/>'); + }) + .catch( + // Log the rejection reason + function(reason) { + console.log('Handle rejected promise ('+reason+') here.'); + }); + + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise made (<small>Sync code terminated</small>)<br/>'); +}</pre> + +<pre class="brush:js hidden">if ("Promise" in window) { + var btn = document.getElementById("btn"); + btn.addEventListener("click",testPromise); +} else { + log = document.getElementById('log'); + log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface."; +} +</pre> + +<p>Ví dụ này được thực thi mỗi khi ta click vào button và để chạy được ví dụ này, bạn cần một trình duyệt có hỗ trợ <code>Promise</code>. Bạn hãy thử click vào button một vài lần liên tiếp trong một khoảng thời gian ngắn để thấy được các promise được xử lý thành chuỗi và sau khi kết thúc xử lý sẽ ở trạng thái thế nào nhé.</p> + +<p>{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}</p> + +<h2 id="Ví_dụ_với_XMLHttpRequest">Ví dụ với XMLHttpRequest</h2> + +<h3 id="Tạo_một_Promise_2">Tạo một Promise</h3> + +<p>Ví dụ này sẽ trình bày một cách sử dụng <code>Promise</code> để lấy kết quả (thành công hoặc lỗi) trả về từ {{domxref("XMLHttpRequest")}}.</p> + +<pre class="brush: js">'use strict'; + +// A-> $http function is implemented in order to follow the standard Adapter pattern +function $http(url){ + + // A small example of object + var core = { + + // Method that performs the ajax request + ajax: function (method, url, args) { + + // Creating a promise + var promise = new Promise( function (resolve, reject) { + + // Instantiates the XMLHttpRequest + var client = new XMLHttpRequest(); + var uri = url; + + if (args && (method === 'POST' || method === 'PUT')) { + uri += '?'; + var argcount = 0; + for (var key in args) { + if (args.hasOwnProperty(key)) { + if (argcount++) { + uri += '&'; + } + uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]); + } + } + } + + client.open(method, uri); + client.send(); + + client.onload = function () { + if (this.status >= 200 && this.status < 300) { + // Performs the function "resolve" when this.status is equal to 2xx + resolve(this.response); + } else { + // Performs the function "reject" when this.status is different than 2xx + reject(this.statusText); + } + }; + client.onerror = function () { + reject(this.statusText); + }; + }); + + // Return the promise + return promise; + } + }; + + // Adapter pattern + return { + 'get': function(args) { + return core.ajax('GET', url, args); + }, + 'post': function(args) { + return core.ajax('POST', url, args); + }, + 'put': function(args) { + return core.ajax('PUT', url, args); + }, + 'delete': function(args) { + return core.ajax('DELETE', url, args); + } + }; +}; +// End A + +// B-> Here you define its functions and its payload +var mdnAPI = 'https://developer.mozilla.org/en-US/search.json'; +var payload = { + 'topic' : 'js', + 'q' : 'Promise' +}; + +var callback = { + success: function(data) { + console.log(1, 'success', JSON.parse(data)); + }, + error: function(data) { + console.log(2, 'error', JSON.parse(data)); + } +}; +// End B + +// Executes the method call +$http(mdnAPI) + .get(payload) + .then(callback.success) + .catch(callback.error); + +// Executes the method call but an alternative way (1) to handle Promise Reject case +$http(mdnAPI) + .get(payload) + .then(callback.success, callback.error); + +// Executes the method call but an alternative way (2) to handle Promise Reject case +$http(mdnAPI) + .get(payload) + .then(callback.success) + .then(undefined, callback.error); +</pre> + +<h3 id="Tải_một_ảnh_với_XHR">Tải một ảnh với XHR</h3> + +<p>Một ví dụ đơn giản khác được sử dụng <code>Promise</code> và <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> để tải về một ảnh là MDN GitHub -<a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a>. Ngoài ra, bạn có thể xem nó <a href="http://mdn.github.io/promises-test/">hoạt động ra sao tại đây</a>. Mỗi bước đều được chú thích đầy đủ để giúp bạn hình dung được việc sử dụng Promise với XHR dễ dàng hơn.</p> + +<h2 id="Mô_tả_2">Mô tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Mô tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> + +<p>{{Compat}}</p> + +<h2 id="Tham_khảo_thêm">Tham khảo thêm</h2> + +<ul> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> + <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li> + <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li> + <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li> + <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li> + <li><a href="http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li> + <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> + <li><a href="https://www.udacity.com/course/javascript-promises--ud898">Udacity: JavaScript Promises</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/promise/prototype/index.html b/files/vi/web/javascript/reference/global_objects/promise/prototype/index.html new file mode 100644 index 0000000000..468622d9d6 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/promise/prototype/index.html @@ -0,0 +1,64 @@ +--- +title: Promise.prototype +slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p>Thuộc tính <code><strong>Promise</strong></code><strong><code>.prototype</code></strong> biểu diễn nguyên mẫu (prototype) cho hàm khởi tạo của {{jsxref("Promise")}}.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Mỗi đối tượng {{jsxref("Promise")}} được kế thừa từ {{jsxref("Promise.prototype")}}. Ta có thể sử dụng nguyên mẫu của hàm khởi tạo để thêm vào các thuộc tính hoặc phương thức mới cho đối tượng <code>Promise</code>.</p> + +<h2 id="Thuộc_tính">Thuộc tính</h2> + +<dl> + <dt><code>Promise.prototype.constructor</code></dt> + <dd>Trả ra hàm khởi tạo một nguyên mẫu đối tượng. Mặc định là hàm {{jsxref("Promise")}}.</dd> +</dl> + +<h2 id="Phương_thức">Phương thức</h2> + +<dl> + <dt>{{jsxref("Promise.catch", "Promise.prototype.catch(onRejected)")}}</dt> + <dd>Thêm một hàm phản hồi lỗi cho promise và trả ra một promise mới chứa kết quả được truyền vào hàm phản hồi đó sau khi thao tác xử lý của promise kết thúc.</dd> + <dt>{{jsxref("Promise.then", "Promise.prototype.then(onFulfilled, onRejected)")}}</dt> + <dd>Thêm một hàm phản hồi (có thể là thành công hoặc thất bại) và trả ra một promise mới chứa kết quả là kết quả thực thi của promise sau khi tác vụ kết thúc. Trong đó onFulfilled sẽ có đầu vòa là kết quả xử lý thành công, còn onRejected có đầu vòa là kết quả xử lý thất bại.</dd> +</dl> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype', 'Promise.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> + +<p>{{Compat}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html b/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html new file mode 100644 index 0000000000..9fdf5c193e --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html @@ -0,0 +1,194 @@ +--- +title: RegExp.prototype.exec() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec +tags: + - Biểu thức chính quy + - Phương Thức + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>exec()</code></strong> tiến hành tìm kiếm một so khớp trong một chuỗi xác định. Trả về một mảng kết quả hoặc {{jsxref("null")}}.</p> + +<p>Nếu bạn đơn giản chỉ muốn xác định có khớp hay không, tức kết quả trả về là true hoặc false, bạn nên sử dụng phương thức {{jsxref("RegExp.prototype.test()")}} hoặc phương thức {{jsxref("String.prototype.search()")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>regexObj</var>.exec(<var>str</var>)</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>str</code></dt> + <dd>Chuỗi dùng để so khớp với biểu thức chính quy.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Nếu so khớp thành công, phương thức <code>exec()</code> trả về một mảng và cập nhật các thuộc tính của đối tượng biểu thức chính quy. Mảng trả về item đầu tiên là đoạn text khớp, và các item tiếp theo là giá trị trong các dấu ngoặc tròn có nhớ đã khớp.</p> + +<p>Nếu việc so khớp thất bại, <code>exec()</code> trả về {{jsxref("null")}}.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Hãy xem xét ví dụ sau:</p> + +<pre class="brush: js">// So khớp "quick brown" theo sau bởi "jumps", bỏ qua các kí tự ở giữa +// Nhớ "brown" và "jumps" +// Không phân biệt chữ hoa/thường +var re = /quick\s(brown).+?(jumps)/ig; +var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog'); +</pre> + +<p>Bảng dưới đây là kết quả trả về của so khớp trên.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Đối tượng</td> + <td class="header">Thuộc tính/Chỉ mục</td> + <td class="header">Mô tả</td> + <td class="header">Ví dụ</td> + </tr> + <tr> + <td rowspan="4"><code>result</code></td> + <td><code>[0]</code></td> + <td>Chuỗi đầy đủ của các kí tự đã khớp.</td> + <td><code>Quick Brown Fox Jumps</code></td> + </tr> + <tr> + <td><code>[1], ...[<em>n</em> ]</code></td> + <td> + <p>Các chuỗi con khớp được đặt trong ngoặc, nếu có. Số lượng ngoặc không giới hạn.</p> + </td> + <td><code>[1] = Brown<br> + [2] = Jumps</code></td> + </tr> + <tr> + <td><code>index</code></td> + <td> + <p>Chỉ mục (tính từ 0) của bản khớp trong chuỗi.</p> + </td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>input</code></td> + <td>Chuỗi ban đầu.</td> + <td><code>The Quick Brown Fox Jumps Over The Lazy Dog</code></td> + </tr> + <tr> + <td rowspan="5"><code>re</code></td> + <td><code>lastIndex</code></td> + <td> + <p>Chỉ mục bắt đầu tìm so khớp tiếp theo. Khi không có cờ "g" thì chỉ mục sẽ trở về 0.</p> + </td> + <td><code>25</code></td> + </tr> + <tr> + <td><code>ignoreCase</code></td> + <td>Xác định xem liệu cờ "i" (không phân biệt chữ hoa/thường) được sử dụng hay không.</td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>global</code></td> + <td>Xác định liệu cờ "g" (so khớp toàn cục) có được sử dụng hay không.</td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>multiline</code></td> + <td>Xác định xem cờ "m" (tìm kiếm chuỗi đa dòng) có được sử dụng hay không.</td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>source</code></td> + <td>mẫu dùng để so khớp.</td> + <td><code>quick\s(brown).+?(jumps)</code></td> + </tr> + </tbody> +</table> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Tìm_các_so_khớp_tiếp_theo">Tìm các so khớp tiếp theo</h3> + +<p>Nếu biểu thức chính quy của bạn sử dụng cờ g, bạn có thể dùng phương thức exec() nhiều lần để tìm các so khớp tiếp theo trong chuỗi giống vậy. Lúc đó, việc tìm kếu bắt đầu từ chuỗi con của str đã được chỉ định bởi thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} của biểu thức chính quy. ({{jsxref("RegExp.prototype.test()", "test()")}} cũng sẽ tăng tới thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} property. Ví dụ, giả sử bạn có kịch bản:</p> + +<pre class="brush: js">var myRe = /ab*/g; +var str = 'abbcdefabh'; +var myArray; +while ((myArray = myRe.exec(str)) !== null) { + var msg = 'Found ' + myArray[0] + '. '; + msg += 'Next match starts at ' + myRe.lastIndex; + console.log(msg); +} +</pre> + +<p>Kịch bản này hiển thị văn bản sau:</p> + +<pre>Found abb. Next match starts at 3 +Found ab. Next match starts at 9 +</pre> + +<p>Chú ý: Đừng đặt biểu thức chính quy thuần (hoặc cấu trúc {{jsxref("RegExp")}}) bên trong điều kiện while hoặc nó sẽ tạo ra một vòng lặp vĩnh cửu nếu có một so khớp vì thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} sẽ reset lại sau mỗi vòng lặp. Và hãy chắc rằng cờ toàn cùng được xét nếu không một vòng lặp sẽ xảy ra.</p> + +<h3 id="Sử_dụng_exec()_với_RegExp_thuần">Sử dụng <code>exec()</code> với <code>RegExp</code> thuần</h3> + +<p>Bạn có thể sử dụng exec() mà không cần tạo đối tượng {{jsxref("RegExp")}}:</p> + +<pre class="brush: js">var matches = /(hello \S+)/.exec('This is a hello world!'); +console.log(matches[1]); +</pre> + +<p>Kịch bản này sẽ ghi ra lời nhắn chứa 'hello world!'.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.10.6.21', 'RegExp.exec')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-regexp.prototype.exec', 'RegExp.exec')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.exec")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></li> + <li>{{jsxref("RegExp")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/regexp/index.html b/files/vi/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..01f9b60832 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,618 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Reference + - RegExp + - Regular Expressions + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>RegExp</code></strong> constructor creates a regular expression object for matching text with a pattern.</p> + +<p>For an introduction to regular expressions, read the <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions chapter</a> in the <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript Guide</a>.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<p>Literal, constructor, and factory notations are possible:</p> + +<pre class="syntaxbox">/<var>pattern</var>/<var>flags</var> +new RegExp(<var>pattern</var>[, <var>flags</var>]) +RegExp(<var>pattern</var>[, <var>flags</var>]) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>pattern</code></dt> + <dd>The text of the regular expression.</dd> + <dt><code>flags</code></dt> + <dd> + <p>If specified, flags can have any combination of the following values:</p> + + <dl> + <dt><code>g</code></dt> + <dd>global match; find all matches rather than stopping after the first match</dd> + <dt><code>i</code></dt> + <dd>ignore case; if <code>u</code> flag is also enabled, use Unicode case folding</dd> + <dt><code>m</code></dt> + <dd>multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of <em>each</em> line (delimited by \n or \r), not only the very beginning or end of the whole input string)</dd> + <dt><code>u</code></dt> + <dd>Unicode; treat pattern as a sequence of Unicode code points</dd> + <dt><code>y</code></dt> + <dd>sticky; matches only from the index indicated by the <code>lastIndex</code> property of this regular expression in the target string (and does not attempt to match from any later indexes).</dd> + </dl> + </dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>There are 2 ways to create a <code>RegExp</code> object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:</p> + +<pre class="brush: js">/ab+c/i; +new RegExp('ab+c', 'i'); +new RegExp(/ab+c/, 'i'); +</pre> + +<p>The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.</p> + +<p>The constructor of the regular expression object, for example, <code>new RegExp('ab+c')</code>, provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.</p> + +<p>Starting with ECMAScript 6, <code>new RegExp(/ab+c/, 'i')</code> no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a <code>RegExp</code> and the second <code>flags</code> argument is present. A new <code>RegExp</code> from the arguments is created instead.</p> + +<p>When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:</p> + +<pre class="brush: js">var re = /\w+/; +var re = new RegExp('\\w+'); +</pre> + +<h2 id="Special_characters_meaning_in_regular_expressions">Special characters meaning in regular expressions</h2> + +<ul> + <li><a href="#character-classes">Character Classes</a></li> + <li><a href="#character-sets">Character Sets</a></li> + <li><a href="#boundaries">Boundaries</a></li> + <li><a href="#alternation">Alternation</a></li> + <li><a href="#grouping-back-references">Grouping and back references</a></li> + <li><a href="#quantifiers">Quantifiers</a></li> + <li><a href="#assertions">Assertions</a></li> +</ul> + +<table class="fullwidth-table"> + <tbody> + <tr id="character-classes"> + <th colspan="2">Character Classes</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code>.</code></td> + <td> + <p>(The dot, the decimal point) matches any single character <em>except</em> line terminators: <code>\n</code>, <code>\r</code>, <code>\u2028</code> or <code>\u2029</code>.</p> + + <p>Inside a character set, the dot loses its special meaning and matches a literal dot.</p> + + <p>Note that the <code>m</code> multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character set <code>[^]</code> can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.</p> + + <p>For example, <code>/.y/</code> matches "my" and "ay", but not "yes", in "yes make my day".</p> + </td> + </tr> + <tr> + <td><code>\d</code></td> + <td> + <p>Matches any digit (Arabic numeral). Equivalent to <code>[0-9]</code>.</p> + + <p>For example, <code>/\d/</code> or <code>/[0-9]/</code> matches "2" in "B2 is the suite number".</p> + </td> + </tr> + <tr> + <td><code>\D</code></td> + <td> + <p>Matches any character that is not a digit (Arabic numeral). Equivalent to <code>[^0-9]</code>.</p> + + <p>For example, <code>/\D/</code> or <code>/[^0-9]/</code> matches "B" in "B2 is the suite number".</p> + </td> + </tr> + <tr> + <td><code>\w</code></td> + <td> + <p>Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to <code>[A-Za-z0-9_]</code>.</p> + + <p>For example, <code>/\w/</code> matches "a" in "apple", "5" in "$5.28", and "3" in "3D".</p> + </td> + </tr> + <tr> + <td><code>\W</code></td> + <td> + <p>Matches any character that is not a word character from the basic Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>.</p> + + <p>For example, <code>/\W/</code> or <code>/[^A-Za-z0-9_]/</code> matches "%" in "50%".</p> + </td> + </tr> + <tr> + <td><code>\s</code></td> + <td> + <p>Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to <code>[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>.</p> + + <p>For example, <code>/\s\w*/</code> matches " bar" in "foo bar".</p> + </td> + </tr> + <tr> + <td><code>\S</code></td> + <td> + <p>Matches a single character other than white space. Equivalent to <code>[^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>.</p> + + <p>For example, <code>/\S\w*/</code> matches "foo" in "foo bar".</p> + </td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Matches a horizontal tab.</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Matches a carriage return.</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>Matches a linefeed.</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Matches a vertical tab.</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Matches a form-feed.</td> + </tr> + <tr> + <td><code>[\b]</code></td> + <td>Matches a backspace. (Not to be confused with <code>\b</code>)</td> + </tr> + <tr> + <td><code>\0</code></td> + <td>Matches a NUL character. Do not follow this with another digit.</td> + </tr> + <tr> + <td><code>\c<em>X</em></code></td> + <td> + <p>Where <code><em>X</em></code> is a letter from A - Z. Matches a control character in a string.</p> + + <p>For example, <code>/\cM/</code> matches control-M in a string.</p> + </td> + </tr> + <tr> + <td><code>\x<em>hh</em></code></td> + <td>Matches the character with the code <code><em>hh</em></code> (two hexadecimal digits).</td> + </tr> + <tr> + <td><code>\u<em>hhhh</em></code></td> + <td>Matches a UTF-16 code-unit with the value <code><em>hhhh</em></code> (four hexadecimal digits).</td> + </tr> + <tr> + <td><code>\u<em>{hhhh} </em>or <em>\u{hhhhh}</em></code></td> + <td>(only when u flag is set) Matches the character with the Unicode value U+<code><em>hhhh</em> or </code>U+<code><em>hhhhh</em></code> (hexadecimal digits).</td> + </tr> + <tr> + <td><code>\</code></td> + <td> + <p>For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.</p> + + <p>For example, <code>/b/</code> matches the character "b". By placing a backslash in front of "b", that is by using <code>/\b/</code>, the character becomes special to mean match a word boundary.</p> + + <p><em>or</em></p> + + <p>For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.</p> + + <p>For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, <code>/a*/</code> means match 0 or more "a"s. To match <code>*</code> literally, precede it with a backslash; for example, <code>/a\*/</code> matches "a*".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="character-sets"> + <th colspan="2">Character Sets</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code>[xyz]<br> + [a-c]</code></td> + <td> + <p>A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. It is also possible to include a character class in a character set.</p> + + <p>For example, <code>[abcd]</code> is the same as <code>[a-d]</code>. They match the "b" in "brisket" and the "c" in "chop".</p> + + <p>For example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop" and the "-" (hyphen) in "non-profit".</p> + + <p>For example, [\w-] is the same as [A-Za-z0-9_-]. They match the "b" in "brisket", the "c" in "chop" and the "n" in "non-profit".</p> + </td> + </tr> + <tr> + <td> + <p><code>[^xyz]<br> + [^a-c]</code></p> + </td> + <td> + <p>A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.</p> + + <p>For example, <code>[^abc]</code> is the same as <code>[^a-c]</code>. They initially match "o" in "bacon" and "h" in "chop".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="alternation"> + <th colspan="2">Alternation</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code><em>x</em>|<em>y</em></code></td> + <td> + <p>Matches either <code><em>x</em></code> or <code><em>y</em></code>.</p> + + <p>For example, <code>/green|red/</code> matches "green" in "green apple" and "red" in "red apple".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="boundaries"> + <th colspan="2">Boundaries</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code>^</code></td> + <td> + <p>Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.</p> + + <p>For example, <code>/^A/</code> does not match the "A" in "an A", but does match the first "A" in "An A".</p> + </td> + </tr> + <tr> + <td><code>$</code></td> + <td> + <p>Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.</p> + + <p>For example, <code>/t$/</code> does not match the "t" in "eater", but does match it in "eat".</p> + </td> + </tr> + <tr> + <td><code>\b</code></td> + <td> + <p>Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.</p> + + <p>Examples:<br> + <code>/\bm/</code> matches the 'm' in "moon" ;<br> + <code>/oo\b/</code> does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character;<br> + <code>/oon\b/</code> matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character;<br> + <code>/\w\b\w/</code> will never match anything, because a word character can never be followed by both a non-word and a word character.</p> + </td> + </tr> + <tr> + <td><code>\B</code></td> + <td> + <p>Matches a non-word boundary. This is a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. Such as between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word bondary is also not included in the match.</p> + + <p>For example, <code>/\Bon/</code> matches "on" in "at noon", and <code>/ye\B/</code> matches "ye" in "possibly yesterday".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="grouping-back-references"> + <th colspan="2">Grouping and back references</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code>(<em>x</em>)</code></td> + <td> + <p>Matches <code><em>x</em></code> and remembers the match. These are called capturing groups.</p> + + <p>For example, <code>/(foo)/</code> matches and remembers "foo" in "foo bar". </p> + + <p>The capturing groups are numbered according to the order of left parentheses of capturing groups, starting from 1. The matched substring can be recalled from the resulting array's elements <code>[1], ..., [n]</code> or from the predefined <code>RegExp</code> object's properties <code>$1, ..., $9</code>.</p> + + <p>Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).</p> + </td> + </tr> + <tr> + <td><code>\<em>n</em></code></td> + <td> + <p>Where <code><em>n</em></code> is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).</p> + + <p>For example, <code>/apple(,)\sorange\1/</code> matches "apple, orange," in "apple, orange, cherry, peach". A complete example follows this table.</p> + </td> + </tr> + <tr> + <td><code>(?:<em>x</em>)</code></td> + <td>Matches <code><em>x</em></code> but does not remember the match. These are called non-capturing groups. The matched substring cannot be recalled from the resulting array's elements <code>[1], ..., [n]</code> or from the predefined <code>RegExp</code> object's properties <code>$1, ..., $9</code>.</td> + </tr> + </tbody> + <tbody> + <tr id="quantifiers"> + <th colspan="2">Quantifiers</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code><em>x</em>*</code></td> + <td> + <p>Matches the preceding item <em>x</em> 0 or more times.</p> + + <p>For example, <code>/bo*/</code> matches "boooo" in "A ghost booooed" and "b" in "A bird warbled", but nothing in "A goat grunted".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>+</code></td> + <td> + <p>Matches the preceding item <em>x</em> 1 or more times. Equivalent to <code>{1,}</code>.</p> + + <p>For example, <code>/a+/</code> matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>?</code></td> + <td> + <p>Matches the preceding item <em>x</em> 0 or 1 time.</p> + + <p>For example, <code>/e?le?/</code> matches the "el" in "angel" and the "le" in "angle."</p> + + <p>If used immediately after any of the quantifiers <code>*</code>, <code>+</code>, <code>?</code>, or <code>{}</code>, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).</p> + </td> + </tr> + <tr> + <td><code><em>x</em>{<em>n</em>}</code></td> + <td> + <p>Where <code><em>n</em></code> is a positive integer. Matches exactly <code><em>n</em></code> occurrences of the preceding item <em>x</em>.</p> + + <p>For example, <code>/a{2}/</code> doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>{<em>n</em>,}</code></td> + <td> + <p>Where <code><em>n</em></code> is a positive integer. Matches at least <code><em>n</em></code> occurrences of the preceding item <em>x</em>.</p> + + <p>For example, <code>/a{2,}/</code> doesn't match the "a" in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>{<em>n</em>,<em>m</em>}</code></td> + <td> + <p>Where <code><em>n</em></code> is 0 or a positive integer, and <code><em>m</em></code> is a positive integer. Matches at least <code><em>n</em></code> and at most <code><em>m</em></code> occurrences of the preceding item <em>x</em>.</p> + + <p>For example, <code>/a{1,3}/</code> matches nothing in "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more "a"'s in it.</p> + </td> + </tr> + <tr> + <td> + <p><code><em>x</em>*?</code><br> + <code><em>x</em>+?</code><br> + <code><em>x</em>??</code><br> + <code><em>x</em>{n}?</code><br> + <code><em>x</em>{n,}?</code><br> + <code><em>x</em>{n,m}?</code></p> + </td> + <td> + <p>Matches the preceding item <em>x</em> like <code>*</code>, <code>+</code>, <code>?</code>, and <code>{...}</code> from above, however the match is the smallest possible match.</p> + + <p>For example, <code>/<.*?>/</code> matches "<foo>" in "<foo> <bar>", whereas <code>/<.*>/</code> matches "<foo> <bar>".</p> + + <p>Quantifiers without <code>?</code> are said to be greedy. Those with <code>?</code> are called "non-greedy".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="assertions"> + <th colspan="2">Assertions</th> + </tr> + <tr> + <th>Character</th> + <th>Meaning</th> + </tr> + <tr> + <td><code><em>x</em>(?=<em>y</em>)</code></td> + <td> + <p>Matches <code><em>x</em></code> only if <code><em>x</em></code> is followed by <code><em>y</em></code>.</p> + + <p>For example, /<code>Jack(?=Sprat)/</code> matches "Jack" only if it is followed by "Sprat".<br> + <code>/Jack(?=Sprat|Frost)/</code> matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.</p> + </td> + </tr> + <tr> + <td><code><em>x</em>(?!<em>y</em>)</code></td> + <td> + <p>Matches <code><em>x</em></code> only if <code><em>x</em></code> is not followed by <code><em>y</em></code>.</p> + + <p>For example, <code>/\d+(?!\.)/</code> matches a number only if it is not followed by a decimal point.<br> + <code>/\d+(?!\.)/.exec('3.141')</code> matches "141" but not "3.141".</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("RegExp.prototype")}}</dt> + <dd>Allows the addition of properties to all objects.</dd> + <dt><code>RegExp.length</code></dt> + <dd>The value of <code>RegExp.length</code> is 2.</dd> + <dt>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("RegExp.lastIndex")}}</dt> + <dd>The index at which to start the next match.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p>The global <code>RegExp</code> object has no methods of its own, however, it does inherit some methods through the prototype chain.</p> + +<h2 id="RegExp_prototype_objects_and_instances"><code>RegExp</code> prototype objects and instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Methods')}}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_a_regular_expression_to_change_data_format">Using a regular expression to change data format</h3> + +<p>The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format <em>first last</em> and output it in the format <em>last, first</em>. In the replacement text, the script uses <code>$1</code> and <code>$2</code> to indicate the results of the corresponding matching parentheses in the regular expression pattern.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = 'John Smith'; +var newstr = str.replace(re, '$2, $1'); +console.log(newstr); +</pre> + +<p>This displays "Smith, John".</p> + +<h3 id="Using_regular_expression_to_split_lines_with_different_line_endingsends_of_lineline_breaks">Using regular expression to split lines with different <strong>line endings/ends of line/line breaks</strong></h3> + +<p>The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.</p> + +<pre class="brush: js">var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'; +var lines = text.split(/\r\n|\r|\n/); +console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ] +</pre> + +<p>Note that the order of the patterns in the regular expression matters.</p> + +<h3 id="Using_regular_expression_on_multiple_lines">Using regular expression on multiple lines</h3> + +<pre class="brush: js">var s = 'Please yes\nmake my day!'; +s.match(/yes.*day/); +// Returns null +s.match(/yes[^]*day/); +// Returns ["yes\nmake my day"] +</pre> + +<h3 id="Using_a_regular_expression_with_the_sticky_flag">Using a regular expression with the sticky flag</h3> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky">sticky flag</a> indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.</p> + +<pre class="brush: js">var str = '#foo#'; +var regex = /foo/y; + +regex.lastIndex = 1; +regex.test(str); // true +regex.lastIndex = 5; +regex.test(str); // false (lastIndex is taken into account with sticky flag) +regex.lastIndex; // 0 (reset after match failure)</pre> + +<h3 id="Regular_expression_and_Unicode_characters">Regular expression and Unicode characters</h3> + +<p>As mentioned above, <code>\w</code> or <code>\W</code> only matches ASCII based characters; for example, "a" to "z", "A" to "Z", "0" to "9" and "_". To match characters from other languages such as Cyrillic or Hebrew, use <code>\uhhhh</code>, where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.</p> + +<pre class="brush: js">var text = 'Образец text на русском языке'; +var regex = /[\u0400-\u04FF]+/g; + +var match = regex.exec(text); +console.log(match[0]); // logs 'Образец' +console.log(regex.lastIndex); // logs '7' + +var match2 = regex.exec(text); +console.log(match2[0]); // logs 'на' [did not log 'text'] +console.log(regex.lastIndex); // logs '15' + +// and so on +</pre> + +<p>Here's an external resource for getting the complete Unicode block range for different scripts: <a href="http://kourge.net/projects/regexp-unicode-block">Regexp-Unicode-block</a>.</p> + +<h3 id="Extracting_sub-domain_name_from_URL">Extracting sub-domain name from URL</h3> + +<pre class="brush: js">var url = 'http://xxx.domain.com'; +console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx' +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>The <code>RegExp</code> constructor no longer throws when the first argument is a <code>RegExp</code> and the second argument is present. Introduces Unicode and sticky flags.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp")}}</p> +</div> + +<h3 id="Firefox-specific_notes">Firefox-specific notes</h3> + +<p>Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now <code>undefined</code> instead of an empty string:</p> + +<pre class="brush: js">// Firefox 33 or older +'x'.replace(/x(.)?/g, function(m, group) { + console.log("'group:" + group + "'"); +}); // 'group:' + +// Firefox 34 or newer +'x'.replace(/x(.)?/g, function(m, group) { + console.log("'group:" + group + "'"); +}); // 'group:undefined' +</pre> + +<p>Note that due to web compatibility, <code>RegExp.$N</code> will still return an empty string instead of <code>undefined</code> ({{bug(1053944)}}).</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/index.html b/files/vi/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..03fe825c98 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,405 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRe +<h2 id="lnyannini">lnyannini</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate">Nội dung HTML mẫu</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css notranslate">Nội dung CSS mẫu</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">Nội dung JavaScript mẫu</pre> + +<h3 id="Kết_quả">Kết quả</h3> + +<p>{{EmbedLiveSample('lnyannini')}}</p> +f}}</div> + +<p><sup><sub>Copy dtoc: june-12-2017</sub></sup><br> + The <strong><code>String</code></strong> global object is a constructor for strings, or a sequence of characters.<br> + <sup><sub>Đối tượng Chuỗi toàn cục là một constructor cho chuỗi, hoặc chuỗi ký tự.</sub></sup></p> + +<h2 id="Syntax">Syntax</h2> + +<p>String literals take the forms:</p> + +<pre class="syntaxbox notranslate">'string text' +"string text" +"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> + +<p>Strings can also be created using the <code>String</code> global object directly:</p> + +<pre class="syntaxbox notranslate">String(thing)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>Anything to be converted to a string.</dd> +</dl> + +<h3 id="Template_literals">Template literals</h3> + +<p>Starting with ECMAScript 2015, string literals can also be so-called <a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a>:<br> + <sup><sub>Trong ES6 Chuỗi cũng được gọi là Template Strings.</sub></sup></p> + +<pre class="syntaxbox notranslate">`hello world` +`hello! + world!` +`hello ${who}` +escape `<a>${who}</a>`</pre> + +<dl> +</dl> + +<h3 id="Escape_notation">Escape notation</h3> + +<p>Beside regular, printable characters, special characters can be encoded using escape notation:<br> + <sup><sub>Ngoài ký tự thường, các ký tự đặc biệt có thể được code ra bằng cách dùng các ký hiệu loại trừ:</sub></sup></p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Code</th> + <th scope="col">Output</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>the NULL character</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>backslash</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>new line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>carriage return</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>vertical tab</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>tab</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>form feed</td> + </tr> + <tr> + <td><code>\uXXXX</code></td> + <td>unicode codepoint</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>unicode codepoint {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>the Latin-1 character</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.</p> +</div> + +<dl> +</dl> + +<h3 id="Long_literal_strings">Long literal strings</h3> + +<p>Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.</p> + +<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> + +<pre class="brush: js notranslate">let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; +</pre> + +<p>Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:</p> + +<pre class="brush: js notranslate">let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable."; +</pre> + +<p>Both of these result in identical strings being created.</p> + +<h2 id="Description">Description</h2> + +<p>Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.</p> + +<h3 id="Character_access">Character access</h3> + +<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> + +<pre class="brush: js notranslate">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:</p> + +<pre class="brush: js notranslate">return 'cat'[1]; // returns "a" +</pre> + +<p>For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)</p> + +<h3 id="Comparing_strings">Comparing strings</h3> + +<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p> + +<pre class="brush: js notranslate">var a = 'a'; +var b = 'b'; +if (a < b) { // true + console.log(a + ' is less than ' + b); +} else if (a > b) { + console.log(a + ' is greater than ' + b); +} else { + console.log(a + ' and ' + b + ' are equal.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<h3 id="Distinction_between_string_primitives_and_String_objects">Distinction between string primitives and <code>String</code> objects</h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</p> + +<pre class="brush: js notranslate">var s_prim = 'foo'; +var s_obj = new String(s_prim); + +console.log(typeof s_prim); // Logs "string" +console.log(typeof s_obj); // Logs "object" +</pre> + +<p>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p> + +<pre class="brush: js notranslate">var s1 = '2 + 2'; // creates a string primitive +var s2 = new String('2 + 2'); // creates a String object +console.log(eval(s1)); // returns the number 4 +console.log(eval(s2)); // returns the string "2 + 2" +</pre> + +<p>For these reasons, code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally authors need not worry about the distinction.</p> + +<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> + +<pre class="brush: js notranslate">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>Note:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>Allows the addition of properties to a <code>String</code> object.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>Returns a string created by using the specified sequence of Unicode values.</dd> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>Returns a string created by using the specified sequence of code points.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>Returns a string created from a raw template string.</dd> +</dl> + +<h2 id="String_generic_methods"><code>String</code> generic methods</h2> + +<div class="warning"> +<p><strong>String generics are non-standard, deprecated and will get removed near future</strong>.</p> +</div> + +<p>The <code>String</code> instance methods are also available in Firefox as of JavaScript 1.6 (<strong>not</strong> part of the ECMAScript standard) on the <code>String</code> object for applying <code>String</code> methods to any object:</p> + +<pre class="brush: js notranslate">var num = 15; +console.log(String.replace(num, /5/, '2')); +</pre> + +<p>For migrating away from String generics, see also <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_string_generics">Warning: String.x is deprecated; use String.prototype.x instead</a>.</p> + +<p>{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.</p> + +<h2 id="String_instances"><code>String</code> instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="String_conversion">String conversion</h3> + +<p>It's possible to use <code>String</code> as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying <code>toString()</code>. It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:</p> + +<pre class="brush: js notranslate">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>\u{XXXXXX}</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("40")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>\u{XXXXXX}</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("40")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/match/index.html b/files/vi/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..d40ffc4482 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,160 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +tags: + - Biểu thức chính quy + - Chuỗi + - Phương Thức +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +<div>{{JSRef}}</div> + +<div> </div> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Phương thức </span></font><strong>match()</strong></code> đưa ra những so khớp khi so khớp một <em>chuỗi (string) </em>với<em> biểu thức chính quy.</em></p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>str</var>.match(<var>regexp</var>)</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>Đối tượng biểu thức chính quy. Nếu một đối tượng <code>obj</code> không phải biểu thức chính quy được truyền vào, nó sẽ ngầm chuyển đổi thành một {{jsxref("RegExp")}} bằng cách sử dụng <code>new RegExp(obj)</code>. Nếu bạn không truyền tham số và sử dụng trực tiếp phương thức match(), bạn sẽ nhận lại một {{jsxref("Array")}} với một chuỗi rỗng: [""].</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Nếu một chuỗi khớp với biểu thức, nó sẽ trả lại một {{jsxref("Array")}} chứa chuỗi khớp hoàn toàn là phần tử đầu tiên, tiếp đó là các kết quả nằm trong dấu ngoặc đơn (ngoặc có nhớ). Nếu không có so khớp, nó sẽ trả về {{jsxref("null")}}.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Nếu một biểu thức chính quy không có cờ <code>g</code>, <code>str.match()</code> trả về kết quả giống như {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. {{jsxref("Array")}} trả về có thêm thuộc tính <code>input</code> chứa chuỗi ban đầu được phân tích ngữ pháp. Thêm nữa, nó có một thuộc tính <code>index</code> đại diện cho chỉ mục (tính từ 0) của so khớp trong chuỗi.</p> + +<p>Nếu biểu thức chính quy có cờ <code>g</code>, phương thức trả về một {{jsxref("Array")}} chứa tất cả chuỗi con khớp mà không phải các đối tượng khớp. Nó không trả về chuỗi trong dấu ngoặc tròn có nhớ. Nếu không có so khớp, phương thức trả về {{jsxref("null")}}.</p> + +<h3 id="Xem_thêm_Các_phương_thức_RegEx">Xem thêm: Các phương thức <code>RegEx</code></h3> + +<ul> + <li>Trường hợp bạn cần biết liệu một chuỗi có khớp với biểu thức chính quy {{jsxref("RegExp")}} hay không, sử dụng {{jsxref("RegExp.prototype.test()", "RegExp.test()")}}.</li> + <li>Nếu chỉ muốn xem so khớp đầu tiên được tìm thấy, bạn sử dụng {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}.</li> + <li>Nếu bạn muốn lấy nhóm trong ngoặc có nhớ và xét cờ, bạn cần sử dụng {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}.</li> +</ul> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_match()">Sử dụng <code>match()</code></h3> + +<p>Trong ví dụ dưới đây, <code>match()</code> được dùng để tìm chuỗi <code>'Chapter '</code> theo sau là một hoặc nhiều kí tự số, tiếp đó là <em>một dấu chấm <code>.</code> thập phân và một số </em>lặp lại 0 hoặc nhiều lần. Biểu thức chính quy có cờ <code>i</code> nên không phân biệt chữ hoa và thường.</p> + +<pre class="brush: js">var str = 'For more information, see Chapter 3.4.5.1'; +var re = /see (chapter \d+(\.\d)*)/i; +var found = str.match(re); + +console.log(found); + +// logs [ 'see Chapter 3.4.5.1', +// 'Chapter 3.4.5.1', +// '.1', +// index: 22, +// input: 'For more information, see Chapter 3.4.5.1' ] + +// 'see Chapter 3.4.5.1' là so khớp toàn bộ. +// 'Chapter 3.4.5.1' được bắt bởi '(chapter \d+(\.\d)*)'. +// '.1' là giá trị cuối cùng được bắt bởi '(\.\d)'. +// Thuộc tính 'index' (22) là chỉ mục tính từ 0 của so khớp toàn bộ. +// Thuộc tính 'input' là chuỗi gốc đã được phân tích ngữ pháp.</pre> + +<h3 id="Sử_dụng_cờ_toàn_cục_và_cờ_không_phân_biệt_chữ_hoathường_với_match()">Sử dụng cờ toàn cục và cờ không phân biệt chữ hoa/thường với <code>match()</code></h3> + +<p>Ví dụ dưới đây mô tả cách sử dụng cờ <code>g</code> và cờ <code>i </code>với <code>match()</code>. Tất cả chữ A tớ E và a tới e sẽ được trả lại và mỗi phần từ khớp nằm trong mảng.</p> + +<pre class="brush: js">var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; +var regexp = /[A-E]/gi; +var matches_array = str.match(regexp); + +console.log(matches_array); +// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e'] +</pre> + +<h3 id="Sử_dụng_match()_không_truyền_tham_số">Sử dụng <code>match()</code> không truyền tham số</h3> + +<pre class="brush: js">var str = "Nothing will come of nothing."; + +str.match(); //trả về [""]</pre> + +<h3 id="Một_đối_tượng_không_phải_biểu_thức_chính_quy_được_coi_như_một_tham_số">Một đối tượng không phải biểu thức chính quy được coi như một tham số</h3> + +<p>Khi tham số là một chuỗi hoặc một số, ngầm định, nó được chuyển đổi thành một {{jsxref("RegExp")}} sử dụng new RegExp(obj). Nếu nó là một số dương với một dấu dương, phương thức Regexp() sẽ bỏ qua dấu dương.</p> + +<pre class="brush: js">var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.", + str2 = "My grandfather is 65 years old and My grandmother is 63 years old.", + str3 = "The contract was declared null and void."; +str1.match("number"); // "number" là một chuỗi. Trả về ["number"] +str1.match(NaN); // kiểu của NaN là kiểu number. Trả về ["NaN"] +str1.match(Infinity); // kiểu của Infinity là number. Trả về ["Infinity"] +str1.match(+Infinity); // Trả về ["Infinity"] +str1.match(-Infinity); // Trả về ["-Infinity"] +str2.match(65); // Trả về ["65"] +str2.match(+65); // Một số với dấu dương. Trả về ["65"] +str3.match(null); // Trả về ["null"]</pre> + +<h2 id="Thông_số">Thông số</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Thông số</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> + <p>Định nghĩa ban đầu. Được bổ sung trong JavaScript 1.2.</p> + </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<p class="hidden">Bảng tương thích trong trang này được tạo ra từ dữ liệu cấu trúc. Nếu bạn muốn đóng góp vào dữ liệu, hãy kiểm tra <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gửi một yêu cầu pull tới chúng tôi.</p> + +<p>{{Compat("javascript.builtins.String.match")}}</p> + +<h2 id="Lưu_ý_cho_Firefox">Lưu ý cho Firefox</h2> + +<ul> + <li>các cờ <code>flags</code> từng không phải đối số thứ hai tiêu chuẩn, nó chỉ có hiệu lực trong Gecko: <var>str</var>.match(<var>regexp, flags</var>)</li> + <li>Bắt đầu từ Gecko 27 {{geckoRelease(27)}}, phương thức này đã được điều chỉnh để phù hợp với ECMAScript. Khi <code>match()</code> được gọi với một biểu thức chính quy toàn cục, thuộc tính {{jsxref("RegExp.lastIndex")}} (nếu nó được chỉ định) sẽ được đưa về <code>0</code> ({{bug(501739)}}).</li> + <li>Từ Gecko 39 {{geckoRelease(39)}}, đối số <code>flags</code> không chuẩn không được chấp nhận và sẽ có cảnh báo ({{bug(1142351)}}) trên giao diện điều khiển.</li> + <li> Từ Gecko 47 {{geckoRelease(47)}}, đối số <code>flags</code> không chuẩn không còn được hỗ trợ trong các phiên bản chưa phát hành và sẽ sớm bị gỡ bỏ {{bug(1245801)}}) hoàn toàn.</li> + <li>Từ Gecko 49 {{geckoRelease(49)}}, đối số <code>flags</code> không chuẩn còn còn được hỗ trợ ({{bug(1108382)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html b/files/vi/web/javascript/reference/global_objects/string/normalize/index.html new file mode 100644 index 0000000000..faf26687eb --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/normalize/index.html @@ -0,0 +1,146 @@ +--- +title: String.prototype.normalize() +slug: Web/JavaScript/Reference/Global_Objects/String/normalize +tags: + - Chuỗi + - ECMAScript 2015 + - JavaScript + - Phương Thức + - Prototype + - String + - Tham khảo + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>normalize()</code></strong> trả về chuỗi với các ký tự Unicode đã được bình thường hóa (nếu giá trị truyền vào không phải chuỗi, nó sẽ được chuyển thành chuỗi trước).</p> + +<div>{{EmbedInteractiveExample("pages/js/string-normalize.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>str</var>.normalize([<var>form</var>])</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>form</code></dt> + <dd>Là một trong các giá trị <code>"NFC"</code>, <code>"NFD"</code>, <code>"NFKC"</code>, hoặc <code>"NFKD"</code>, để chỉ định định dạng Unicode của chuỗi ký tự. Nếu bỏ qua hoặc mang giá trị {{jsxref("undefined")}}, <code>"NFC"</code> sẽ được sử dụng. + <ul> + <li><code>NFC</code> — Normalization Form Canonical Composition. (Unicode Dựng Sẵn)</li> + <li><code>NFD</code> — Normalization Form Canonical Decomposition. (Unicode Tổ Hợp)</li> + <li><code>NFKC</code> — Normalization Form Compatibility Composition. (Unicode Dựng Sẵn Tương Thích)</li> + <li><code>NFKD</code> — Normalization Form Compatibility Decomposition. (Unicode Tổ Hợp Tương Thích)</li> + </ul> + </dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chuỗi mới với các ký tự Unicode đã được bình thường hóa.</p> + +<h3 id="Lỗi_có_thể_gây_ra">Lỗi có thể gây ra</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>Phương thức sẽ gây ra lỗi {{jsxref("RangeError")}} nếu như giá trị tham số <code>form</code> không phải là một trong các giá trị liệt kê ở trên.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức <code>normalize()</code> sẽ trả về một chuỗi mới với các ký tự Unicode đã được bình thường hóa theo một trong các định dạng Unicode Normalization Form. Nó không làm thay đổi chuỗi ban đầu.</p> + +<div class="blockIndicator note"> +<p>Đối với tiếng Việt, việc bình thường hóa giữa hai định dạng Canonical hoặc Compatibility (cùng Tổ Hợp hoặc Dựng Sẵn) là như nhau.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_normalize()">Sử dụng <code>normalize()</code></h3> + +<pre class="brush: js">// Chuỗi ban đầu + +// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE +// U+0323: COMBINING DOT BELOW +var str = '\u1E9B\u0323'; + + +// Canonically-composed form (NFC) + +// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE +// U+0323: COMBINING DOT BELOW +str.normalize('NFC'); // '\u1E9B\u0323' +str.normalize(); // như trên + + +// Canonically-decomposed form (NFD) + +// U+017F: LATIN SMALL LETTER LONG S +// U+0323: COMBINING DOT BELOW +// U+0307: COMBINING DOT ABOVE +str.normalize('NFD'); // '\u017F\u0323\u0307' + + +// Compatibly-composed (NFKC) + +// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE +str.normalize('NFKC'); // '\u1E69' + + +// Compatibly-decomposed (NFKD) + +// U+0073: LATIN SMALL LETTER S +// U+0323: COMBINING DOT BELOW +// U+0307: COMBINING DOT ABOVE +str.normalize('NFKD'); // '\u0073\u0323\u0307' + +// So sánh chuỗi tiếng Việt: + +// Unicode Dựng Sẵn +var tvds = 'Tiếng Việt'; +// Unicode Tổ Hợp +var tvth = 'Tiếng Việt'; + +console.log(tvds.length); // 10 +console.log(tvth.length); // 14 +console.log(tvds == tvth); // false +console.log(tvds.normalize('NFC') == tvth.normalize('NFC')); // true +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa lần đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.normalize")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="http://www.unicode.org/reports/tr15/">Unicode Standard Annex #15, Unicode Normalization Forms</a></li> + <li><a href="http://en.wikipedia.org/wiki/Unicode_equivalence">Unicode equivalence</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html b/files/vi/web/javascript/reference/global_objects/string/repeat/index.html new file mode 100644 index 0000000000..72e2179cf1 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/repeat/index.html @@ -0,0 +1,118 @@ +--- +title: String.prototype.repeat() +slug: Web/JavaScript/Reference/Global_Objects/String/repeat +tags: + - Chuỗi + - ES6 + - Phương Thức + - Tham khảo +translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>repeat()</code></strong> xây dựng và trả về một chuỗi mới chứa số lượng nhất định bản sao chép của chuỗi được gọi tới và nối chung với nhau.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>str</var>.repeat(<var>count</var>);</code> +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>count</code></dt> + <dd>Là 0 hoặc số nguyên dương, tức là giá trị nằm trong khoảng: [0, +∞), xác định số lần lặp để tạo chuỗi mới.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chuỗi mới chứa số lần sao chép (count) chuỗi đầu vào.</p> + +<h3 id="Ngoại_lệ">Ngoại lệ</h3> + +<ul> + <li>{{jsxref("Errors/Negative_repetition_count", "RangeError")}}: số lần lặp phải không âm.</li> + <li>{{jsxref("Errors/Resulting_string_too_large", "RangeError")}}: số lần lặp phải nhỏ hơn vô cực và không vượt kích cỡ chuỗi tối đa.</li> +</ul> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">'abc'.repeat(-1); // RangeError +'abc'.repeat(0); // '' +'abc'.repeat(1); // 'abc' +'abc'.repeat(2); // 'abcabc' +'abc'.repeat(3.5); // 'abcabcabc' (tham số đếm sẽ được chuyển thành số nguyên) +'abc'.repeat(1/0); // RangeError + +({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); +// 'abcabc' (repeat() is a generic method) +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Phương thức này đã được thêm vào kỹ thuật ES6 và có thể chưa có sẵn trong tất cả các bản bổ sung JS. Tuy nhiên bạn có thể sử dụng polyfill <code>String.prototype.repeat()</code> với snippet dưới đây:</p> + +<pre class="brush: js">if (!String.prototype.repeat) { + String.prototype.repeat = function(count) { + 'use strict'; + if (this == null) { + throw new TypeError('can\'t convert ' + this + ' to object'); + } + var str = '' + this; + count = +count; + if (count != count) { + count = 0; + } + if (count < 0) { + throw new RangeError('repeat count must be non-negative'); + } + if (count == Infinity) { + throw new RangeError('repeat count must be less than infinity'); + } + count = Math.floor(count); + if (str.length == 0 || count == 0) { + return ''; + } + + // Đảm bảo tham số đếm là số nguyên 31 bít cho phép ta tối ưu hóa nhiều + // phần chính. Nhưng dù sao thì, hầu hết các trình duyệt hiện tại (tháng Tám năm 2014) không thể xử lý + // các chuỗi 1 << 28 chars hoặc lớn hơn, vậy nên: + if (str.length * count >= 1 << 28) { + throw new RangeError('repeat count must not overflow maximum string size'); + } + var rpt = ''; + for (var i = 0; i < count; i++) { + rpt += str; + } + return rpt; + } +} +</pre> + +<h2 id="Thông_số">Thông số</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa bổ sung.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.repeat")}}</p> diff --git a/files/vi/web/javascript/reference/global_objects/string/replace/index.html b/files/vi/web/javascript/reference/global_objects/string/replace/index.html new file mode 100644 index 0000000000..b9d5330c6c --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/replace/index.html @@ -0,0 +1,233 @@ +--- +title: String.prototype.replace() +slug: Web/JavaScript/Reference/Global_Objects/String/replace +translation_of: Web/JavaScript/Reference/Global_Objects/String/replace +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>replace()</code></strong> sẽ trả về một chuỗi mới với một vài (hoặc tất cả) phần tử trùng khớp với <code>pattern</code> được thay thế bằng <code>replacement</code>. Pattern có thể là một chuỗi, hoặc một {{jsxref("RegExp")}}, và replacement có thể là một chuỗi, hoặc một function được gọi áp dụng cho mỗi kết quả trùng khớp. Nếu pattern là một chuỗi, thì phương thức replace() chỉ trả về kết quả đầu tiên trùng khớp.</p> + +<p>Replace() không làm thay đổi chuỗi gốc.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-replace.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate">const newStr = <var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubstr</var>|<var>function</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><var>regexp</var></code> (pattern)</dt> + <dd>Một {{jsxref("RegExp")}} object hoặc biểu thức RegEx. Phần tử được match sẽ được thay thế bởi <code><var>newSubstr</var></code> hoặc giá trị trả về bởi <code><var>function</var></code>.</dd> + <dt><code><var>substr</var></code></dt> + <dd>Một {{jsxref("String")}} cái mà sẽ bị thay thế bởi <code><var>newSubstr</var></code>. String này sẽ được xem như là một literal string và không phải là một regular expression. Nên chỉ có phần tử trùng khớp đầu tiên sẽ bị thay thế.</dd> + <dt><code><var>newSubstr</var></code> (replacement)</dt> + <dd>Một {{jsxref("String")}} có nhiệm vụ thay thế substr được chỉ định trong <code><var>regexp</var></code> hoặc <code><var>substr</var></code>. Có nhiều kiểu thay thế khác nhau, xem chi tiết tại phần "<a href="#Specifying_a_string_as_a_parameter">Specifying a string as a parameter</a>" bên dưới.</dd> + <dt><code><var>function</var></code> (replacement)</dt> + <dd>Function được định nghĩa và gọi để sử dụng cho việc thay thế các phần tử trùng khớp với regexp hoặc substr. Đối số của function này có thể là các loại sau, xem chi tiết tại phần: "<a href="#Specifying_a_function_as_a_parameter">Specifying a function as a parameter</a>" bên dưới.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Một string mới, với một số phần tử trùng khớp (hoặc tất cả phần tử trùng khớp) đã bị thay thế bởi các replacement.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Phương thức này không làm thay đổi {{jsxref("String")}} gốc. Nó chỉ đơn giản tạo ra một string mới.</p> + +<p>Để thực hiện tìm kiếm global search và replace, hãy thêm từ khóa <code>g</code> và biểu thức regular expression.</p> + +<h3 id="Specifying_a_string_as_a_parameter">Specifying a string as a parameter</h3> + +<p>The replacement string can include the following special replacement patterns:</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">Pattern</th> + <th class="header" scope="col">Inserts</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>$$</code></td> + <td>Inserts a <code>"$"</code>.</td> + </tr> + <tr> + <td><code>$&</code></td> + <td>Inserts the matched substring.</td> + </tr> + <tr> + <td><code>$`</code></td> + <td>Inserts the portion of the string that precedes the matched substring.</td> + </tr> + <tr> + <td><code>$'</code></td> + <td>Inserts the portion of the string that follows the matched substring.</td> + </tr> + <tr> + <td><code>$<var>n</var></code></td> + <td>Where <code><var>n</var></code> is a positive integer less than 100, inserts the <code><var>n</var></code>th parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. Note that this is <code>1</code>-indexed.</td> + </tr> + </tbody> +</table> + +<h3 id="Specifying_a_function_as_a_parameter">Specifying a function as a parameter</h3> + +<p>You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (<strong>Note:</strong> The above-mentioned special replacement patterns do <em>not</em> apply in this case.)</p> + +<p>Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.</p> + +<p>The arguments to the function are as follows:</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">Possible name</th> + <th class="header" scope="col">Supplied value</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>match</code></td> + <td>The matched substring. (Corresponds to <code>$&</code> above.)</td> + </tr> + <tr> + <td><code>p1, p2, ...</code></td> + <td>The <var>n</var>th string found by a parenthesized capture group, provided the first argument to <code>replace()</code> was a {{jsxref("RegExp")}} object. (Corresponds to <code>$1</code>, <code>$2</code>, etc. above.) For example, if <code>/(\a+)(\b+)/</code>, was given, <code>p1</code> is the match for <code>\a+</code>, and <code>p2</code> for <code>\b+</code>.</td> + </tr> + <tr> + <td><code>offset</code></td> + <td>The offset of the matched substring within the whole string being examined. (For example, if the whole string was <code>'abcd'</code>, and the matched substring was <code>'bc'</code>, then this argument will be <code>1</code>.)</td> + </tr> + <tr> + <td><code>string</code></td> + <td>The whole string being examined.</td> + </tr> + </tbody> +</table> + +<p>(The exact number of arguments depends on whether the first argument is a {{jsxref("RegExp")}} object—and, if so, how many parenthesized submatches it specifies.)</p> + +<p>The following example will set <code>newString</code> to <code>'abc - 12345 - #$*%'</code>:</p> + +<pre class="brush: js notranslate">function replacer(match, p1, p2, p3, offset, string) { + // p1 is nondigits, p2 digits, and p3 non-alphanumerics + return [p1, p2, p3].join(' - '); +} +let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); +console.log(newString); // abc - 12345 - #$*% +</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Định_nghĩa_một_biểu_thức_regular_expression_trong_phương_thức_replace">Định nghĩa một biểu thức regular expression trong phương thức replace()</h3> + +<p>Ví dụ bên dưới, regular expression được định nghĩa trong <code>replace()</code> và nó có thêm flat "i" (giúp kết quả matching không phân biệt chữ hoa và chữ thường).</p> + +<pre class="brush: js notranslate">let str = 'Twas the night before Xmas...'; +let newstr = str.replace(/xmas/i, 'Christmas'); +console.log(newstr); // Twas the night before Christmas... +</pre> + +<p>This logs <code>'Twas the night before Christmas...'</code>.</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> See <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">this guide</a> for more explanations about regular expressions.</p> +</div> + +<h3 id="Sử_dụng_flag_global_và_flag_ignore_trong_replace">Sử dụng flag global và flag ignore trong replace()</h3> + +<p>Global replace (thay thế tất cả kết quả trùng khớp) có thể được thực hiện trong regex. Ví dụ sau, biểu thức regex có chứa các flag <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2">global and ignore case flags</a> cho phép <code>replace()</code> sẽ thay thế mỗi string <code>'apples'</code> trong chuỗi gốc với string <code>'oranges'</code>. </p> + +<pre class="brush: js notranslate">let re = /apples/gi; +let str = 'Apples are round, and apples are juicy.'; +let newstr = str.replace(re, 'oranges'); +console.log(newstr); // oranges are round, and oranges are juicy. +</pre> + +<p>This logs <code>'oranges are round, and oranges are juicy'</code>.</p> + +<h3 id="Đảo_ngược_vị_trí_của_2_từ_trong_một_string">Đảo ngược vị trí của 2 từ trong một string</h3> + +<p>Đoạn code bên dưới sẽ đảo qua lại vị trí của các từ trong một string. Ở phần replacement, đoạn code sử dụng <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">capturing groups</a> và ký tự <code>$1,$2</code> để làm pattern cho phần replacement.</p> + +<pre class="brush: js notranslate">let re = /(\w+)\s(\w+)/; +let str = 'John Smith'; +let newstr = str.replace(re, '$2, $1'); +console.log(newstr); // Smith, John +</pre> + +<p>This logs <code>'Smith, John'</code>.</p> + +<h3 id="Sử_dụng_một_inline_function_để_thay_đổi_các_giá_trị_matched">Sử dụng một inline function để thay đổi các giá trị matched</h3> + +<p>Trong ví dụ này, tất cả trường hợp chữ cái viết hoa trong một string sẽ được convert sang dạng viết thường, và dấu gạch ngang sẽ được thêm vào trước vị trí matching đó. Điều quan trọng ở đây, là cần thêm vào các dấu gạch ngang này trước khi trả về một replacement hoàn chỉnh để sử dụng.</p> + +<p>Replacement function này sẽ nhận vào các đoạn trích mà đã match với pattern làm tham số, và sử dụng các đoạn trích đó để biến đổi chữ hoa chữ thường, và ghép nối một dấu gạch ngang vào trước mỗi đoạn trích.</p> + +<pre class="brush: js notranslate">function styleHyphenFormat(propertyName) { + function upperToHyphenLower(match, offset, string) { + return (offset > 0 ? '-' : '') + match.toLowerCase(); + } + return propertyName.replace(/[A-Z]/g, upperToHyphenLower); +} +</pre> + +<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns <code>'border-top'</code>.</p> + +<p>Because we want to further transform the <em>result</em> of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.</p> + +<pre class="brush: js example-bad notranslate">let newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work +</pre> + +<p>This is because <code>'$&'.toLowerCase()</code> would first be evaluated as a string literal (resulting in the same <code>'$&'</code>) before using the characters as a pattern.</p> + +<h3 id="Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent">Replacing a Fahrenheit degree with its Celsius equivalent</h3> + +<p>The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with <code>"F"</code>. The function returns the Celsius number ending with <code>"C"</code>. For example, if the input number is <code>"212F"</code>, the function returns <code>"100C"</code>. If the number is <code>"0F"</code>, the function returns <code>"-17.77777777777778C"</code>.</p> + +<p>The regular expression <code>test</code> checks for any number that ends with <code>F</code>. The number of Fahrenheit degree is accessible to the function through its second parameter, <code>p1</code>. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the <code>f2c()</code> function. <code>f2c()</code> then returns the Celsius number. This function approximates Perl's <code>s///e</code> flag.</p> + +<pre class="brush: js notranslate">function f2c(x) { + function convert(str, p1, offset, s) { + return ((p1 - 32) * 5/9) + 'C'; + } + let s = String(x); + let test = /(-?\d+(?:\.\d*)?)F\b/g; + return s.replace(test, convert); +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.replace")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.replaceAll", "String.prototype.replaceAll()")}}</li> + <li>{{jsxref("String.prototype.match", "String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec", "RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test", "RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/slice/index.html b/files/vi/web/javascript/reference/global_objects/string/slice/index.html new file mode 100644 index 0000000000..002f1be65f --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/slice/index.html @@ -0,0 +1,138 @@ +--- +title: String.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/String/slice +translation_of: Web/JavaScript/Reference/Global_Objects/String/slice +--- +<div>{{JSRef}}</div> + +<p>Phương thức <strong><code>slice()</code></strong> tạo ra một Chuỗi mới từ một phần của Chuỗi hiện tại.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>str</var>.slice(<var>beginSlice</var>[, <var>endSlice</var>])</code></pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>beginSlice</code></dt> + <dd>Chỉ số điểm bắt đầu của chuỗi con muốn lấy - bắt đầu từ 0. Nếu tham số này là số âm, thì nó tương đương với việc bạn gán nó bằng <code>"độ dài chuỗi" + beginSlice</code>. Ví dụ nếu <code>beginSlice </code>bằng <code>-3</code> thì tương đương với <code>beginSlice</code> bằng <code>"đội dài chuỗi" - 3</code>.</dd> + <dt><code>endSlice</code></dt> + <dd>Tham số này không bắt buộc. Nếu có nó sẽ chỉ điểm cuối của chuỗi con muốn lấy. Nếu tham số này âm, nó sẽ được hiểu bằng <code>"đội dài chuỗi" + endSlice</code>. Ví dụ <code>endSlice</code> bằng <code>-3</code> nó sẽ tương đương với <code>"độ dài chuỗi" - 3</code></dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>slice()</code> thực hiện lấy một phần chuỗi từ chuỗi ban đầu và trả về một chuỗi mới. Chuỗi ban đầu sẽ không bị thay đổi giá trị.</p> + +<p><code>slice()</code> sẽ lấy một phần chuỗi nhưng sẽ không chứa ký tự có chỉ số bằng với tham số endSlice. <code>str.slice(1, 4)</code> sẽ chỉ lấy ba ký tự 1,2 và 3.</p> + +<p>Ví dụ khác, <code>str.slice(2, -1)</code> sẽ lấy từ ký tự thứ 3 đến ký tự gần cuối, ký tự cuối không được đưa vào chuỗi mới</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Dùng_slice()_để_tạo_chuỗi_mới">Dùng <code>slice()</code> để tạo chuỗi mới</h3> + +<p>Ví dụ sau sử dụng <code>slice()</code> để tạo chuỗi mới.</p> + +<pre class="brush: js">var str1 = 'The morning is upon us.'; +var str2 = str1.slice(4, -2); + +console.log(str2); // OUTPUT: morning is upon u +</pre> + +<h3 id="Dùng_slice()_với_chỉ_số_âm">Dùng <code>slice()</code> với chỉ số âm</h3> + +<p>Ví dụ sau sử dụng <code>slice()</code> với chỉ số âm.</p> + +<pre class="brush: js">var str = 'The morning is upon us.'; +str.slice(-3); // returns 'us.' +str.slice(-3, -1); // returns 'us' +str.slice(0, -1); // returns 'The morning is upon us' +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tạ</th> + <th scope="col">Trạng thái</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_hỗ_trợ_của_các_trình_duyệt">Khả năng hỗ trợ của các trình duyệt</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> + <li>{{jsxref("Array.prototype.slice()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html b/files/vi/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..7d3f6bfaa6 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,128 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +<div>{{JSRef}}</div> + +<p><strong><code>startsWith()</code></strong> method xác định liệu một chuỗi bắt đầu với các chữ cái của chuỗi khác hay không, trả về giá trị true hoặc false tương ứng.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><code><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</code></pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>Các ký tự cần tìm kiếm tại vị trí bắt đầu của chuỗi này.</dd> + <dt><code>position</code></dt> + <dd>Tùy chọn. Vị trí trong chuỗi bắt đầu tìm kiếm cho <code>searchString;</code> mặc định là 0.</dd> +</dl> + +<h2 id="Miêu_tả">Miêu tả</h2> + +<p>Method này cho phép bạn xác định liệu một chuỗi có bắt đầu với chuỗi khác không.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Cách_sử_dụng_startsWith()">Cách sử dụng <code>startsWith()</code></h3> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; + +console.log(str.startsWith('To be')); // true +console.log(str.startsWith('not to be')); // false +console.log(str.startsWith('not to be', 10)); // true +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Method này đã được thêm vào chỉ dẫn kỹ thuật ECMAScript 6 và có thể chưa có sẵn trong tất cả JavaScript implementations. Tuy nhiên, bạn có thể polyfill String.prototype.startWith() với snippet sau:</p> + +<pre class="brush: js">if (!String.prototype.startsWith) { + String.prototype.startsWith = function(searchString, position) { + position = position || 0; + return this.indexOf(searchString, position) === position; + }; +} +</pre> + +<p>Polyfill mạnh và được tối ưu hơn có sẵn <a href="https://github.com/mathiasbynens/String.prototype.startsWith">trên GitHub bởi Mathias Bynens</a>.</p> + +<h2 id="Hướng_dẫn_kỹ_thuật">Hướng dẫn kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_với_Browser">Khả năng tương thích với Browser</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("41")}}</td> + <td>{{CompatGeckoDesktop("17")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("41")}}</td> + <td>{{CompatSafari("9")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatGeckoMobile("17")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}</li> + <li>{{jsxref("String.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/substr/index.html b/files/vi/web/javascript/reference/global_objects/string/substr/index.html new file mode 100644 index 0000000000..c7d477fede --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/substr/index.html @@ -0,0 +1,121 @@ +--- +title: String.prototype.substr() +slug: Web/JavaScript/Reference/Global_Objects/String/substr +translation_of: Web/JavaScript/Reference/Global_Objects/String/substr +--- +<div>{{JSRef}}</div> + +<div>Phương thức <strong><code>substr()</code></strong>trả về những ký tự trong một chuỗi được xác định bởi vị trí ký tự bắt đầu và số lượng ký tự theo sau đó.</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>str</var>.substr(<var>start</var>, [<var>length]</var>)</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>start (bắt đầu)</code></dt> + <dd><code>Vị trí chính xác của ký tự bắt đầu. Nếu là một số âm, nó sẽ được xử lý như sau <strong>strLength</strong> - <strong>start </strong>trong đó strLength</code>là chiều dài của chuỗi. Ví dụ, <code>str.substr(-3) </code>sẽ được coi như là<code> str.substr(str.length -3)</code></dd> + <dt><code>length (độ dài)</code></dt> + <dd>Số lượng ký tự muốn lấy ra. Nếu tham số này là {{jsxref("undefined")}}, tất cả các ký tự từ vị trí bắt đầu tới kết thúc của chuỗi sẽ được lấy.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một chuỗi mới là phần đã lấy ra từ chuỗi ban đầu. Nếu <strong>length</strong> là <strong>0</strong> hoặc là một số âm thì trả về một chuỗi rỗng.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p><code>start</code> là chỉ số của ký tự. Chỉ số của ký tự đầu tiên là 0, và chỉ số của ký tự cuối cùng thì nhỏ hơn độ dài của chuỗi là 1. <code>substr()</code> bắt đầu lấy các ký tự tại <code>start</code> và thu thập <code>length</code> các ký tự( trừ khi nó chấm tới cuối chuỗi trước, trong trường hợp này nó sẽ trả về ít hơn).</p> + +<p>Nếu <code>start</code> là số dương và lớn hơn hoặc bằng chiều dài của chuỗi, <code>substr()</code> trả về một chuỗi rỗng.</p> + +<p>Nếu <code>start</code> là số âm, <code>substr()</code> coi nó như chỉ là chỉ số của ký tự tính từ cuối chuỗi; chỉ số của ký tự cuối cùng là -1. Nếu <code>start</code> là số âm và <code>abs(start)</code> lớn hơn chiều dài của chuỗi,<code>substr()</code> coi 0 như là chỉ số bắt đầu.</p> + +<p>Chú ý: Việc xử lý giá trị âm của tham số <code>start</code> như ở trên không được Microsoft JScript hỗ trợ.</p> + +<p>Nếu <code>length</code> là 0 hoặc âm, <code>substr()</code> trả về một mảng rỗng. Nếu <code>length</code> bị bỏ sót, <code>substr()</code> lấy các ký tự cho tới cuối chuỗi.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_substr()">Sử dụng <code>substr()</code></h3> + +<pre class="brush: js">var str = 'abcdefghij'; + +console.log('(1, 2): ' + str.substr(1, 2)); // '(1, 2): bc' +console.log('(-3, 2): ' + str.substr(-3, 2)); // '(-3, 2): hi' +console.log('(-3): ' + str.substr(-3)); // '(-3): hij' +console.log('(1): ' + str.substr(1)); // '(1): bcdefghij' +console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab' +console.log('(20, 2): ' + str.substr(20, 2)); // '(20, 2): ' +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Microsoft's JScript không hỗ trợ các giá trị âm cho chi số bắt đầu. Nếu bạn mong muốn sử dụng tính năng này, bạn có thể sử dụng đoạn code dưới đây để xử lý bug này:</p> + +<pre class="brush: js">// only run when the substr() function is broken +if ('ab'.substr(-1) != 'b') { + /** + * Get the substring of a string + * @param {integer} start where to start the substring + * @param {integer} length how many characters to return + * @return {string} + */ + String.prototype.substr = function(substr) { + return function(start, length) { + // call the original method + return substr.call(this, + // did we get a negative start, calculate how much it is from the beginning of the string + // adjust the start parameter for negative value + start < 0 ? this.length + start : start, + length) + } + }(String.prototype.substr); +} +</pre> + +<h2 id="Các_quy_cách">Các quy cách</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Quy cách</th> + <th scope="col">Tình trạng</th> + <th scope="col">Ý kiến</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). Ap dung trong JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_với_trình_duyệt">Tương thích với trình duyệt</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.substr")}}</p> + +<h2 id="Tương_tự">Tương tự</h2> + +<ul> + <li>{{jsxref("String.prototype.slice()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/string/substring/index.html b/files/vi/web/javascript/reference/global_objects/string/substring/index.html new file mode 100644 index 0000000000..e53b920581 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/string/substring/index.html @@ -0,0 +1,195 @@ +--- +title: String.prototype.substring() +slug: Web/JavaScript/Reference/Global_Objects/String/substring +translation_of: Web/JavaScript/Reference/Global_Objects/String/substring +--- +<div>{{JSRef}}</div> + +<p><strong><code>substring()</code></strong> phương thức trả về chuỗi con của 1 chuỗi bắt đầu từ vị trí bắt đầu đến vị trí kết thúc, hoặc đến cuối chuỗi nếu không có vị trí kết thúc</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><var>indexStart</var></code></dt> + <dd>Một số integer giữa 0 và một số nhỏ hơn độ dài chuỗi, xác định vị trí kí tự đầu tiên trong chuỗi gốc để đưa vào chuỗi con.</dd> + <dt><code>indexEnd</code></dt> + <dd>Không bắt buộc. Một số integer giữa 0 và độ dài chuỗi. Chuỗi con không bao gồm ký tự ở vị trí indexEnd.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Chuỗi con trả về là chuỗi nằm ở vị trí từ indexStart đến vị trí ( indexEnd - 1 )</p> + +<h2 id="Description">Description</h2> + +<p><code>substring()</code> lấy ký tự từ vị trí <code>indexStart</code> tới vị trí (nhưng không bao gồm) <code>indexEnd</code>. Đặc biệt:</p> + +<ul> + <li>Nếu <code><var>indexStart bằng</var></code> <code><var>indexEnd</var></code>, <code>substring()</code> trả về 1 chuỗi rỗng.</li> + <li>Nếu không có <code>indexEnd</code>, <code>substring()</code> sẽ lấy từ vị trí bắt đầu đến cuối chuỗi. <em>(điều này giống với hàm substr()).</em></li> + <li>Nếu 1 trong 2 giá trị nhỏ hơn 0 hoặc là {{jsxref("NaN")}}, nó sẽ được xử lý như là 0.</li> + <li>Nếu 1 trong 2 giá trị lớn hơn <code>stringName.length</code>, nó sẽ được xử lý như là <code>stringName.length</code>.</li> +</ul> + +<p>Nếu <code>indexStart</code> lớn hơn <code>indexEnd</code>, chúng se được đổi chỗ; ví dụ, <code><em>str</em>.substring(1, 0) == <em>str</em>.substring(0, 1)</code>.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_substring">Using <code>substring()</code></h3> + +<p>The following example uses <code>substring()</code> to display characters from the string <code>'Mozilla'</code>:</p> + +<pre class="brush: js notranslate">var anyString = 'Mozilla'; + +// Displays 'Moz' +console.log(anyString.substring(0, 3)); +console.log(anyString.substring(3, 0)); + +// Displays 'lla' +console.log(anyString.substring(4, 7)); +console.log(anyString.substring(4)); +console.log(anyString.substring(7, 4)); + +// Displays 'Mozill' +console.log(anyString.substring(0, 6)); + +// Displays 'Mozilla' +console.log(anyString.substring(0, 7)); +console.log(anyString.substring(0, 10)); +</pre> + +<h3 id="Using_substring_with_length_property">Using <code>substring()</code> with <code>length</code> property</h3> + +<p>The following example uses the <code>substring()</code> method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.</p> + +<pre class="brush: js notranslate">// Displays 'illa' the last 4 characters +var anyString = 'Mozilla'; +var anyString4 = anyString.substring(anyString.length - 4); +console.log(anyString4); + +// Displays 'zilla' the last 5 characters +var anyString = 'Mozilla'; +var anyString5 = anyString.substring(anyString.length - 5); +console.log(anyString5); +</pre> + +<h3 id="Replacing_a_substring_within_a_string">Replacing a substring within a string</h3> + +<p>The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string <code>'Brave New World'</code> into <code>'Brave New Web'</code>.</p> + +<pre class="brush: js notranslate">// Replaces oldS with newS in the string fullS +function replaceString(oldS, newS, fullS) { + for (var i = 0; i < fullS.length; ++i) { + if (fullS.substring(i, i + oldS.length) == oldS) { + fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length); + } + } + return fullS; +} + +replaceString('World', 'Web', 'Brave New World'); +</pre> + +<p>Note that this can result in an infinite loop if <code>oldS</code> is itself a substring of <code>newS</code> — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:</p> + +<pre class="brush: js notranslate">function replaceString(oldS, newS, fullS) { + return fullS.split(oldS).join(newS); +} +</pre> + +<p>The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}}</li> + <li>{{jsxref("String.prototype.slice()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/global_objects/weakmap/index.html b/files/vi/web/javascript/reference/global_objects/weakmap/index.html new file mode 100644 index 0000000000..bdc4c9d40a --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/weakmap/index.html @@ -0,0 +1,138 @@ +--- +title: WeakMap +slug: Web/JavaScript/Reference/Global_Objects/WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code style=""><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Đối tượng </span></font><strong>WeakMap</strong></code> là bộ sưu tập của các cặp key/value với các key được tham chiếu <em>yếu ớt</em>. Các key phải là đối tượng và các value có thể là bất kỳ giá trị nào. </span></p> + +<p>Bạn có thể tham khảo thêm về <code>WeakMap</code>s trong hướng dẫn <a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object" title="This chapter introduces collections of data which are ordered by a key; Map and Set objects contain elements which are iterable in the order of insertion.">WeakMap object</a> (trong <a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections" title="This chapter introduces collections of data which are ordered by a key; Map and Set objects contain elements which are iterable in the order of insertion.">Keyed collections</a>).</p> + +<h2 id="Description">Description</h2> + +<p>Các key của WeakMap phải là kiểu <code>Object</code>. <a href="/en-US/docs/Glossary/Primitive">Primitive data types</a> không được phép là key(ví dụ một {{jsxref("Symbol")}} không thể là key của <code>WeakMap</code>).</p> + +<h3 id="Why_WeakMap">Why <em>Weak</em>Map?</h3> + +<p>Một map API<em>có thể </em>được triển khai trong JavaScript với 2 mảng (một cho các key, một cho các value) được chia sẽ bởi 4 API method. Thiết lập các phần tử trong map sẽ đẩy đồng thời một key và value vào cuối mỗi mảng. Kết quả là chỉ số của key và value sẽ tương ứng ở cả 2 mảng. Lấy value từ một map sẽ liên quan tới vòng lặp qua tất cả các key để tìm kiếm kết quả phù hợp, sau đó sử dụng chỉ số của kết quả đó để nhận được giá trị tương ứng từ mảng các value.</p> + +<p>Việc thực hiện như vậy sẽ có 2 sự bất tiện chính:</p> + +<ol> + <li>Điều đầu tiên là thiết lập và tìm kiếm trong mảng có n phần tử<em>,</em> vì cả 2 hành động này đều phải lặp lại qua danh sách các key để tìm giá trị thích hợp.</li> + <li>Điều bất tiện thứ 2 là rò rỉ bộ nhớ bởi vì các mảng sẽ phải đảm bảo các tham chiếu tới mỗi key và mỗi value được duy trì vô thời hạn. Các tham chiếu này sẽ ngăn các key khỏi garbage collected, ngay cả khi không có một tham chiếu nào khác tới đối tượng. Điều này cũng ngăn các value tương ứng khỏi garbage collected.</li> +</ol> + +<p>Ngược lại, các <code>WeakMap</code> giữ các tham chiếu "yếu" tới key, điều này có nghĩa chúng không được bảo vệ khỏi garbage collection trong trường hợp không có tham chiếu nào tới key. Điều này cũng tương tự với value. WeakMaps có thể đặc biệt là cấu trúc hiệu quả khi cần ánh xạ các key tới các thông tin về key có giá trị chỉ khi key chưa được thu gom rác.</p> + +<p><strong>Bởi vì các tham chiếu là yếu, các key của <code>WeakMap</code> key không thể đếm được.</strong> Không có phương thức nào để lấy được danh sách các key. Nếu có, danh sách key sẽ phụ thuộc vào trạng thái của garbage collection, đưa ra tính không xác định. Nếu bạn muốn lấy được danh sách của key, bạn phải sử dụng {{jsxref("Map")}}.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/WeakMap">WeakMap()</a></code></dt> + <dd>Creates new <code>WeakMap</code> objects.</dd> +</dl> + +<h2 id="Instance_methods">Instance methods</h2> + +<dl> + <dt>{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(<var>key</var>)")}}</dt> + <dd>Removes any value associated to the <code><var>key</var></code>. <code>WeakMap.prototype.has(<var>key</var>)</code> will return <code>false</code> afterwards.</dd> + <dt>{{jsxref("WeakMap.get", "WeakMap.prototype.get(<var>key</var>)")}}</dt> + <dd>Returns the value associated to the <code><var>key</var></code>, or <code>undefined</code> if there is none.</dd> + <dt>{{jsxref("WeakMap.has", "WeakMap.prototype.has(<var>key</var>)")}}</dt> + <dd>Returns a Boolean asserting whether a value has been associated to the <code><var>key</var></code> in the <code>WeakMap</code> object or not.</dd> + <dt>{{jsxref("WeakMap.set", "WeakMap.prototype.set(<var>key</var>, <var>value</var>)")}}</dt> + <dd>Sets the <code><var>value</var></code> for the <code><var>key</var></code> in the <code>WeakMap</code> object. Returns the <code>WeakMap</code> object.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_WeakMap">Using <code>WeakMap</code></h3> + +<pre class="brush: js">const wm1 = new WeakMap(), + wm2 = new WeakMap(), + wm3 = new WeakMap(); +const o1 = {}, + o2 = function() {}, + o3 = window; + +wm1.set(o1, 37); +wm1.set(o2, 'azerty'); +wm2.set(o1, o2); // a value can be anything, including an object or a function +wm2.set(o3, undefined); +wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps! + +wm1.get(o2); // "azerty" +wm2.get(o2); // undefined, because there is no key for o2 on wm2 +wm2.get(o3); // undefined, because that is the set value + +wm1.has(o2); // true +wm2.has(o2); // false +wm2.has(o3); // true (even if the value itself is 'undefined') + +wm3.set(o1, 37); +wm3.get(o1); // 37 + +wm1.has(o1); // true +wm1.delete(o1); +wm1.has(o1); // false +</pre> + +<h3 id="Implementing_a_WeakMap-like_class_with_a_.clear_method">Implementing a <code>WeakMap</code>-like class with a .clear() method</h3> + +<pre class="brush: js">class ClearableWeakMap { + constructor(init) { + this._wm = new WeakMap(init); + } + clear() { + this._wm = new WeakMap(); + } + delete(k) { + return this._wm.delete(k); + } + get(k) { + return this._wm.get(k); + } + has(k) { + return this._wm.has(k); + } + set(k, v) { + this._wm.set(k, v); + return this; + } +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-weakmap-objects', 'WeakMap')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.WeakMap")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object"><code>WeakMap</code> in the JavaScript guide</a></li> + <li><a href="http://fitzgeraldnick.com/weblog/53/">Hiding Implementation Details with ECMAScript 6 WeakMaps</a></li> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/index.html b/files/vi/web/javascript/reference/index.html new file mode 100644 index 0000000000..be6e0ebe3d --- /dev/null +++ b/files/vi/web/javascript/reference/index.html @@ -0,0 +1,50 @@ +--- +title: JavaScript reference +slug: Web/JavaScript/Reference +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference +--- +<div>{{JsSidebar}}</div> + +<p>This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more <a href="/en-US/docs/Web/JavaScript/Reference/About">about this reference</a>.</p> + +<h2 id="Global_Objects">Global Objects</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">JavaScript standard built-in objects</a>, along with their methods and properties.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}</div> + +<h2 id="Statements">Statements</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements and declarations</a>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}</div> + +<h2 id="Expressions_and_operators">Expressions and operators</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Operators">JavaScript expressions and operators</a>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}</div> + +<h2 id="Functions">Functions</h2> + +<p>This chapter documents how to work with <a href="/en-US/docs/Web/JavaScript/Reference/Functions">JavaScript functions</a> to develop your applications.</p> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default parameters</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> +</ul> + +<h2 id="Additional_reference_pages">Additional reference pages</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated features</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/iteration_protocols/index.html b/files/vi/web/javascript/reference/iteration_protocols/index.html new file mode 100644 index 0000000000..2485382349 --- /dev/null +++ b/files/vi/web/javascript/reference/iteration_protocols/index.html @@ -0,0 +1,383 @@ +--- +title: Iteration protocols +slug: Web/JavaScript/Reference/Iteration_protocols +translation_of: Web/JavaScript/Reference/Iteration_protocols +--- +<div>{{jsSidebar("More")}}</div> + +<p>Là một vài bổ sung cho ECMAScript 2015, <strong>Iteration protocols</strong> không phải là một tích hợp sẵn hay cú pháp mới mà là <em>protocols</em>. Các giao thức này có thể triển khai bởi bất kỳ đối tượng nào đơn giản bằng cách thực hiện theo một số quy ước.</p> + +<p>Có 2 giao thức: <a href="#The_iterable_protocol">iterable protocol</a> và <a href="#The_iterator_protocol">iterator protocol</a>.</p> + +<h2 id="The_iterable_protocol">The iterable protocol</h2> + +<p><strong>Iterable protocol</strong> cho phép các đối tượng của JavaScript xác định hoặc tuỳ chỉnh hành vi lặp của chúng, chẳng hạn như giá trị nào sẽ được lặp trong vòng lặp {{jsxref("Statements/for...of", "for...of")}}. Một số kiểu tích hợp sẵn <a href="#Built-in_iterables">built-in iterables</a> là hành vi lặp mặc định, chẳng hạn như {{jsxref("Array")}} hoặc {{jsxref("Map")}}, trong khi các kiểu khác (chẳng hạn {{jsxref("Object")}}) không có.</p> + +<p>Để có thể triển khai giao thức <strong>iterable</strong>, một đối tượng phải có phương thức <strong><code>@@iterator</code></strong>, điều này có nghĩa là một đối tượng (hoặc một trong các đối tượng trên <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">prototype chain</a> của đối tượng đó) phải có một thuộc tính <code>@@iterator</code> và thao tác với thuộc tính đó thông qua hằng số {{jsxref("Symbol.iterator")}}:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Value</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>[Symbol.iterator]</code></td> + <td>Một hàm không có tham số đầu vào trả ra một đối tượng phù hợp với <a href="#The_iterator_protocol">iterator protocol</a>.</td> + </tr> + </tbody> +</table> + +<p>Bất cứ khi nào một đối tượng thực hiện vòng lặp (chẳng hạn như sử dụng vòng lặp {{jsxref("Statements/for...of", "for...of")}}), phương thức <code>@@iterator</code> sẽ được gọi mà không có tham số đầu vào, và trả ra <strong>iterator</strong> được sử dụng để thu được giá trị được lặp.</p> + +<p>Lưu ý khi hàm không tham số đầu vào được gọi, nó sẽ được gọi như là một phương thức của iterable object. Do đó bên trong hàm, từ khoá <code>this</code> có thể được sử dụng để truy cập vào các thuộc tính của iterable object, để quyết định những gì được cung cấp trong quá trình lặp.</p> + +<p>Hàm này có thể là một hàm bình thường hoặc nó có thể là một generator function, do đó khi được gọi, một iterator object sẽ được trả về. Bên trong của generator function, mỗi giá trị trả về có thể cung cấp bằng cách sử dụng <code>yield</code>.</p> + +<h2 id="The_iterator_protocol">The iterator protocol</h2> + +<p><strong>Ierator protocol</strong> định nghĩa một cách tiêu chuẩn để tạo ra một chuỗi các giá trị (hưu hạn hoặc vô hạn), và có thể trả về 1 giá trị khi tất cả các giá trị đã được tạo.</p> + +<p>Một đối tượng là một iterator khi nó triển khai phương thức <code><strong>next()</strong></code> với ý nghĩa như sau:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Value</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>next()</code></td> + <td> + <p>Một hàm không tham số đầu vào trả ra một đối tượng có ít nhất 2 thuộc tính sau: </p> + + <dl> + <dt><code>done</code> (boolean)</dt> + <dd> + <p>Có giá trị <code>false</code> nếu iterator có thể tạo ra giá trị tiếp theo trong chuỗi. (This is equivalent to not specifying the <code>done</code> property altogether.)</p> + + <p>Có giá trị <code>true</code> nếu iterator kết thúc chuỗi. Trong trường hợp này, <code>value</code> có thể tuỳ chọn giá trị trả về cho iterator.</p> + </dd> + <dt><code>value</code></dt> + <dd>Bất kỳ giá trị JavaScript nào được trả về bởi iterator. ?Có thể bỏ qua khi <code>done</code> là <code>true</code>.</dd> + </dl> + + <p>Phương thức <code>next()</code> phải luôn luôn trả về một đối tượng với các thuộc tính thích hợp bao gồm <code>done</code> và <code>value</code>. Nếu một giá trị không phải đối tượng được trả về (chẳng hạn như <code>false</code> hoặc <code>undefined</code>), một {{jsxref("TypeError")}} (<code>"iterator.next() returned a non-object value"</code>) sẽ được đẩy ra.</p> + </td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Lưu ý:</strong> Không thể biết liệu một đối tượng cụ thể có triển khai giao thức iterator hay không. Tuy nhiên, dễ dàng để tạo ra một đối tượng mà có cả 2 giao thức iterator và iterable (như ví dụ dưới đây).</p> + +<p>Làm như vậy cho phép một iterator có thể sử dụng các cú pháp đa dạng của iterables. Vì vậy, rất hiếm khi triển khai giao thức Iterator Protocol mà không triển khai Iterable.</p> + +<pre class="brush: js example-good">// Satisfies both the Iterator Protocol and Iterable +let myIterator = { + next: function() { + // ... + }, + [Symbol.iterator]: function() { return this; } +}; +</pre> +</div> + +<h2 id="Examples_using_the_iteration_protocols">Examples using the iteration protocols</h2> + +<p>{{jsxref("String")}} là một ví dụ tích hợp sẵn iterable object:</p> + +<pre class="brush: js">let someString = 'hi'; +console.log(typeof someString[Symbol.iterator]); // "function" +</pre> + +<p>{{jsxref("String/@@iterator", "iterator mặc định", "", 1)}} của <code>String</code> trả ra lần lượt từng mã của các ký tự:</p> + +<pre class="brush: js">let iterator = someString[Symbol.iterator](); +console.log(iterator + ''); // "[object String Iterator]" + +console.log(iterator.next()); // { value: "h", done: false } +console.log(iterator.next()); // { value: "i", done: false } +console.log(iterator.next()); // { value: undefined, done: true }</pre> + +<p>Some built-in constructs—such as the {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}—use the same iteration protocol under the hood:</p> + +<pre class="brush: js">console.log([...someString]); // ["h", "i"]</pre> + +<p>You can redefine the iteration behavior by supplying our own <code>@@iterator</code>:</p> + +<pre class="brush: js">// need to construct a String object explicitly to avoid auto-boxing +let someString = new String('hi'); + +someString[Symbol.iterator] = function () { + return { + // this is the iterator object, returning a single element (the string "bye") + next: function () { + return this._first ? { + value: 'bye', + done: (this._first = false) + } : { + done: true + } + }, + _first: true + }; +}; +</pre> + +<p>Notice how redefining <code>@@iterator</code> affects the behavior of built-in constructs that use the iteration protocol:</p> + +<pre class="brush: js">console.log([...someString]); // ["bye"] +console.log(someString + ''); // "hi" +</pre> + +<h2 id="Iterable_examples">Iterable examples</h2> + +<h3 id="Built-in_iterables">Built-in iterables</h3> + +<p>{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, and {{jsxref("Set")}} are all built-in iterables, because each of their prototype objects implements an <code>@@iterator</code> method.</p> + +<h3 id="User-defined_iterables">User-defined iterables</h3> + +<p>You can make your own iterables like this:</p> + +<pre class="brush: js">let myIterable = {}; +myIterable[Symbol.iterator] = function* () { + yield 1; + yield 2; + yield 3; +}; +console.log([...myIterable]); // [1, 2, 3] +</pre> + +<h3 id="Built-in_APIs_accepting_iterables">Built-in APIs accepting iterables</h3> + +<p>There are many APIs that accept iterables. Some examples include:</p> + +<ul> + <li>{{jsxref("Map", "new Map([<var>iterable</var>])")}}</li> + <li>{{jsxref("WeakMap", "new WeakMap([<var>iterable</var>])")}}</li> + <li>{{jsxref("Set", "new Set([<var>iterable</var>])")}}</li> + <li>{{jsxref("WeakSet", "new WeakSet([<var>iterable</var>])")}}</li> +</ul> + +<pre class="brush: js">new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" + +let myObj = {}; + +new WeakMap([ + [{}, 'a'], + [myObj, 'b'], + [{}, 'c'] +]).get(myObj); // "b" + +new Set([1, 2, 3]).has(3); // true +new Set('123').has('2'); // true + +new WeakSet(function* () { + yield {} + yield myObj + yield {} +}()).has(myObj); // true +</pre> + +<h4 id="See_Also">See Also</h4> + +<ul> + <li>{{jsxref("Promise.all()", "Promise.all(<var>iterable</var>)")}}</li> + <li>{{jsxref("Promise.race()", "Promise.race(<var>iterable</var>)")}}</li> + <li>{{jsxref("Array.from()", "Array.from(<var>iterable</var>)")}}</li> +</ul> + +<h3 id="Syntaxes_expecting_iterables">Syntaxes expecting iterables</h3> + +<p>Some statements and expressions expect iterables, for example the {{jsxref("Statements/for...of", "for...of")}} loops, the {{jsxref("Operators/Spread_syntax", "spread operator", "", 1)}})}}, {{jsxref("Operators/yield*", "yield*")}}, and {{jsxref("Operators/Destructuring_assignment", "destructuring assignment")}}:</p> + +<pre class="brush: js">for (let value of ['a', 'b', 'c']) { + console.log(value); +} +// "a" +// "b" +// "c" + +console.log([...'abc']); // ["a", "b", "c"] + +function* gen() { + yield* ['a', 'b', 'c']; +} + +console.log(gen().next()); // { value: "a", done: false } + +[a, b, c] = new Set(['a', 'b', 'c']); +console.log(a); // "a" + +</pre> + +<h3 id="Non-well-formed_iterables">Non-well-formed iterables</h3> + +<p>If an iterable's <code>@@iterator</code> method doesn't return an iterator object, then it's considered a <em>non-well-formed</em> iterable.</p> + +<p>Using one is likely to result in runtime errors or buggy behavior:</p> + +<pre class="brush: js example-bad">let nonWellFormedIterable = {}; +nonWellFormedIterable[Symbol.iterator] = () => 1; +[...nonWellFormedIterable]; // TypeError: [] is not a function +</pre> + +<h2 id="Iterator_examples">Iterator examples</h2> + +<h3 id="Simple_iterator">Simple iterator</h3> + +<pre class="brush: js">function makeIterator(array) { + let nextIndex = 0 + return { + next: function() { + return nextIndex < array.length ? { + value: array[nextIndex++], + done: false + } : { + done: true + }; + } + }; +} + +let it = makeIterator(['yo', 'ya']); + +console.log(it.next().value); // 'yo' +console.log(it.next().value); // 'ya' +console.log(it.next().done); // true +</pre> + +<h3 id="Infinite_iterator">Infinite iterator</h3> + +<pre class="brush: js">function idMaker() { + let index = 0; + return { + next: function() { + return { + value: index++, + done: false + }; + } + }; +} + +let it = idMaker(); + +console.log(it.next().value); // '0' +console.log(it.next().value); // '1' +console.log(it.next().value); // '2' +// ... +</pre> + +<h3 id="With_a_generator">With a generator</h3> + +<pre class="brush: js">function* makeSimpleGenerator(array) { + let nextIndex = 0; + while (nextIndex < array.length) { + yield array[nextIndex++]; + } +} + +let gen = makeSimpleGenerator(['yo', 'ya']); + +console.log(gen.next().value); // 'yo' +console.log(gen.next().value); // 'ya' +console.log(gen.next().done); // true + +function* idMaker() { + let index = 0; + while (true) { + yield index++; + } +} + +let gen = idMaker() + +console.log(gen.next().value); // '0' +console.log(gen.next().value); // '1' +console.log(gen.next().value); // '2' +// ... +</pre> + +<h3 id="With_ES2015_class">With ES2015 class</h3> + +<pre class="brush: js">class SimpleClass { + constructor(data) { + this.data = data; + } + + [Symbol.iterator]() { + // Use a new index for each iterator. This makes multiple + // iterations over the iterable safe for non-trivial cases, + // such as use of break or nested looping over the same iterable. + let index = 0; + + return { + next: () => { + if (index < this.data.length) { + return {value: this.data[index++], done: false} + } else { + return {done: true} + } + } + } + } +} + +const simple = new SimpleClass([1,2,3,4,5]); + +for (const val of simple) { + console.log(val); // '1' '2' '3' '4' '5' +} +</pre> + +<h2 id="Is_a_generator_object_an_iterator_or_an_iterable">Is a generator object an iterator or an iterable?</h2> + +<p>A {{jsxref("Generator", "generator object", "", 1)}} is <em>both</em> iterator and iterable:</p> + +<pre class="brush: js">let aGeneratorObject = function* () { + yield 1; + yield 2; + yield 3; +}(); + +console.log(typeof aGeneratorObject.next); +// "function", because it has a next method, so it's an iterator + +console.log(typeof aGeneratorObject[Symbol.iterator]); +// "function", because it has an @@iterator method, so it's an iterable + +console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject); +// true, because its @@iterator method returns itself (an iterator), so it's an well-formed iterable + +console.log([...aGeneratorObject]); +// [1, 2, 3] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-iteration', 'Iteration')}}</td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li>To learn more about ES2015 generators, see:<br> + {{jsxref("Statements/function*", "the <code>function*</code> documentation", "", 1)}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/arithmetic_operators/index.html b/files/vi/web/javascript/reference/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..a9fe805490 --- /dev/null +++ b/files/vi/web/javascript/reference/operators/arithmetic_operators/index.html @@ -0,0 +1,312 @@ +--- +title: Toán tử số học +slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Toán tử số học</strong> lấy giá trị số học (cả chuỗi hoặc biến) làm toán hạng của nó và trả về một giá trị số học. Các toán tử số học thông thường là cộng (+), trừ (-), nhân (*), và chia (/).</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}</div> + +<p class="hidden">Mã nguồn cho các ví dụ tương tác trong bài được lưu trên GitHub. Nếu bạn muốn đóng góp thêm ví dụ tương tác, làm ơn <em>clone</em> lại <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi cho chúng tôi một <em>pull request</em>.</p> + +<h2 id="Cộng_()"><a name="Addition">Cộng (+)</a></h2> + +<p>Toán tử cộng xuất ra tổng của toán hạng số học hoặc để nối chuỗi.</p> + +<h3 id="Cú_pháp">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> x + y +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// Number + Number -> addition +1 + 2 // 3 + +// Boolean + Number -> addition +true + 1 // 2 + +// Boolean + Boolean -> addition +false + false // 0 + +// Number + String -> concatenation +5 + 'foo' // "5foo" + +// String + Boolean -> concatenation +'foo' + false // "foofalse" + +// String + String -> concatenation +'foo' + 'bar' // "foobar" +</pre> + +<h2 id="Trừ_(-)"><a name="Subtraction">Trừ (-)</a></h2> + +<p>Toán tử trừ thực hiện trừ hai toán hạng, xuất ra chênh lệch giữa chúng.</p> + +<h3 id="Cú_pháp_2">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> x - y +</pre> + +<h3 id="Ví_dụ">Ví dụ</h3> + +<pre class="brush: js">5 - 3 // 2 +3 - 5 // -2 +'foo' - 3 // NaN</pre> + +<h2 id="Chia_()"><a name="Division">Chia (/)</a></h2> + +<p>Toán tử chia xuất ra thương của phép chia với toán hạng bên trái là số bị chia và toán hạng bên phải là số chia.</p> + +<h3 id="Cú_pháp_3">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> x / y +</pre> + +<h3 id="Ví_dụ_2">Ví dụ</h3> + +<pre class="brush: js">1 / 2 // trả về 0.5 trong JavaScript +1 / 2 // trả về 0 trong Java +// (neither number is explicitly a floating point number) + +1.0 / 2.0 // ?trả về 0.5 trong cả JavaScript lẫn Java + +2.0 / 0 // ?trả về Infinity trong JavaScript +2.0 / 0.0 // cũng trả về Infinity +2.0 / -0.0 // trả về -Infinity trong JavaScript</pre> + +<h2 id="Nhân_(*)"><a name="Multiplication">Nhân (*)</a></h2> + +<p>Toán tử nhân xuất ra tích của các toán hạng.</p> + +<h3 id="Cú_pháp_4">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> x * y +</pre> + +<h3 id="Ví_dụ_3">Ví dụ</h3> + +<pre class="brush: js">2 * 2 // 4 +-2 * 2 // -4 +Infinity * 0 // NaN +Infinity * Infinity // Infinity +'foo' * 2 // NaN +</pre> + +<h2 id="Chia_lấy_dư_()"><a name="Remainder">Chia lấy dư (%)</a></h2> + +<p>Toán tử chia lấy dư trả về phần dư khi toán hạng thứ nhất chia cho toán hạng thứ hai. Dấu của kết quả luôn cùng dấu với số bị chia.</p> + +<h3 id="Cú_pháp_5">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> var1 % var2 +</pre> + +<h3 id="Ví_dụ_4">Ví dụ</h3> + +<pre class="brush: js">12 % 5 // 2 +-1 % 2 // -1 +1 % -2 // 1 +NaN % 2 // NaN +1 % 2 // 1 +2 % 3 // 2 +-4 % 2 // -0 +5.5 % 2 // 1.5 +</pre> + +<h2 id="Luỹ_thừa_(**)"><a name="Exponentiation">Luỹ thừa (**)</a></h2> + +<p>Toán tử luỹ thừa trả về kết quả là luỹ thừa bậc là toán hạng thứ hai của toán hạng thứ nhất, tức là, <code>var1</code><sup><code>var2</code></sup>, như đã khẳng định trước đó, với <code>var1</code> và <code>var2</code> là biến số. Toán tử luỹ thừa là dạng liên hợp phải. <code>a ** b ** c</code> bằng với <code>a ** (b ** c)</code>.</p> + +<h3 id="Cú_pháp_6">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> var1 ** var2 +</pre> + +<h3 id="Ghi_chú">Ghi chú</h3> + +<p>Trong hầu hết các ngôn ngữ như PHP và Python và một số khác mà có toán tử luỹ thừa (**), toán tử luỹ thừa được định nghĩa là có độ ưu tiên cao hơn toán tử một ngôi như là toán tử + một ngôi và toán tử - một ngôi, nhưng cũng có vài ngoại lệ. Chẳng hạn, trong Bash, toán tử ** được định nghĩa là có độ ưu tiên thấp hơn toán tử một ngôi. Trong JavaScript, hoàn toàn có thể viết một biểu thức luỹ thừa nhập nhằng, như là bạn không thể đặt toán tử một ngôi (<code>+/-/~/!/delete/void/typeof</code>) ngay trước cơ số.</p> + +<pre class="brush: js">-2 ** 2; +// 4 trong Bash, -4 trong các ngôn ngữ khác. +// Không hợp lệ trong JavaScript, vì toán tử không nhập nhằng. + + +-(2 ** 2); +// -4 trong JavaScript và ý định của tác giả không nhập nhằng. +</pre> + +<h3 id="Ví_dụ_5">Ví dụ</h3> + +<pre class="brush: js">2 ** 3 // 8 +3 ** 2 // 9 +3 ** 2.5 // 15.588457268119896 +10 ** -1 // 0.1 +NaN ** 2 // NaN + +2 ** 3 ** 2 // 512 +2 ** (3 ** 2) // 512 +(2 ** 3) ** 2 // 64 +</pre> + +<p>To invert the sign of the result of an exponentiation expression:</p> + +<pre class="brush: js">-(2 ** 2) // -4 +</pre> + +<p>Để ép cơ số trong biểu thức luỹ thừa thành số âm:</p> + +<pre class="brush: js">(-2) ** 2 // 4 +</pre> + +<div class="note"> +<p><strong>Ghi chú:</strong> JavaScript cũng có <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR"> toán tử thao tác bit ^ (XOR)</a>. <code>**</code> và <code>^</code> khác nhau (chẳng hạn: <code>2 ** 3 === 8</code> trong khi <code>2 ^ 3 === 1</code>.)</p> +</div> + +<p> </p> + +<h2 id="Tăng_()"><a name="Increment">Tăng (++)</a></h2> + +<p> </p> + +<p>Toán tử tăng tăng (thêm một vào) toán hạng của nó và trả về một giá trị.</p> + +<ul> + <li>Nếu dùng như hậu tố, toán tử ở sau toán hạng (chẳng hạn, x++), thí nó trả về giá trị trước khi tăng.</li> + <li>Nếu dùng như tiền tố, toán tử ở trước toán hạng (chẳng hạn, ++x), thí nó trả về giá trị sau khi tăng.</li> +</ul> + +<h3 id="Cú_pháp_7">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> x++ hoặc ++x +</pre> + +<h3 id="Ví_dụ_6">Ví dụ</h3> + +<pre class="brush: js">// Hậu tố +var x = 3; +y = x++; // y = 3, x = 4 + +// Tiền tố +var a = 2; +b = ++a; // a = 3, b = 3 +</pre> + +<h2 id="Giảm_(--)"><a name="Decrement">Giảm (--)</a></h2> + +<p>Toán tử giảm giảm (bớt một khỏi) toán hạng của nó và trả về một giá trị.</p> + +<ul> + <li>Nếu dùng như hậu tố (chẳng hạn, x--), thì nó trả về giá trị trước khi giảm.</li> + <li>Nếu dùng như tiền tố (chẳng hạn, --x), thì nó trả về giá trị sau khi giảm.</li> +</ul> + +<h3 id="Cú_pháp_8">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> x-- hoặc --x +</pre> + +<h3 id="Ví_dụ_7">Ví dụ</h3> + +<pre class="brush: js">// Hậu tố +var x = 3; +y = x--; // y = 3, x = 2 + +// Tiền tố +var a = 2; +b = --a; // a = 1, b = 1 +</pre> + +<h2 id="Phủ_định_một_ngôi_(-)"><a name="Unary_negation">Phủ định một ngôi (-)</a></h2> + +<p>Toán tử phủ định một ngôi đứng trước và phủ định toán hạng của nó.</p> + +<h3 id="Cú_pháp_9">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> -x +</pre> + +<h3 id="Ví_dụ_8">Ví dụ</h3> + +<pre class="brush: js">var x = 3; +y = -x; // y = -3, x = 3 + +//toán tử phủ định một ngôi có thể chuyển giá-trị-không-phải-kiểu-số về dạng số học +var x = "4"; +y = -x; // y = -4 +</pre> + +<h2 id="Cộng_một_ngôi_()"><a name="Unary_plus">Cộng một ngôi (+)</a></h2> + +<p>Toán tử cộng một ngôi đứng trước và định lượng toán hạng của nó nhưng cố gắng chuyển kiểu cho toán hạng sang dạng số, nếu ban đầu không phải ở dạng đó. Mặc dù toán tử phủ định một ngôi (-) cũng có thể chuyển kiểu như vậy, nhưng toán tử cộng một ngôi lại nhanh nhất và được dùng ưu tiên dùng nhiều hơn khi phải chuyển đổi kiểu dữ liệu về dạng số, bởi vì nó không thực hiện bất cứ phép toán nào khác trên số. Nó có thể chuyển kiểu từ biểu diễn dạng chuỗi của số nguyên hoặc số thực, thậm chí cả các giá trị không phải số như <code>true</code>, <code>false</code>, và <code>null</code>. Số thực ở dạng thập phân và bát phân (tiền tố - "0x") đều được hỗ trợ. Đồng thời hỗ trợ cả số âm (trừ số âm dạng bát phân). Nếu nó không thể truyền đúng dữ liệu đã định, nó sẽ định lượng thành <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a>.</p> + +<h3 id="Cú_pháp_10">Cú pháp</h3> + +<pre class="syntaxbox"><strong>Toán tử:</strong> +x +</pre> + +<h3 id="Ví_dụ_9">Ví dụ</h3> + +<pre class="brush: js">+3 // 3 ++'3' // 3 ++true // 1 ++false // 0 ++null // 0 ++function(val){ return val } // NaN +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.3')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Defined in several sections of the specification: <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.6">Additive operators</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.5">Multiplicative operators</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.3">Postfix expressions</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.4">Unary operators</a>.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-postfix-expressions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Defined in several sections of the specification: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-additive-operators">Additive operators</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-multiplicative-operators">Multiplicative operators</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-postfix-expressions">Postfix expressions</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-unary-operators">Unary operators</a>.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-postfix-expressions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td>Added <a href="https://github.com/rwaldron/exponentiation-operator">Exponentiation operator</a>.</td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-postfix-expressions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-additive-operators')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + + + +<p>{{Compat("javascript.operators.arithmetic")}}</p> + +<h2 id="Đọc_thêm">Đọc thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Toán tử gán</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/conditional_operator/index.html b/files/vi/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..62cc4cadb5 --- /dev/null +++ b/files/vi/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,119 @@ +--- +title: Conditional (ternary) operator +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Toán tử điều kiện (ba ngôi)</strong> là toán tử duy nhất của JavaScript cần tới ba toán hạng. Toán tử này thường dùng tắt cho câu lệnh <a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if</code></a>.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><em>condition</em> ? <em>exprT</em> : <em>exprF</em> </pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>condition</code></dt> + <dd>Biểu thức mà giá trị của nó được dùng như điều kiện.</dd> +</dl> + +<dl> + <dt><code>exprT</code>, <code>exprF</code></dt> + <dd>Biểu thức với giá trị có kiểu bất kỳ.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Nếu <code>condition</code> có thể chuyển đổi thành<code>true</code> (hay là {{Glossary("truthy")}}), toán tử trả về giá trị của <code>exprT</code>; ngược lại (khi <code>condition</code> là {{Glossary("falsy")}}), nó trả về giá trị của <code>exprF</code>.</p> + +<p>(Trong cả hai trường hợp, biểu thức còn lại đều không được duyệt tới.)</p> + +<p>Ngoài <code>false</code> ra, các biểu thức falsy có thể xảy ra bao gồm: <code>null</code>, <code><code>NaN</code></code>, <code><code><code>0</code></code></code>, xâu ký tự rỗng (<code><code><code><code>""</code></code></code></code>), và <code><code><code><code>undefined</code></code></code></code>. Nếu <code>condition</code> là một trong những gì vừa liệt kê phía trên, kết quả của biểu thức điều kiện sẽ là <code>exprF</code>.</p> + +<p>Ví dụ đơn giản:</p> + +<pre class="brush: js">var age = 26; +var beverage = (age >= 21) ? "Beer" : "Juice"; +console.log(beverage); // "Beer" +</pre> + +<p>Thường dùng để xử lý giá trị <code>null</code>:</p> + +<pre class="brush: js">function greeting(person) { + var name = person ? person.name : "stranger"; + return "Howdy, " + name; +} + +console.log(greeting({name: 'Alice'})); // "Howdy, Alice" +console.log(greeting(null)); // "Howdy, stranger" +</pre> + +<h3 id="Điều_kiện_nối_tiếp">Điều kiện nối tiếp</h3> + +<p>Toán tử điều kiện tuân theo suy dẫn phải, tức là nó có thể được gọi "nối tiếp" theo cách sau đây, tương tự như với <code>if … else if … else if … else</code> nối tiếp nhau:</p> + +<pre class="brush: js">function example(…) { + return condition1 ? value1 + : condition2 ? value2 + : condition3 ? value3 + : value4; +} + +// Equivalent to: + +function example(…) { + if (condition1) { return value1; } + else if (condition2) { return value2; } + else if (condition3) { return value3; } + else { return value4; } +} +</pre> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Bình luận</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu. Cài đặt trong JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> + + + +<p>{{Compat("javascript.operators.conditional")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">Lệnh if</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/delete/index.html b/files/vi/web/javascript/reference/operators/delete/index.html new file mode 100644 index 0000000000..46a837d094 --- /dev/null +++ b/files/vi/web/javascript/reference/operators/delete/index.html @@ -0,0 +1,292 @@ +--- +title: delete operator +slug: Web/JavaScript/Reference/Operators/delete +translation_of: Web/JavaScript/Reference/Operators/delete +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary"><strong>Toán tử <code>delete</code></strong> của JavaScript loại bỏ một thuộc tính khỏi object; nếu không tồn tại tham chiếu tới thuộc tính, nó sẽ tự động giải phóng.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">delete <em>expression</em> </pre> + +<p>với <em>expression</em> thực thi thành tham chiếu đến <a href="/en-US/docs/Glossary/property/JavaScript">thuộc tính</a> nào đó, tức là:</p> + +<pre class="syntaxbox">delete <em>object.property</em> +delete <em>object</em>['<em>property</em>'] +</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>object</code></dt> + <dd>Tên object, hoặc biểu thức thực thi tới object.</dd> + <dt><code>property</code></dt> + <dd>Thuộc tính muốn xoá.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p><code>true</code> cho mọi trường hợp trừ khi thuộc tính là <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty">own</a> <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete">non-configurable</a>, trong trường hợp đó, trả về <code>false</code> trong chế độ non-strict.</p> + +<h3 id="Ngoại_lệ">Ngoại lệ</h3> + +<p>Quăng {{jsxref("TypeError")}} trong <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode"> chế độ strict</a> nếu thuộc tính là own non-configurable.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Khác với suy nghĩ của nhiều người, toán tử <code>delete</code> <strong>không</strong> trực tiếp giải phóng bộ nhớ. Quản lý bộ nhớ được thực hiện trung gian qua việc bẻ tham chiếu. Xem trang <a href="/en-US/docs/Web/JavaScript/Memory_Management">quản lý bộ nhớ</a> để biết thêm chi tiết.</p> + +<p>Toán tử <code><strong>delete</strong></code> loại bỏ thuộc tính xác định trong object. Nếu xoá thành công, nó sẽ trả về <code>true</code>, ngoài ra thì <code>false</code>. Tuy nhiên, hãy lưu ý những kịch bản có thể xảy đến sau đây:</p> + +<ul> + <li>Nếu thuộc tính muốn xoá không tồn tại, <code>delete</code> sẽ không có tác dụng và sẽ trả về <code>true</code></li> + <li>Nếu tồn tại thuộc tính có cùng tên trong prototype nối với object, thì sau khi xoá xong, object sẽ dùng thuộc tính từ prototype đó (nói cách khác, <code>delete</code> chỉ có tác dụng với những thuộc tính của riêng object).</li> + <li>Bất cứ thuộc tính nào được khởi tạo bằng {{jsxref("Statements/var","var")}} không thể bị xoá khỏi phạm vi toàn cục hoặc phạm vi hàm. + <ul> + <li>Vì thế, <code>delete</code> không thể xoá bất cứ hàm nào trong phạm vi toàn cục (cho dù là một phần của định nghĩa hàm hay biểu thức hàm).</li> + <li>Các hàm là một phần của object (tách biệt với phạm vi toàn cục) có thể bị xoá với <code>delete</code>.</li> + </ul> + </li> + <li>Bất cứ thuộc tính nào được khởi tạo bởi {{jsxref("Statements/let","let")}} hoặc {{jsxref("Statements/const","const")}} không thể bị xoá khỏi phạm vi mà chúng được khai báo.</li> + <li>Thuộc tính không-thể-cấu-hình không thể bị loại bỏ. Các thuộc tính này bao gồm các object dựng sẵn như {{jsxref("Math")}}, {{jsxref("Array")}}, {{jsxref("Object")}} và thuộc tính được tạo ra như thuộc tính không-thể-cấu-hình bằng phương thức như là {{jsxref("Object.defineProperty()")}}.</li> +</ul> + +<p>Snippet sau đưa ra ví dụ đơn giản:</p> + +<pre class="brush: js">var Employee = { + age: 28, + name: 'abc', + designation: 'developer' +} + +console.log(delete Employee.name); // trả về true +console.log(delete Employee.age); // trả về true + +// Khi cố xoá một thuộc tính không tồn tại +// sẽ trả về giá trị true +console.log(delete Employee.salary); // trả về true +</pre> + +<h3 id="Thuộc_tính_không-thể-cấu-hình"><strong>Thuộc tính không-thể-cấu-hình</strong></h3> + +<p>Khi một thuộc tính được đánh dấu không-thể-cấu-hình, <code>delete</code> không có tác dụng nào, và sẽ trả về <code>false</code>. Trong chế độ strict, lỗi <code>TypeError</code> sẽ nhảy ra.</p> + +<pre class="brush: js">var Employee = {}; +Object.defineProperty(Employee, 'name', {configurable: false}); + +console.log(delete Employee.name); // trả về false +</pre> + +<p>{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}} và {{jsxref("Statements/const","const")}} tạo ra thuộc tính không-thể-cấu-hình mà không thể xoá bằng toán tử <code>delete</code>:</p> + +<pre class="brush: js">var nameOther = 'XYZ'; + +// Ta có thể truy cập vào thuộc tính toàn cục này thông qua: +Object.getOwnPropertyDescriptor(window, 'nameOther'); + +// output: Object {value: "XYZ", +// writable: true, +// enumerable: true, +// <strong>configurable: false</strong>} + +// Bởi vì "nameOther" được thêm vào nhờ dùng +// từ khoá var, nên nó được đánh dấu là "không-thể-cấu-hình" + +delete nameOther; // trả về false</pre> + +<p>Trong chế độ strict, ngoại lệ sẽ quăng ra.</p> + +<h3 id="Chế_độ_strict_và_non-strict"><strong>Chế độ strict và non-strict</strong></h3> + +<p>Khi ở trong chế độ strict, nếu <code>delete</code> được dùng để tham chiếu trực tiếp tới một biến, một đối số của hàm hoặc tên hàm, nó sẽ quăng ra {{jsxref("SyntaxError")}}<strong>.</strong></p> + +<p>Bất cứ biến nào được định nghĩa với <code>var</code> đều được đánh dấu là không-thể-cấu-hình. Trong ví dụ sau đây, <code>salary</code> là không-thể-cấu-hình và không thể xoá. Trong chế độ non-strict, phép toán <code>delete</code> sẽ trả về <code>false</code>.</p> + +<pre class="brush: js">function Employee() { + delete salary; + var salary; +} + +Employee(); +</pre> + +<p>Cùng xem mã nguồn tương tự hoạt động ra sao trong chế độ strict nhé. Thay vì trả về <code>false</code>, <code>SyntaxError</code> được quăng ra.</p> + +<pre class="brush: js">"use strict"; + +function Employee() { + delete salary; // SyntaxError + var salary; +} + +// Tương tự, bất cứ truy nhập trực tiếp nào vào hàm +// dùng delete đều quăng ra SyntaxError + +function DemoFunction() { + //vài đoạn code +} + +delete DemoFunction; // SyntaxError +</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<pre class="brush: js">// Tạo thuộc tính adminName trên phạm vi toàn cục. +adminName = 'xyz'; + +// Tạo thuộc tính empCount trên phạm vi toàn cục =. +// Vì dùng var, thuộc tính này được đánh dấu là không-thể-cấu-hình. +// Điều tương tự xảy đến với let và const. +var empCount = 43; + +EmployeeDetails = { + name: 'xyz', + age: 5, + designation: 'Developer' +}; + +// adminName là thuộc tính trên phạm vi toàn cục. +// Nó có thể bị xoá bởi được khởi tạo mà không dùng var, +// và vì thế khả cấu. +delete adminName; // trả về true + +// Ngược lại, empCount không khả cấu +// bởi dùng var. +delete empCount; // trả về false + +// Có thể dùng delete để loại bỏ thuộc tính khỏi object. +delete EmployeeDetails.name; // trả về true + +<strong>// </strong>Thậm chí thuộc tính không tồn tại, delete vẫn trả về "true". +delete EmployeeDetails.salary; // trả về true + +// delete không có tác dụng với thuộc tính dựng sẵn. +delete Math.PI; // trả về false + +// EmployeeDetails là thuộc tính trong phạm vi toàn cục. +// Vì được khởi tạo mà không dùng "var", nó được đánh dấu là khả cấu. +delete EmployeeDetails; // trả về true + +function f() { + var z = 44; + + // delete không có tác dụng với tên biến cục bộ + delete z; // trả về false +} +</pre> + +<h3 id="delete_và_prototype_chain"><code>delete</code> và prototype chain</h3> + +<p>Trong ví dụ sau, ta sẽ xoá một thuộc tính riêng của object mà vẫn tồn tại thuộc tính cùng tên trong prototype chain:</p> + +<pre class="brush: js">function Foo() { + this.bar = 10; +} + +Foo.prototype.bar = 42; + +var foo = new Foo(); + +// foo.bar liên kết với +// thuộc tính riêng. +console.log(foo.bar); // 10 + +// Xoá thuộc tính riêng trên +// foo object. +delete foo.bar; // trả về true + +// foo.bar vẫn sẵn sàng trên +// prototype chain. +console.log(foo.bar); // 42 + +// Xoá thuộc tính trên prototype. +delete Foo.prototype.bar; // trả về true + +// Thuộc tính "bar" không còn có thể +// kể thừa từ Foo bởi nó đã bị xoá +console.log(foo.bar); // undefined</pre> + +<h3 id="Xoá_phần_tử_mảng"><strong>Xoá phần tử mảng</strong></h3> + +<p>Khi bạn xoá phần tử mảng, độ dài mảng không bị ảnh hưởng. Thậm chí khi bạn xoá phần tử cuối của mảng cũng không thay đổi được điều này.</p> + +<p>Khi toán tử <code>delete</code> loại bỏ một phần tử mảng, phần tử đó không còn trong mảng. Trong ví dụ sau, <code>trees[3]</code> bị xoá bởi <code>delete</code>.</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +delete trees[3]; +if (3 in trees) { + // không thực thi đoạn code này +}</pre> + +<p>Nếu bạn muốn giữ lại phần tử mảng và gán giá trị undefined cho nó, hãy dùng <code>undefined</code> thay vì toán tử <code>delete</code>. Trong ví dụ sau, <code>trees[3]</code> được gán giá trị undefined, nhưng phần tử mảng vẫn tồn tại:</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +trees[3] = undefined; +if (3 in trees) { + // đoạn code trong này sẽ chạy +}</pre> + +<p>Thay vì thế, nếu muốn loại bỏ phần tử mảng bằng cách thay đổi nội dung của mảng, hãy dùng phương thức <code>{{jsxref("Array.splice", "splice")}}</code>. Trong ví dụ sau, <code>trees[3]</code> bị xoá bỏ hoàn toàn khỏi mảng thông qua <code>{{jsxref("Array.splice", "splice")}}</code>:</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +trees.splice(3,1); +console.log(trees); // ["redwood", "bay", "cedar", "maple"] +</pre> + +<h2 id="Đặc_Đặc_tả">Đặc Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-delete-operator', 'The delete Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-delete-operator', 'The delete Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.1', 'The delete Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.1', 'The delete Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Định nghĩa lần đầu. Cài đặt trong JavaScript 1.2.</td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + + + +<p>{{Compat("javascript.operators.delete")}}</p> + +<h2 id="Ghi_chú_Cross-browser">Ghi chú Cross-browser</h2> + +<p>Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses <code>delete</code> on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property <em>value</em> is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its <em>old</em> position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.</p> + +<p>If you want to use an ordered associative array in a cross-browser environment, use a {{jsxref("Map")}} object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="http://perfectionkills.com/understanding-delete/">Phân tích sâu về delete</a></li> + <li>{{jsxref("Reflect.deleteProperty()")}}</li> + <li>{{jsxref("Map.prototype.delete()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/function/index.html b/files/vi/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..1e302774be --- /dev/null +++ b/files/vi/web/javascript/reference/operators/function/index.html @@ -0,0 +1,175 @@ +--- +title: function expression +slug: Web/JavaScript/Reference/Operators/function +translation_of: Web/JavaScript/Reference/Operators/function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Từ khóa <strong><code>function </code></strong><code>(hàm)</code> có thể dùng để định nghĩa chức năng bên trong một biểu thức.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">var myFunction = function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) { + <em>statements</em> +};</pre> + +<h3 id="Tham_số">Tham số</h3> + +<dl> + <dt><code>name</code></dt> + <dd>Tên hàm. Có thể bỏ qua, trong trường hợp chức năng đó là <code>vô danh. </code>Nó mô tả chính xác nhiệm vụ mà <strong>hàm </strong>sẽ làm.</dd> + <dt><code>paramN</code></dt> + <dd>Tên các đối số truyền vào.</dd> + <dt><code>statements</code></dt> + <dd>Các câu lệnh xử lý các đối số <strong><code>paramN </code></strong>truyền vào.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Một biểu thức chức năng (<code>function</code>) is very similar to and has almost the same syntax as a function statement (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details). The main difference between a function expression and a function statement is the <em>function name,</em> which can be omitted in function expressions to create <em>anonymous</em> functions. A function expression can be used as a <strong>IIFE </strong>(Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about <a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a> for more information.</p> + +<h3 id="Function_expression_hoisting">Function expression hoisting</h3> + +<p>Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:</p> + +<pre class="brush: js">notHoisted(); // TypeError: notHoisted is not a function + +var notHoisted = function() { + console.log('bar'); +}; +</pre> + +<h2 id="Examples">Examples</h2> + +<p>The following example defines an unnamed function and assigns it to <code>x</code>. The function returns the square of its argument:</p> + +<pre class="brush: js">var x = function(y) { + return y * y; +}; +</pre> + +<h3 id="Named_function_expression">Named function expression</h3> + +<p>If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code> property.</p> + +<pre class="brush: js">var math = { + 'factorial': function factorial(n) { + if (n <= 1) + return 1; + return n * factorial(n - 1); + } +}; +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Trailing comma in parameters</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("52.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Trailing comma in parameters</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("52.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/index.html b/files/vi/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..139208dbca --- /dev/null +++ b/files/vi/web/javascript/reference/operators/index.html @@ -0,0 +1,298 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - TopicStub +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>This chapter documents all the JavaScript language operators, expressions and keywords.</p> + +<h2 id="Expressions_and_operators_by_category">Expressions and operators by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Primary_expressions">Primary expressions</h3> + +<p>Basic keywords and general expressions in JavaScript.</p> + +<dl> + <dt>{{jsxref("Operators/this", "this")}}</dt> + <dd>The <code>this</code> keyword refers to the function's execution context.</dd> + <dt>{{jsxref("Operators/function", "function")}}</dt> + <dd>The <code>function</code> keyword defines a function expression.</dd> + <dt>{{jsxref("Operators/class", "class")}}</dt> + <dd>The <code>class</code> keyword defines a class expression.</dd> + <dt>{{jsxref("Operators/function*", "function*")}}</dt> + <dd>The <code>function*</code> keyword defines a generator function expression.</dd> + <dt>{{jsxref("Operators/yield", "yield")}}</dt> + <dd>Pause and resume a generator function.</dd> + <dt>{{jsxref("Operators/yield*", "yield*")}}</dt> + <dd>Delegate to another generator function or iterable object.</dd> + <dt>{{jsxref("Global_Objects/Array", "[]")}}</dt> + <dd>Array initializer/literal syntax.</dd> + <dt>{{jsxref("Operators/Object_initializer", "{}")}}</dt> + <dd>Object initializer/literal syntax.</dd> + <dt>{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>Regular expression literal syntax.</dd> + <dt>{{jsxref("Operators/Grouping", "( )")}}</dt> + <dd>Grouping operator.</dd> +</dl> + +<h3 id="Left-hand-side_expressions">Left-hand-side expressions</h3> + +<p>Left values are the destination of an assignment.</p> + +<dl> + <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>Member operators provide access to a property or method of an object<br> + (<code>object.property</code> and <code>object["property"]</code>).</dd> + <dt>{{jsxref("Operators/new", "new")}}</dt> + <dd>The <code>new</code> operator creates an instance of a constructor.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></dt> + <dd>In constructors, <code>new.target</code> refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.</dd> + <dt>{{jsxref("Operators/super", "super")}}</dt> + <dd>The <code>super</code> keyword calls the parent constructor.</dd> + <dt>{{jsxref("Operators/Spread_operator", "...obj")}}</dt> + <dd>The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.</dd> +</dl> + +<h3 id="Increment_and_decrement">Increment and decrement</h3> + +<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> + <dd>Postfix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> + <dd>Postfix decrement operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> + <dd>Prefix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> + <dd>Prefix decrement operator.</dd> +</dl> + +<h3 id="Unary_operators">Unary operators</h3> + +<p>A unary operation is operation with only one operand.</p> + +<dl> + <dt>{{jsxref("Operators/delete", "delete")}}</dt> + <dd>The <code>delete</code> operator deletes a property from an object.</dd> + <dt>{{jsxref("Operators/void", "void")}}</dt> + <dd>The <code>void</code> operator discards an expression's return value.</dd> + <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> + <dd>The <code>typeof</code> operator determines the type of a given object.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> + <dd>The unary plus operator converts its operand to Number type.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> + <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> + <dd>Bitwise NOT operator.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> + <dd>Logical NOT operator.</dd> +</dl> + +<h3 id="Arithmetic_operators">Arithmetic operators</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> + <dd>Addition operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> + <dd>Subtraction operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> + <dd>Division operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> + <dd>Multiplication operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> + <dd>Remainder operator.</dd> +</dl> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</dt> + <dd>Exponentiation operator.</dd> +</dl> + +<h3 id="Relational_operators">Relational operators</h3> + +<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/in", "in")}}</dt> + <dd>The <code>in</code> operator determines whether an object has a given property.</dd> + <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> + <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> + <dd>Less than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> + <dd>Greater than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> + <dd>Less than or equal operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> + <dd>Greater than or equal operator.</dd> +</dl> + +<div class="note"> +<p><strong>Note: =></strong> is not an operator, but the notation for <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a>.</p> +</div> + +<h3 id="Equality_operators">Equality operators</h3> + +<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> + <dd>Equality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> + <dd>Inequality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> + <dd>Identity operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> + <dd>Nonidentity operator.</dd> +</dl> + +<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> + +<p>Operations to shift all bits of the operand.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> + <dd>Bitwise left shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> + <dd>Bitwise right shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> + <dd>Bitwise unsigned right shift operator.</dd> +</dl> + +<h3 id="Binary_bitwise_operators">Binary bitwise operators</h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> + <dd>Bitwise AND.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> + <dd>Bitwise OR.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> + <dd>Bitwise XOR.</dd> +</dl> + +<h3 id="Binary_logical_operators">Binary logical operators</h3> + +<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> + +<dl> + <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> + <dd>Logical AND.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> + <dd>Logical OR.</dd> +</dl> + +<h3 id="Conditional_(ternary)_operator">Conditional (ternary) operator</h3> + +<dl> + <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>The conditional operator returns one of two values based on the logical value of the condition.</p> + </dd> +</dl> + +<h3 id="Assignment_operators">Assignment operators</h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> + +<dl> + <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> + <dd>Assignment operator.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> + <dd>Multiplication assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> + <dd>Division assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> + <dd>Remainder assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> + <dd>Addition assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> + <dd>Subtraction assignment</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> + <dd>Left shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> + <dd>Right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> + <dd>Unsigned right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> + <dd>Bitwise AND assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> + <dd>Bitwise XOR assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> + <dd>Bitwise OR assignment.</dd> + <dt>{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.</p> + </dd> +</dl> + +<h3 id="Comma_operator">Comma operator</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> +</dl> + +<h3 id="Non-standard_features">Non-standard features</h3> + +<dl> + <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> + <dd>The <code>function</code> keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> + <dd>The expression closure syntax is a shorthand for writing simple function.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> + <dd>Array comprehensions.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> + <dd>Generator comprehensions.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Spread operator, destructuring assignment, <code>super</code> keyword.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">Operator precedence</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/operator_precedence/index.html b/files/vi/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..efa25029b2 --- /dev/null +++ b/files/vi/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,477 @@ +--- +title: Operator precedence +slug: Web/JavaScript/Reference/Operators/Operator_Precedence +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +<div><font><font>{{jsSidebar ("Toán tử")}}</font></font></div> + +<p><strong><font><font>Mức độ ưu tiên của toán tử</font></font></strong><font><font> xác định cách các toán tử được phân tích cú pháp liên quan đến nhau. </font><font>Các toán tử có mức độ ưu tiên cao hơn trở thành toán hạng của các toán tử có mức độ ưu tiên thấp hơn.</font></font></p> + +<div><font><font>{{EmbedInteractiveExample ("pages / js / expression-operatorprecedence.html")}}</font></font></div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Precedence_And_Associativity">Precedence And Associativity</h2> + +<p>Consider an expression describable by the representation below. Note that both OP<sub>1</sub> and OP<sub>2</sub> are fill-in-the-blanks for OPerators.</p> + +<pre class="syntaxbox notranslate">a OP<sub>1</sub> b OP<sub>2</sub> c</pre> + +<p>If <code>OP<sub>1</sub></code> and <code>OP<sub>2</sub></code> have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.</p> + +<pre class="brush: js notranslate">console.log(3 + 10 * 2); // logs 23 +console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous +console.log((3 + 10) * 2); // logs 26 because the parentheses change the order +</pre> + +<p>Left-associativity (left-to-right) means that it is processed as <code>(a OP<sub>1</sub> b) OP<sub>2</sub> c</code>, while right-associativity (right-to-left) means it is interpreted as <code>a OP<sub>1</sub> (b OP<sub>2</sub> c)</code>. Assignment operators are right-associative, so you can write:</p> + +<pre class="brush: js notranslate">a = b = 5; // same as writing a = (b = 5); +</pre> + +<p>with the expected result that <code>a</code> and <code>b</code> get the value 5. This is because the assignment operator returns the value that is assigned. First, <code>b</code> is set to 5. Then the <code>a</code> is also set to 5, the return value of <code>b = 5</code>, aka right operand of the assignment.</p> + +<p>As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td>Code</td> + <td>Output</td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the division operator (/) +console.log(echo("left", 6) / echo("right", 2)); +</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the right side +3 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the exponentiation operator (**) +console.log(echo("left", 2) ** echo("right", 3));</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the right side +8</pre> + </td> + </tr> + </tbody> +</table> + +<p>The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity doesn't affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td>Code</td> + <td>Output</td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the division operator (/) +console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3)); +</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +1 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the exponentiation operator (**) +console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2)); +</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +512 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the parentheses around the left and middle exponentiation +console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +64</pre> + </td> + </tr> + </tbody> +</table> + +<p>Looking at the code snippets above, <code>6 / 3 / 2</code> is the same as <code>(6 / 3) / 2</code> because division is left-associative. Exponentiation, on the other hand, is right-associative, so <code>2 ** 3 ** 2</code> is the same as <code>2 ** (3 ** 2)</code>. Thus, doing <code>(2 ** 3) ** 2</code> changes the order and results in the 64 seen in the table above.</p> + +<p>Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, <code>2 ** 3 / 3 ** 2</code> results in 0.8888888888888888 because it is the same as <code>(2 ** 3) / (3 ** 2)</code>.</p> + +<h3 id="Note_on_grouping_and_short-circuiting">Note on grouping and short-circuiting</h3> + +<p>In the table below, <strong>Grouping</strong> is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols <code>( … )</code> is evaluated first, especially when it comes to short-circuiting.</p> + +<p>Short-circuiting is jargon for conditional evaluation. For example, in the expression <code>a && (b + c)</code>, if <code>a</code> is {{Glossary("falsy")}}, then the sub-expression <code>(b + c)</code> will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator ("OR") is "short-circuited". Along with logical disjunction, other short-circuited operators include logical conjunction ("AND"), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.</p> + +<pre class="brush: js notranslate">a || (b * c); // evaluate `a` first, then produce `a` if `a` is "truthy" +a && (b < c); // evaluate `a` first, then produce `a` if `a` is "falsy" +a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined` +a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined` +</pre> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js notranslate">3 > 2 && 2 > 1 +// returns true + +3 > 2 > 1 +// Returns false because 3 > 2 is true, then true is converted to 1 +// in inequality operators, therefore true > 1 becomes 1 > 1, which +// is false. Adding parentheses makes things clear: (3 > 2) > 1. +</pre> + +<h2 id="Table">Table</h2> + +<p>The following table is ordered from highest (21) to lowest (1) precedence.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Precedence</th> + <th>Operator type</th> + <th>Associativity</th> + <th>Individual operators</th> + </tr> + <tr> + <td>21</td> + <td>{{jsxref("Operators/Grouping", "Grouping", "", 1)}}</td> + <td>n/a</td> + <td><code>( … )</code></td> + </tr> + <tr> + <td colspan="1" rowspan="5">20</td> + <td>{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation", 1)}}</td> + <td>left-to-right</td> + <td><code>… . …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation", 1)}}</td> + <td>left-to-right</td> + <td><code>… [ … ]</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/new","new")}} (with argument list)</td> + <td>n/a</td> + <td><code>new … ( … )</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Function Call</a></td> + <td>left-to-right</td> + <td><code>… ( <var>… </var>)</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">Optional chaining</a></td> + <td>left-to-right</td> + <td><code>?.</code></td> + </tr> + <tr> + <td rowspan="1">19</td> + <td>{{jsxref("Operators/new","new")}} (without argument list)</td> + <td>right-to-left</td> + <td><code>new …</code></td> + </tr> + <tr> + <td rowspan="2">18</td> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment", 1)}}</td> + <td colspan="1" rowspan="2">n/a</td> + <td><code>… ++</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement", 1)}}</td> + <td><code>… --</code></td> + </tr> + <tr> + <td colspan="1" rowspan="10">17</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">Logical NOT</a></td> + <td colspan="1" rowspan="10">right-to-left</td> + <td><code>! …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">Bitwise NOT</a></td> + <td><code>~ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">Unary Plus</a></td> + <td><code>+ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">Unary Negation</a></td> + <td><code>- …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">Prefix Increment</a></td> + <td><code>++ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">Prefix Decrement</a></td> + <td><code>-- …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/typeof", "typeof")}}</td> + <td><code>typeof …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/void", "void")}}</td> + <td><code>void …</code></td> + </tr> + <tr> + <td><font><font>{{jsxref ("Toán tử / xóa", "xóa")}}</font></font></td> + <td><code>delete …</code></td> + </tr> + <tr> + <td><font><font>{{jsxref ("Toán tử / await", "await")}}</font></font></td> + <td><code>await …</code></td> + </tr> + <tr> + <td><font><font>16</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation"><font><font>Luỹ thừa</font></font></a></td> + <td><font><font>phải sang trái</font></font></td> + <td><code>… ** …</code></td> + </tr> + <tr> + <td rowspan="3"><font><font>15</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Multiplication"><font><font>Phép nhân</font></font></a></td> + <td colspan="1" rowspan="3"><font><font>trái sang phải</font></font></td> + <td><code>… * …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Division"><font><font>Sư đoàn</font></font></a></td> + <td><code>… / …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder"><font><font>Phần còn lại</font></font></a></td> + <td><code>… % …</code></td> + </tr> + <tr> + <td rowspan="2"><font><font>14</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition"><font><font>Thêm vào</font></font></a></td> + <td colspan="1" rowspan="2"><font><font>trái sang phải</font></font></td> + <td><code>… + …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Subtraction"><font><font>Phép trừ</font></font></a></td> + <td><code>… - …</code></td> + </tr> + <tr> + <td rowspan="3"><font><font>13</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators"><font><font>Dịch chuyển sang trái theo chiều bit</font></font></a></td> + <td colspan="1" rowspan="3"><font><font>trái sang phải</font></font></td> + <td><code>… << …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators"><font><font>Chuyển sang phải theo chiều bit</font></font></a></td> + <td><code>… >> …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators"><font><font>Chuyển sang phải không dấu bit</font></font></a></td> + <td><code>… >>> …</code></td> + </tr> + <tr> + <td rowspan="6"><font><font>12</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator"><font><font>Ít hơn</font></font></a></td> + <td colspan="1" rowspan="6"><font><font>trái sang phải</font></font></td> + <td><code>… < …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator"><font><font>Nhỏ hơn hoặc bằng</font></font></a></td> + <td><code>… <= …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator"><font><font>Lớn hơn</font></font></a></td> + <td><code>… > …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator"><font><font>Lớn hơn hoặc bằng</font></font></a></td> + <td><code>… >= …</code></td> + </tr> + <tr> + <td><font><font>{{jsxref ("Toán tử / trong", "trong")}}</font></font></td> + <td><code>… in …</code></td> + </tr> + <tr> + <td><font><font>{{jsxref ("Toán tử / instanceof", "instanceof")}}</font></font></td> + <td><code>… instanceof …</code></td> + </tr> + <tr> + <td rowspan="4"><font><font>11</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality"><font><font>Bình đẳng</font></font></a></td> + <td colspan="1" rowspan="4"><font><font>trái sang phải</font></font></td> + <td><code>… == …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality"><font><font>Bất bình đẳng</font></font></a></td> + <td><code>… != …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity"><font><font>Bình đẳng nghiêm ngặt</font></font></a></td> + <td><code>… === …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity"><font><font>Bất bình đẳng nghiêm ngặt</font></font></a></td> + <td><code>… !== …</code></td> + </tr> + <tr> + <td><font><font>10</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND"><font><font>Bitwise VÀ</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… & …</code></td> + </tr> + <tr> + <td><font><font>9</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR"><font><font>Bitwise XOR</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… ^ …</code></td> + </tr> + <tr> + <td><font><font>số 8</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR"><font><font>Bitwise HOẶC</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… | …</code></td> + </tr> + <tr> + <td><font><font>7</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND"><font><font>Logic AND</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… && …</code></td> + </tr> + <tr> + <td><font><font>6</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR"><font><font>Logic HOẶC</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… || …</code></td> + </tr> + <tr> + <td><font><font>5</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator"><font><font>Nhà điều hành liên kết Nullish</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… ?? …</code></td> + </tr> + <tr> + <td><font><font>4</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator"><font><font>Có điều kiện</font></font></a></td> + <td><font><font>phải sang trái</font></font></td> + <td><code>… ? … : …</code></td> + </tr> + <tr> + <td rowspan="16"><font><font>3</font></font></td> + <td rowspan="16"><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators"><font><font>Chuyển nhượng</font></font></a></td> + <td rowspan="16"><font><font>phải sang trái</font></font></td> + <td><code>… = …</code></td> + </tr> + <tr> + <td><code>… += …</code></td> + </tr> + <tr> + <td><code>… -= …</code></td> + </tr> + <tr> + <td><code>… **= …</code></td> + </tr> + <tr> + <td><code>… *= …</code></td> + </tr> + <tr> + <td><code>… /= …</code></td> + </tr> + <tr> + <td><code>… %= …</code></td> + </tr> + <tr> + <td><code>… <<= …</code></td> + </tr> + <tr> + <td><code>… >>= …</code></td> + </tr> + <tr> + <td><code>… >>>= …</code></td> + </tr> + <tr> + <td><code>… &= …</code></td> + </tr> + <tr> + <td><code>… ^= …</code></td> + </tr> + <tr> + <td><code>… |= …</code></td> + </tr> + <tr> + <td><code>… &&= …</code></td> + </tr> + <tr> + <td><code>… ||= …</code></td> + </tr> + <tr> + <td><code>… ??= …</code></td> + </tr> + <tr> + <td rowspan="2"><font><font>2</font></font></td> + <td><font><font>{{jsxref ("Toán tử / lợi nhuận", "lợi nhuận")}}</font></font></td> + <td colspan="1" rowspan="2"><font><font>phải sang trái</font></font></td> + <td><code>yield …</code></td> + </tr> + <tr> + <td><font><font>{{jsxref ("Toán tử / lợi nhuận *", "lợi nhuận *")}}</font></font></td> + <td><code>yield* …</code></td> + </tr> + <tr> + <td><font><font>1</font></font></td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator"><font><font>Dấu phẩy / Chuỗi</font></font></a></td> + <td><font><font>trái sang phải</font></font></td> + <td><code>… , …</code></td> + </tr> + </tbody> +</table> diff --git a/files/vi/web/javascript/reference/operators/super/index.html b/files/vi/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..4e5a092475 --- /dev/null +++ b/files/vi/web/javascript/reference/operators/super/index.html @@ -0,0 +1,226 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operators/super +translation_of: Web/JavaScript/Reference/Operators/super +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Từ khóa <strong>super </strong>được sử dụng để gọi các hàm trên đối tượng cha.</p> + +<p>Các biểu thức super.prop và super[expr] là hợp lệ trong mọi <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">định nghĩa phương thức</a> ở cả <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classes</a> và <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object literals</a>.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">super([arguments]); // gọi hàm khởi tạo cha. +super.functionOnParent([arguments]); +</pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Khi được sử dụng trong một hàm khởi tạo, từ khóa super xuất hiện một mình và phải được sử dụng trước khi từ khóa this có thể sử dụng. Từ khóa này cũng có thể được sử dụng để gọi các hàm trên đối tượng cha.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_super_trong_classes">Sử dụng super trong classes</h3> + +<p>Đoạn code này lấy từ <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">ví dụ về class</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>). <code>super()</code> ở đây được gọi để tránh việc lặp lại các phần giống nhau của <code>Rectangle</code> và <code>Square</code>.</p> + +<pre class="brush: js">class Polygon { + constructor(height, width) { + this.name = 'Polygon'; + this.height = height; + this.width = width; + } + sayName() { + console.log('Hi, I am a ', this.name + '.'); + } +} + +class Square extends Polygon { + constructor(length) { + this.height; // ReferenceError, super needs to be called first! + + // Here, it calls the parent class' constructor with lengths + // provided for the Polygon's width and height + super(length, length); + + // Note: In derived classes, super() must be called before you + // can use 'this'. Leaving this out will cause a reference error. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="Gọi_super_trên_các_phương_thức_tĩnh">Gọi super trên các phương thức tĩnh</h3> + +<p>Bạn cũng có thể gọi <code>super()</code> trên các phương thức <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static">tĩnh</a>.</p> + +<pre class="brush: js">class Human { + constructor() {} + static ping() { + return 'ping'; + } +} + +class Computer extends Human { + constructor() {} + static pingpong() { + return super.ping() + ' pong'; + } +} +Computer.pingpong(); // 'ping pong' +</pre> + +<h3 id="Xóa_các_thuộc_tính_của_super_sẽ_gây_ra_lỗi">Xóa các thuộc tính của super sẽ gây ra lỗi</h3> + +<p>Bạn không thể sử dụng <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">thao tác delete</a> và <code>super.prop</code> hoặc <code>super[expr]</code> để xóa một thuộc tính của lớp cha, nó sẽ ném lỗi {{jsxref("ReferenceError")}}.</p> + +<pre class="brush: js">class Base { + constructor() {} + foo() {} +} +class Derived extends Base { + constructor() {} + delete() { + delete super.foo; + } +} + +new Derived().delete(); // ReferenceError: invalid delete involving 'super'. </pre> + +<h3 id="Super.prop_không_thể_ghi_đè_các_thuộc_tính_non-writable">Super.prop không thể ghi đè các thuộc tính non-writable</h3> + +<p>Khi định nghĩa các thuộc tính non-writable ví dụ {{jsxref("Object.defineProperty")}}, <code>super</code> không thể ghi đè giá trị của thuộc tính này.</p> + +<pre class="brush: js">class X { + constructor() { + Object.defineProperty(this, "prop", { + configurable: true, + writable: false, + value: 1 + }); + } + f() { + super.prop = 2; + } +} + +var x = new X(); +x.f(); +console.log(x.prop); // 1 +</pre> + +<h3 id="Sử_dụng_super.prop_trong_object_literals">Sử dụng super.prop trong object literals</h3> + +<p>Super cũng có thể được sử dụng trong <a href="/en-US/docs/">khởi tạo đối tượng hoặc literal</a>. Trong ví dụ này, 2 đối tượng định nghĩa một phương thức. Trong đối tượng thứ hai, <code>super</code> gọi phương thức của đối tượng thứ nhất. Điều này làm được với sự trợ giúp của {{jsxref("Object.setPrototypeOf()")}} cái giúp chúng ta có thể thiết lập prototype của <code>obj2</code> thành <code>obj1</code>, vì thế <code>super</code> có thể tìm <code>method1</code> trên <code>obj1</code>.</p> + +<pre class="brush: js">var obj1 = { + method1() { + console.log("method 1"); + } +} + +var obj2 = { + method2() { + super.method1(); + } +} + +Object.setPrototypeOf(obj2, obj1); +obj2.method2(); // logs "method 1" +</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-super-keyword', 'super')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Khả_năng_tương_thích_của_các_trình_duyệt">Khả năng tương thích của các trình duyệt</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(45)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoMobile(45)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Lưu_ý_cho_Gecko">Lưu ý cho Gecko</h2> + +<ul> + <li>super() chưa làm việc như mong đợi cho việc xây dựng trong các nguyên mẫu</li> +</ul> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/this/index.html b/files/vi/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..d3112507cb --- /dev/null +++ b/files/vi/web/javascript/reference/operators/this/index.html @@ -0,0 +1,382 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Từ khoá<strong> <code>this</code> </strong>của hàm trong JavaScript hơi khác so với các ngôn ngữ khác. Nó cũng có một vài điểm khác nhau giữa 2 chế độ <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">strict mode</a> và non-strict mode.</p> + +<p>Trong hầu hết các trường hợp, giá trị của <code>this</code> được xác định bởi cách gọi hàm (runtime binding). Nó không thể được thiết lập bằng cách gán trong khi thực thi, và nó có thể khác nhau mỗi lần hàm được gọi. ES5 giới thiệu phương thức {{jsxref("Function.prototype.bind()", "bind()")}} để <a href="#">thiết lập giá trị của <code>this</code> bất kể hàm được gọi thế nào</a>, và ES2015 giới thiệu <a href="../Functions/Arrow_functions">arrow functions</a> mà không cung cấp ràng buộc với <code>this</code> của chúng (Nó sẽ giữ giá trị <code>this</code> của lexical context kèm theo).</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-this.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">this</pre> + +<h3 id="Giá_trị">Giá trị</h3> + +<p>Một thuộc tính của bối cảnh thực thi (global, function or eval), trong non–strict mode, luôn luôn tham chiếu tới một đối tượng và trong strict mode có thể là bất kỳ giá trị nào.</p> + +<h2 id="Global_context">Global context</h2> + +<p>Trong global context (bên ngoài các hàm), <code>this</code> tham chiếu tới global object cho dù trong strict mode hoặc không.</p> + +<pre class="brush:js">// Trong trình duyệt, đối tượng window ?là global object: +console.log(this === window); // true + +a = 37; +console.log(window.a); // 37 + +this.b = "MDN"; +console.log(window.b) // "MDN" +console.log(b) // "MDN" +</pre> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> Bạn có thể dễ dàng lấy được global object bằng cách sử dụng thuộc tính toàn cầu {{jsxref("globalThis")}}, bất kể bối cảnh hiện tại mà mã của bạn đang chạy.</p> +</div> + +<h2 id="Function_context">Function context</h2> + +<p>Bên trong một hàm, giá trị của <code>this</code> phụ thuộc vào cách gọi hàm.</p> + +<h3 id="Simple_call">Simple call</h3> + +<p>Vì đoạn mã sau không ở chế độ <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, và vì giá trị của <code>this</code> không được thiết lập khi gọi, <code>this</code> mặc định là global objecct, đó là <a href="/en-US/docs/Web/API/Window" title="The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window."><code>window</code></a> trong trình duyệt. </p> + +<pre class="brush:js">function f1() { + return this; +} + +// In a browser: +f1() === window; // true + +// In Node: +f1() === global; // true</pre> + +<p>Tuy nhiên, trong chế độ strict mode, nếu giá trị của <code>this</code> không được thiết lập khi vào bối cảnh thực thi, nó sẽ giữ giá trị <code>undefined</code>, như ví dụ sau<strong>:</strong></p> + +<pre class="brush:js">function f2() { + 'use strict'; // see strict mode + return this; +} + +f2() === undefined; // true +</pre> + +<div class="note"> Trong ví dụ thứ 2, <code>this</code> nên là {{jsxref("undefined")}}, bởi vì <code>f2</code> được gọi 1 cách trực tiếp và không phải là một phương thức hoặc thuộc tính của một đối tượng(ví dụ <code>window.f2()</code>). ?Tính năng này sẽ không được triển khai trong một số trình duyệt khi chúng lần đầu hỗ trợ chế độ <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="Strict mode">strict mode</a>. Như kết quả trên, chúng không trả về đối tượng <code>window</code>.</div> + +<p>Để thiết lập giá trị cụ thể của <code>this</code> khi gọi hàm, sử dụng {{jsxref("Function.prototype.call()", "call()")}}, hoặc {{jsxref("Function.prototype.apply()", "apply()")}} như các ví dụ dưới đây<strong>.</strong></p> + +<p><strong>Example 1</strong></p> + +<pre class="brush:js" dir="rtl">// Một đối tượng có thể truyền vào như là tham số đầu tiên của call hoặc apply và this sẽ được ràng buộc với nó.. +var obj = {a: 'Custom'}; + +// Thuộc tính này được thiết lập trên global object +var a = 'Global'; + +function whatsThis() { + return this.a; // Giá trị của this phụ thuộc vào cách hàm được gọi. +} + +whatsThis(); // 'Global' +whatsThis.call(obj); // 'Custom' +whatsThis.apply(obj); // 'Custom' +</pre> + +<p><strong>Example 2</strong></p> + +<pre class="brush:js">function add(c, d) { + return this.a + this.b + c + d; +} + +var o = {a: 1, b: 3}; + +// Tham số đầu tiên là đối tượng sử dụng như là +// 'this', tham số tiếp theo được truyền vào là +// đối số trong hàm gọi +add.call(o, 5, 7); // 16 + +// Tham số đầu tiên là đối tượng sử dụng như là +// 'this', tham số thứ 2 là 1 mảng +// các phần tử được sử dụng làm đối số trong lệnh gọi hàm +add.apply(o, [10, 20]); // 34 +</pre> + +<p> Chú ý trong chế độ non–strict mode, với <code>call</code> và <code>apply</code>, nếu giá trị được truyền vào <code>this</code> không phải là đối tượng, một nỗ lực sẽ được thực hiện để chuyển đổi nó thành đối tượng bằng cách sử dụng <code>ToObject</code>. Vì thế nếu bạn truyền vào giá trị primitive như <code>7</code> hoặc <code>'foo'</code>, nó sẽ được chuyển đổi thành Object bằng cách sử dụng các constructor liên quan, do đó <code>7</code> sẽ được chuyển đổi thành đối tượng như tạo bằng <code>new Number(7)</code> và string <code>'foo'</code> cũng được chuyển đổi thành đối tượng như tạo bằng <code>new String('foo')</code>, ví dụ:</p> + +<pre class="brush:js">function bar() { + console.log(Object.prototype.toString.call(this)); +} + +bar.call(7); // [object Number] +bar.call('foo'); // [object String] +</pre> + +<h3 id="The_bind_method">The <code>bind</code> method</h3> + +<p>ECMAScript 5 giới thiệu {{jsxref("Function.prototype.bind()")}}. Gọi <code>f.bind(someObject)</code> tạo ra một hàm mới với cùng thân hàm và phạm vi như hàm <code>f</code>, nhưng <code>this</code> chỉ xảy ra trong hàm ban đầu, trong những hàm mới nó bị ràng buộc vĩnh viễn với đối số đầu tiên của <code>bind</code>, bất kể các hàm được sử dụng thế nào..</p> + +<pre class="brush:js">function f() { + return this.a; +} + +var g = f.bind({a: 'azerty'}); +console.log(g()); // azerty + +var h = g.bind({a: 'yoo'}); // bind only works once! +console.log(h()); // azerty + +var o = {a: 37, f: f, g: g, h: h}; +console.log(o.a, o.f(), o.g(), o.h()); // 37,37, azerty, azerty +</pre> + +<h3 id="Arrow_functions">Arrow functions</h3> + +<p>Trong <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>, <code>this</code> giữ giá trị ?<code>this</code> của lexical context kèm theo. Trong đoạn mã toàn cục, nó sẽ được thiết lập là global object.</p> + +<pre class="brush: js">var globalObject = this; +var foo = (() => this); +console.log(foo() === globalObject); // true</pre> + +<div class="note"> +<p> Lưu ý: nếu đối số this được truyền vào call, bind, hoặc apply ?trong việc gọi một arrow function nó sẽ bị bỏ qua. Bạn vẫn có thể thêm các đối số cho việc gọi hàm nhưng đối số đầu tiên (thisArg) nên được đặt thành null.</p> +</div> + +<pre class="brush: js">// Call as a method of an object +var obj = {func: foo}; +console.log(obj.func() === globalObject); // true + +// Attempt to set this using call +console.log(foo.call(obj) === globalObject); // true + +// Attempt to set this using bind +foo = foo.bind(obj); +console.log(foo() === globalObject); // true</pre> + +<p>Không có vấn đề gì ở đây, <code>this</code> của <code>foo</code> vẫn giữ nguyên giá trị khi nó được tạo (trong ví dụ trên, nó là global object). Điều tương tự cũng được áp dụng cho những arrow function được tạo bên trong hàm khác: <code>this</code> của chúng giữ giá trị <code>this</code> của lexical context kèm theo.</p> + +<pre class="brush: js">// Tạo 1 đối tượng với phương thức bar trả về 1 hàm, hàm này sẽ +// trả về this của nó. Hàm trả về là arrow function, +// vì thế this của nó được ràng buộc vĩnh viễn với this của hàm kèm theo. +// Giá trị của bar có thể được thiết lập trong khi gọi hàm, +// lần lượt đặt giá của hàm trả về. +var obj = { + bar: function() { + var x = (() => this); + return x; + } +}; + +// Gọi phương thức bar của obj, thiết lập this là obj. +// Gán một tham chiếu tới hàm trả về là fn +var fn = obj.bar(); + +// Gọi hàm fn mà không thiết lập 'this', +// thông thường sẽ mặc định cho global object hoặc undefined trong strict mode +console.log(fn() === obj); // true + +// Nhưng hãy cẩn thận nếu bạn tham chiếu phương thức của đối tượng mà không gọi nó +var fn2 = obj.bar; +// Gọi hàm arrow function bên trong phương thức bar() +// nó sẽ trả về window, bởi vì nó theo 'this' từ fn2. +console.log(fn2()() == window); // true +</pre> + +<p>Trong ví dụ trên, hàm (gọi nó là hàm ẩn danh A) gán cho <code>obj.bar</code> trả về một hàm khác (gọi là hàm ẩn danh B) mà nó là một arrow function. Kết quả là, <code>this</code> của hàm B được thiết lập vĩnh viễn là <code>this</code> của <code>obj.bar</code> (hàm A) khi được gọi. Khi hàm trả về (hàm B) được gọi, <code>this</code> của nó sẽ luôn là những gì được thiết lập ban đầu. Trong đoạn mã trên, <code>this</code> của hàm B được thiết lập theo <code>this</code> của hàm A đó là <code>obj</code>, vì thế nó vẫn được thiết lập là <code>obj</code> ngay cả khi được gọi theo cách thông thường thiết lập <code>this</code> thành <code>undefined</code> hoặc global object (hoặc bất kỳ phương thức nào khác như trong ví dụ trên được thực thi trong bối cảnh toàn cầu).</p> + +<h3 id="As_an_object_method">As an object method</h3> + +<p>Khi một hàm được gọi như là một phương thức của đối tượng,<code>this</code> được đặt thành đối tượng mà có phương thức được gọi trên.</p> + +<p>Trong ví dụ dưới đây, khi <code>o.f()</code> được gọi, <code>this</code> bên trong hàm sẽ liên kết với đối tượng <code>o</code>.</p> + +<pre class="brush:js">var o = { + prop: 37, + f: function() { + return this.prop; + } +}; + +console.log(o.f()); // 37 +</pre> + +<p>Lưu ý hành vi này hoàn toàn không bị ảnh hưởng bởi cách thức hoặc nơi chức năng được khai báo. Trong ví dụ ở trên, chúng ta khai báo hàm <code>f</code> bên trong đối tượng <code>o</code>. Tuy nhiên, chúng ta có thể dễ dàng khai báo hàm trước và đính kèm nó vào <code>o.f</code>. Làm như vậy sẽ có kết quả tương tự:</p> + +<pre class="brush:js">var o = {prop: 37}; + +function independent() { + return this.prop; +} + +o.f = independent; + +console.log(o.f()); // 37 +</pre> + +<p>Điều này chứng tỏ rằng vấn đề chỉ là việc gọi hàm <code>f</code> của <code>o</code>.</p> + +<p>Tương tự, ràng buộc với <code>this</code> chỉ bị ảnh hưởng bởi tham chiếu trực tiếp nhất. Trong ví dụ dưới, khi chúng ta gọi hàm, chúng ta gọi nó như là một phương thức <code>g</code> của đối tượng <code>o.b</code>. Khi thực thi, <code>this</code> bên trong hàm sẽ tham chiếu tới <code>o.b</code>. Thực tế đối tượng này là một thành viên của <code>o</code> không ảnh hưởng; tham chiếu trực tiếp nhất mới là quan trọng nhất.</p> + +<pre class="brush:js">var o = {prop: 37}; +function independent() { return this.prop; } +o.f = independent; +console.log(o.f()); // 37 bởi vì tham chiếu trực tiếp nhất là o +o.b = {g: independent, prop: 42}; +console.log(o.b.g()); // 42 bởi vì tham chiếu trực tiếp nhất là o.b +</pre> + +<h4 id="this_on_the_objects_prototype_chain"><code>this</code> on the object's prototype chain</h4> + +<p>The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, <code>this</code> refers to the object the method was called on, as if the method were on the object.</p> + +<pre class="brush:js">var o = {f: function() { return this.a + this.b; }}; +var p = Object.create(o); +p.a = 1; +p.b = 4; + +console.log(p.f()); // 5 +</pre> + +<p>In this example, the object assigned to the variable <code>p</code> doesn't have its own <code>f</code> property, it inherits it from its prototype. But it doesn't matter that the lookup for <code>f</code> eventually finds a member with that name on <code>o</code>; the lookup began as a reference to <code>p.f</code>, so <code>this</code> inside the function takes the value of the object referred to as <code>p</code>. That is, since <code>f</code> is called as a method of <code>p</code>, its <code>this</code> refers to <code>p</code>. This is an interesting feature of JavaScript's prototype inheritance.</p> + +<h4 id="this_with_a_getter_or_setter"><code>this</code> with a getter or setter</h4> + +<p>Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its <code>this</code> bound to the object from which the property is being set or gotten.</p> + +<pre class="brush:js">function sum() { + return this.a + this.b + this.c; +} + +var o = { + a: 1, + b: 2, + c: 3, + get average() { + return (this.a + this.b + this.c) / 3; + } +}; + +Object.defineProperty(o, 'sum', { + get: sum, enumerable: true, configurable: true}); + +console.log(o.average, o.sum); // 2, 6 +</pre> + +<h3 id="As_a_constructor">As a constructor</h3> + +<p>When a function is used as a constructor (with the {{jsxref("Operators/new", "new")}} keyword), its <code>this</code> is bound to the new object being constructed.</p> + +<div class="note"> +<p>While the default for a constructor is to return the object referenced by <code>this</code>, it can instead return some other object (if the return value isn't an object, then the <code>this</code> object is returned).</p> +</div> + +<pre class="brush:js">/* + * Constructors work like this: + * + * function MyConstructor(){ + * // Actual function body code goes here. + * // Create properties on |this| as + * // desired by assigning to them. E.g., + * this.fum = "nom"; + * // et cetera... + * + * // If the function has a return statement that + * // returns an object, that object will be the + * // result of the |new| expression. Otherwise, + * // the result of the expression is the object + * // currently bound to |this| + * // (i.e., the common case most usually seen). + * } + */ + +function C() { + this.a = 37; +} + +var o = new C(); +console.log(o.a); // 37 + + +function C2() { + this.a = 37; + return {a: 38}; +} + +o = new C2(); +console.log(o.a); // 38 +</pre> + +<p>In the last example (<code>C2</code>), because an object was returned during construction, the new object that <code>this</code> was bound to simply gets discarded. (This essentially makes the statement "<code>this.a = 37;</code>" dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.)</p> + +<h3 id="As_a_DOM_event_handler">As a DOM event handler</h3> + +<p>When a function is used as an event handler, its <code>this</code> is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than <a href="/en-US/docs/Web/API/EventTarget/addEventListener" title="The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target."><code>addEventListener()</code></a>).</p> + +<pre class="brush:js">// When called as a listener, turns the related element blue +function bluify(e) { + // Always true + console.log(this === e.currentTarget); + // true when currentTarget and target are the same object + console.log(this === e.target); + this.style.backgroundColor = '#A5D9F3'; +} + +// Get a list of every element in the document +var elements = document.getElementsByTagName('*'); + +// Add bluify as a click listener so when the +// element is clicked on, it turns blue +for (var i = 0; i < elements.length; i++) { + elements[i].addEventListener('click', bluify, false); +}</pre> + +<h3 id="In_an_inline_event_handler">In an inline event handler</h3> + +<p>When the code is called from an inline <a href="/en-US/docs/Web/Guide/Events/Event_handlers">on-event handler</a>, its <code>this</code> is set to the DOM element on which the listener is placed:</p> + +<pre class="brush:js"><button onclick="alert(this.tagName.toLowerCase());"> + Show this +</button> +</pre> + +<p>The above alert shows <code>button</code>. Note however that only the outer code has its <code>this</code> set this way:</p> + +<pre class="brush:js"><button onclick="alert((function() { return this; })());"> + Show inner this +</button> +</pre> + +<p>In this case, the inner function's <code>this</code> isn't set so it returns the global/window object (i.e. the default object in non–strict mode where <code>this</code> isn't set by the call).</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.this")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">Strict mode</a></li> + <li><a href="https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/">Gentle explanation of 'this' keyword in JavaScript</a></li> + <li>Getting the global context: {{jsxref("globalThis")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/operators/typeof/index.html b/files/vi/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..e949879669 --- /dev/null +++ b/files/vi/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,271 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operators/typeof +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Phương thức <strong><code>typeof</code></strong> trả về kiểu dữ liệu của đối tượng nào đó.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<p>Phương thức <code>typeof</code> được theo sau bởi toán hạng operand:</p> + +<pre class="syntaxbox">typeof <em>operand +</em>typeof(<em>operand</em>) +</pre> + +<h3 id="Các_tham_số">Các tham số</h3> + +<dl> + <dt><code>operand</code></dt> + <dd>Là một đối tượng cần kiểu tra kiểu dữ liệu hoặc một biểu thức đại điện cho đối tượng.</dd> +</dl> + +<h2 id="Định_nghĩa">Định nghĩa</h2> + +<p>Bảng tóm tắt bên dưới mô tả các giá trị có thể trả về của <code>typeof</code>. Xem thêm thông tin tại trang <a href="/en-US/docs/Web/JavaScript/Data_structures">JavaScript data structure</a>.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Type</th> + <th scope="col">Result</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{glossary("Undefined")}}</td> + <td><code>"undefined"</code></td> + </tr> + <tr> + <td>{{glossary("Null")}}</td> + <td><code>"object"</code> (see {{anch("null", "below")}})</td> + </tr> + <tr> + <td>{{glossary("Boolean")}}</td> + <td><code>"boolean"</code></td> + </tr> + <tr> + <td>{{glossary("Number")}}</td> + <td><code>"number"</code></td> + </tr> + <tr> + <td>{{glossary("BigInt")}}</td> + <td><code>"bigint"</code></td> + </tr> + <tr> + <td>{{glossary("String")}}</td> + <td><code>"string"</code></td> + </tr> + <tr> + <td>{{glossary("Symbol")}} (new in ECMAScript 2015)</td> + <td><code>"symbol"</code></td> + </tr> + <tr> + <td>Host object (provided by the JS environment)</td> + <td><em>Implementation-dependent</em></td> + </tr> + <tr> + <td>{{glossary("Function")}} object (implements [[Call]] in ECMA-262 terms)</td> + <td><code>"function"</code></td> + </tr> + <tr> + <td>Any other object</td> + <td><code>"object"</code></td> + </tr> + </tbody> +</table> + +<h2 id="Các_ví_dụ">Các ví dụ</h2> + +<pre class="brush:js">// Numbers +typeof 37 === 'number'; +typeof 3.14 === 'number'; +typeof(42) === 'number'; +typeof Math.LN2 === 'number'; +typeof Infinity === 'number'; +typeof NaN === 'number'; // Mặc dù "Not-A-Number" nhưng lại là number :) +typeof Number('1') === 'number'; // Number ép kiểu chuỗi thành kiểu number + +typeof 42n === 'bigint'; + + +// Strings +typeof '' === 'string'; +typeof 'bla' === 'string'; +typeof `template literal` === 'string'; +typeof '1' === 'string'; // 1 là number nhưng khi nằm trong ngoặc '' sẽ thành kiểu string +typeof (typeof 1) === 'string'; // typeof 1 sẽ trả về chữ number, bạn tự hiểu được hen +typeof String(1) === 'string'; // String sẽ đổi kiểu số 1 từ number thành string + +// Booleans +typeof true === 'boolean'; +typeof false === 'boolean'; +typeof Boolean(1) === 'boolean'; // Boolean() will convert values based on if they're truthy or falsy +typeof !!(1) === 'boolean'; // two calls of the ! (logical NOT) operator are equivalent to Boolean() + + +// Symbols +typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' + + +// Undefined +typeof undefined === 'undefined'; +typeof declaredButUndefinedVariable === 'undefined'; +typeof undeclaredVariable === 'undefined'; + + +// Objects +typeof {a: 1} === 'object'; + +// use <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray">Array.isArray</a> or Object.prototype.toString.call +// to differentiate regular objects from arrays +typeof [1, 2, 4] === 'object'; + +typeof new Date() === 'object'; +typeof /regex/ === 'object'; // See Regular expressions section for historical results + + +// The following are confusing, dangerous, and wasteful. Avoid them. +typeof new Boolean(true) === 'object'; +typeof new Number(1) === 'object'; +typeof new String('abc') === 'object'; + + +// Functions +typeof function() {} === 'function'; +typeof class C {} === 'function'; +typeof Math.sin === 'function'; +</pre> + +<h2 id="Additional_information">Additional information</h2> + +<h3 id="null"><code>null</code></h3> + +<pre class="brush:js">// This stands since the beginning of JavaScript +typeof null === 'object'; +</pre> + +<p>In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. <code>null</code> was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object" <code>typeof</code> return value. (<a href="http://www.2ality.com/2013/10/typeof-null.html">reference</a>)</p> + +<p>A fix was proposed for ECMAScript (via an opt-in), but <a class="external" href="https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null">was rejected</a>. It would have resulted in <code>typeof null === 'null'</code>.</p> + +<h3 id="Using_new_operator">Using <code>new</code> operator</h3> + +<pre class="brush:js">// All constructor functions, with the exception of the Function constructor, will always be typeof 'object' +var str = new String('String'); +var num = new Number(100); + +typeof str; // It will return 'object' +typeof num; // It will return 'object' + +var func = new Function(); + +typeof func; // It will return 'function' +</pre> + +<h3 id="Need_for_parentheses_in_Syntax">Need for parentheses in Syntax</h3> + +<pre class="brush:js">// Parentheses can be used for determining the data type of expressions. +var iData = 99; + +typeof iData + ' Wisen'; // 'number Wisen' +typeof (iData + ' Wisen'); // 'string' +</pre> + +<h3 id="Regular_expressions">Regular expressions</h3> + +<p>Callable regular expressions were a non-standard addition in some browsers.</p> + +<pre class="brush:js">typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1 +typeof /s/ === 'object'; // Firefox 5+ Conform to ECMAScript 5.1 +</pre> + +<h3 id="Errors">Errors</h3> + +<p>Before ECMAScript 2015, <code>typeof</code> was always guaranteed to return a string for any operand it was supplied with. Even with undeclared identifiers, <code>typeof</code> will return <code>'undefined'</code>. Using <code>typeof</code> could never generate an error.</p> + +<p>But with the addition of block-scoped {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const")}} using <code>typeof</code> on <code>let</code> and <code>const</code> variables (or using <code>typeof</code> on a <code>class</code>) in a block before they are declared will throw a {{jsxref("ReferenceError")}}. Block scoped variables are in a "<a href="/en-US/docs/Web/JavaScript/Reference/Statements/let#The_temporal_dead_zone_and_typeof">temporal dead zone</a>" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.</p> + +<pre class="brush: js">typeof undeclaredVariable === 'undefined'; + +typeof newLetVariable; // ReferenceError +typeof newConstVariable; // ReferenceError +typeof newClass; // ReferenceError + +let newLetVariable; +const newConstVariable = 'hello'; +class newClass{};</pre> + +<h3 id="Exceptions">Exceptions</h3> + +<p>All current browsers expose a non-standard host object {{domxref("document.all")}} with type <code>undefined</code>.</p> + +<pre class="brush:js">typeof document.all === 'undefined'; +</pre> + +<p>Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of <code>document.all</code> having type <code>'undefined'</code> is classified in the web standards as a "willful violation" of the original ECMA JavaScript standard.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.typeof")}}</p> + +<h2 id="IE-specific_notes">IE-specific notes</h2> + +<p>On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:</p> + +<pre class="brush: js">typeof alert === 'object'</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> + <li><a href="http://es-discourse.com/t/why-typeof-is-no-longer-safe/15">Why typeof is no longer "safe"</a></li> + <li><a href="https://github.com/tc39/ecma262/issues/668">document.all willful violation of the standard</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/async_function/index.html b/files/vi/web/javascript/reference/statements/async_function/index.html new file mode 100644 index 0000000000..3009b78083 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/async_function/index.html @@ -0,0 +1,255 @@ +--- +title: async function +slug: Web/JavaScript/Reference/Statements/async_function +translation_of: Web/JavaScript/Reference/Statements/async_function +--- +<div> +<div>{{jsSidebar("Statements")}}<br> +<span class="seoSummary">Việc tạo hàm với câu lệnh <code><strong>async function</strong></code> sẽ định nghĩa ra một <strong>hàm không đồng bộ (asynchronous function)</strong> - hàm này sẽ trả về một object {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}</span></div> + +<p>Các hàm không đồng bộ sẽ hoạt động trong một thứ tự tách biệt so với phần còn lại của đoạn code thông qua một <a href="/en-US/docs/Web/JavaScript/EventLoop">event loop</a>, trả về kết quả là một {{jsxref("Promise")}} tiềm ẩn. Nhưng cú pháp và cấu trúc của đoạn code mà sử dụng các hàm async function trông cứ như những hàm đồng bộ tiêu chuẩn.</p> + +<div class="noinclude"> +<p>Bạn cũng có thể định nghĩa các async function với một {{jsxref("Operators/async_function", "async function expression", "", 1)}}.</p> +</div> +</div> + +<div>{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">async function <var>name</var>([<var>param</var>[, <var>param</var>[, ...<var>param</var>]]]) { + <var>statements</var> +} +</pre> + +<h3 id="Các_thông_số">Các thông số</h3> + +<dl> + <dt><code><var>name</var></code></dt> + <dd>Tên của function.</dd> + <dt><code><var>param</var></code></dt> + <dd>Tên của một đối số được truyền vào function.</dd> + <dt><code><var>statements</var></code></dt> + <dd>Các câu lệnh bao hàm phần thân của function.</dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>Một <code><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>, cái mà sẽ được giải quyết với giá trị được trả về bởi async function, hoặc được đẩy ra ngoài với một exception không được bắt lại bên trong hàm async function.</p> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Một hàm async có thể bao gồm một biểu thức {{jsxref("Operators/await", "await")}}, biểu thức này sẽ tạm dừng việc thực thi của hàm async để chờ cho <code>Promise's resolution</code> được truyền vào, sau đó tiếp tục việc thực thi của hàm <code>async</code> and evaluates as the resolved value.</p> + +<p><strong>Từ khóa await chỉ có hiệu lực bên trong hàm <code>async</code>.</strong> Nếu bạn sử dụng nó bên ngoài phần thân của hàm <code>async</code>, bạn sẽ nhận một <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code>.</p> + +<p>Trong lúc hàm async tạm dừng, hàm được gọi sẽ tiếp tục chạy. (hàm mà nhận được Promise tiềm ẩn được trả về bởi hàm <code>async</code>).</p> + +<div class="note"> +<p>Mục đích của <code>async</code>/<code>await</code> là để đơn giả hóa việc sử dụng các promises một cách đồng bộ, và để triển khai một số hoạt động trên một nhóm của các <code>Promises</code>. Nếu <code>Promises </code>là tương tự như các callback có cấu trúc, <code>async</code>/<code>await </code>là tương tự với kết hợp các <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">generators</a> và promises.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Async_functions_và_thứ_tự_của_việc_thực_thi">Async functions và thứ tự của việc thực thi</h3> + +<pre class="brush: js">function resolveAfter2Seconds() { + console.log("starting slow promise") + return new Promise(resolve => { + setTimeout(function() { + resolve("slow") + console.log("slow promise is done") + }, 2000) + }) +} + +function resolveAfter1Second() { + console.log("starting fast promise") + return new Promise(resolve => { + setTimeout(function() { + resolve("fast") + console.log("fast promise is done") + }, 1000) + }) +} + +async function sequentialStart() { + console.log('==SEQUENTIAL START==') + + // 1. Execution gets here almost instantly + const slow = await resolveAfter2Seconds() + console.log(slow) // 2. this runs 2 seconds after 1. + + const fast = await resolveAfter1Second() + console.log(fast) // 3. this runs 3 seconds after 1. +} + +async function concurrentStart() { + console.log('==CONCURRENT START with await=='); + const slow = resolveAfter2Seconds() // starts timer immediately + const fast = resolveAfter1Second() // starts timer immediately + + // 1. Execution gets here almost instantly + console.log(await slow) // 2. this runs 2 seconds after 1. + console.log(await fast) // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved +} + +function concurrentPromise() { + console.log('==CONCURRENT START with Promise.all==') + return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => { + console.log(messages[0]) // slow + console.log(messages[1]) // fast + }) +} + +async function parallel() { + console.log('==PARALLEL with await Promise.all==') + + // Start 2 "jobs" in parallel and wait for both of them to complete + await Promise.all([ + (async()=>console.log(await resolveAfter2Seconds()))(), + (async()=>console.log(await resolveAfter1Second()))() + ]) +} + +// This function does not handle errors. See warning below! +function parallelPromise() { + console.log('==PARALLEL with Promise.then==') + resolveAfter2Seconds().then((message)=>console.log(message)) + resolveAfter1Second().then((message)=>console.log(message)) +} + +sequentialStart() // after 2 seconds, logs "slow", then after 1 more second, "fast" + +// wait above to finish +setTimeout(concurrentStart, 4000) // after 2 seconds, logs "slow" and then "fast" + +// wait again +setTimeout(concurrentPromise, 7000) // same as concurrentStart + +// wait again +setTimeout(parallel, 10000) // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow" + +// wait again +setTimeout(parallelPromise, 13000) // same as parallel +</pre> + +<h4 id="await_và_xử_lý_song_song"><code>await</code> và xử lý song song</h4> + +<p>In <code>sequentialStart</code>, execution suspends 2 seconds for the first <code>await</code>, and then another second for the second <code>await</code>. The second timer is not created until the first has already fired, so the code finishes after 3 seconds.</p> + +<p>In <code>concurrentStart</code>, both timers are created and then <code>await</code>ed. The timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.<br> + However, the <code>await</code> calls still run in series, which means the second <code>await</code> will wait for the first one to finish. In this case, the result of the fastest timer is processed after the slowest.</p> + +<p>If you wish to fully perform two or more jobs in parallel, you must use <code>await Promise.all([job1(), job2()])</code>, as shown in the <code>parallel</code> example.</p> + +<div class="warning"> +<h4 id="asyncawait_vs_Promise.then_and_error_handling"><code>async</code>/<code>await</code> vs <code>Promise.then</code> and error handling</h4> + +<p>Most async functions can also be written as regular functions using Promises. However, <code>async</code> functions are less tricky when it comes to error handling.</p> + +<p>Both <code>concurrentStart</code> and <code>concurrentPromise</code> are functionally equivalent:</p> + +<ul> + <li>In <code>concurrentStart</code>, if either of the <code>await</code>ed calls fail, the exception will be automatically caught, the async function execution interrupted, and the Error propagated to the caller through the implicit return Promise.</li> + <li>For the same to happen in the Promise case, the function must take care of returning a <code>Promise</code> which captures the completion of the function. In <code>concurrentPromise</code> that means <code>return</code>ing the promise from <code>Promise.all([]).then()</code>. As a matter of fact, a previous version of this example forgot to do this!</li> +</ul> + +<p>It is, however, still possible for <code>async</code> functions to mistakenly swallow errors.</p> + +<p>Take, for example the <code>parallel</code> async function. If it didn't <code>await</code> (or <code>return</code>) the result of the <code>Promise.all([])</code> call, any Error would not propagate.</p> + +<p>While the <code>parallelPromise</code> example seems simpler, it does not handle errors at all! Doing so would require a similar <code>return </code><code>Promise.all([])</code>.</p> +</div> + +<h3 id="Rewriting_a_Promise_chain_with_an_async_function">Rewriting a Promise chain with an <code>async</code> function</h3> + +<p>An API that returns a {{jsxref("Promise")}} will result in a promise chain, and it splits the function into many parts. Consider the following code:</p> + +<pre class="brush: js">function getProcessedData(url) { + return downloadData(url) // returns a promise + .catch(e => { + return downloadFallbackData(url) // returns a promise + }) + .then(v => { + return processDataInWorker(v) // returns a promise + }) +} +</pre> + +<p>it can be rewritten with a single <code>async</code> function as follows:</p> + +<pre class="brush: js">async function getProcessedData(url) { + let v + try { + v = await downloadData(url) + } catch(e) { + v = await downloadFallbackData(url) + } + return processDataInWorker(v) +} +</pre> + +<p>In the above example, there is no <code>await</code> statement after the <code>return</code> keyword, because the return value of an <code>async function</code> is implicitly wrapped in {{jsxref("Promise.resolve")}}.</p> + +<div class="blockIndicator note"> +<h4 id="return_await_promiseValue_vs._return_promiseValue"><code>return await promiseValue</code> vs. <code>return promiseValue</code></h4> + +<p>The implicit wrapping of return values in {{jsxref("Promise.resolve")}} does not imply that <code>return await promiseValue</code> is functionally equivalent to <code>return promiseValue</code>.</p> + +<p>Consider the following rewrite of the above code. It returns <code>null</code> if <code>processDataInWorker</code> rejects with an error:</p> + +<pre class="brush: js">async function getProcessedData(url) { + let v + try { + v = await downloadData(url) + } catch(e) { + v = await downloadFallbackData(url) + } + try { + return await processDataInWorker(v) // Note the `return await` vs. just `return` + } catch (e) { + return null + } +} +</pre> + +<p>Writing <code>return processDataInWorker(v)</code> would have caused the {{jsxref("Promise")}} returned by the function to reject, instead of resolving to <code>null</code> if <code>processDataInWorker(v)</code> rejects.</p> + +<p>This highlights the subtle difference between <code>return foo;</code> and <code>return await foo;</code> — <code>return foo</code> immediately returns <code>foo</code> and never throws, even if <code>foo</code> is a Promise that rejects. <code>return await foo</code> will <em>wait </em>for <code>foo</code> to resolve or reject if it's a Promise, and throws <strong>before returning</strong> if it rejects.</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.statements.async_function")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("AsyncFunction")}} object</li> + <li>{{jsxref("Operators/await", "await")}}</li> + <li><a href="http://innolitics.com/10x/javascript-decorators-for-promise-returning-functions/">"Decorating Async Javascript Functions" on "innolitics.com"</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/continue/index.html b/files/vi/web/javascript/reference/statements/continue/index.html new file mode 100644 index 0000000000..d6afd506d7 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/continue/index.html @@ -0,0 +1,135 @@ +--- +title: continue +slug: Web/JavaScript/Reference/Statements/continue +translation_of: Web/JavaScript/Reference/Statements/continue +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Câu lệnh <strong>continue </strong>chấm dứt việc thực thi của các câu lệnh trong lượt lặp hiện tại của vòng lặp hiện tại, hoặc của vòng lặp được gắn nhãn, và tiếp tục việc thực thi lượt lặp kế tiếp.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-continue.html")}}</div> + +<p class="hidden">Nguồn cho ví dụ tương tác này được lưu trữ trên GitHub repository. Nếu bạn muốn đóng góp vào các dự án ví dụ tương tác, hãy clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và send a pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">continue [<em>label</em>];</pre> + +<dl> + <dt><code>label</code></dt> + <dd>Identifier gắn liền với nhãn của câu lệnh.</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Trái ngược với câu lệnh {{jsxref("Statements/break", "break")}}, <code>continue</code> không chấm dứt việc thực thi của cả vòng lặp: thay vào đó,</p> + +<ul> + <li>Trong một vòng lặp {{jsxref("Statements/while", "while")}}, nó nhảy trở về biểu thức điều kiện.</li> + <li>Trong một vòng lặp {{jsxref("Statements/for", "for")}}, nó nhảy đến biểu thức tăng tiến (update expression).</li> +</ul> + +<p>Câu lệnh <code>continue</code> có thể bao gồm một nhãn tùy chọn cho phép chương trình nhảy đến lượt lặp tiếp theo của một câu lệnh vòng lặp được gắn nhãn, thay vì nhảy đến lượt lặp tiếp theo của vòng lặp hiện tại. Trong trường hợp này, câu lệnh <code>continue</code> cần được lồng bên trong câu lệnh được gắn nhãn đó.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_continue_với_while">Sử dụng continue với while</h3> + +<p>Ví dụ sau thể hiện một vòng lặp {{jsxref("Statements/while", "while")}} có một câu lệnh <code>continue</code> mà sẽ được thực thi khi giá trị của <code>i</code> là 3. Vì vậy, <code>n</code> nhận các giá trị 1, 3, 7 và 12.</p> + +<pre class="brush: js">var i = 0; +var n = 0; + +while (i < 5) { + i++; + + if (i === 3) { + continue; + } + + n += i; +} +</pre> + +<h3 id="Sử_dụng_continue_với_một_nhãn_label">Sử dụng continue với một nhãn (label)</h3> + +<p>Trong ví dụ sau đây, một câu lệnh được gắn nhãn <code>checkiandj</code> có chứa một câu lệnh được gắn nhãn <code>checkj</code>. Nếu gặp phải <code>continue</code>, chương trình sẽ tiếp tục tại phần đầu của câu lệnh <code>checkj</code>. Mỗi lần gặp phải <code>continue</code>, <code>checkj</code> sẽ chạy lại cho đến khi điều kiện của nó trả về false. Khi false được trả về, phần còn lại của câu lệnh <code>checkiandj</code> sẽ được hoàn thành.</p> + +<p>Nếu sau <code>continue</code> có một nhãn <code>checkiandj</code>, chương trình sẽ tiếp túc tại phần đầu của câu lệnh <code>checkiandj</code>.</p> + +<p>Xem thêm {{jsxref("Statements/label", "label")}}.</p> + +<pre class="brush: js">var i = 0; +var j = 8; + +checkiandj: while (i < 4) { + console.log('i: ' + i); + i += 1; + + checkj: while (j > 4) { + console.log('j: ' + j); + j -= 1; + + if ((j % 2) == 0) + continue checkj; + console.log(j + ' is odd.'); + } + console.log('i = ' + i); + console.log('j = ' + j); +} +</pre> + +<p>Kết quả:</p> + +<pre class="brush: js">i: 0 + +// start checkj +j: 8 +7 is odd. +j: 7 +j: 6 +5 is odd. +j: 5 +// end checkj + +i = 1 +j = 4 + +i: 1 +i = 2 +j = 4 + +i: 2 +i = 3 +j = 4 + +i: 3 +i = 4 +j = 4 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.continue")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/label", "label")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/do...while/index.html b/files/vi/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..eef8cf1f08 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,98 @@ +--- +title: do...while +slug: Web/JavaScript/Reference/Statements/do...while +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>Vòng lặp</strong> <strong><code>do...while</code></strong> tạo ra vòng lặp thực thi các câu lệnh bên trong nó đến khi điều kiện không còn thoả mãn nữa. Điều kiện của vòng lặp sẽ được kiểm tra sau thực thi các câu lệnh, các câu lệnh của vòng lặp sẽ được thực thi ít nhất một lần.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">do + <em>// các câu lệnh</em> +while (<em>// điều kiện</em>); +</pre> + +<dl> + <dt><code>statement</code></dt> + <dd>A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block")}} statement (<code>{ ... }</code>) to group those statements.</dd> +</dl> + +<dl> + <dt><code>condition</code></dt> + <dd>An expression evaluated after each pass through the loop. If <code>condition</code> evaluates to true, the <code>statement</code> is re-executed. When <code>condition</code> evaluates to false, control passes to the statement following the <code>do...while</code>.</dd> +</dl> + +<h2 id="Examples" name="Examples">Examples</h2> + +<h3 id="Using_do...while">Using <code>do...while</code></h3> + +<p>In the following example, the <code>do...while</code> loop iterates at least once and reiterates until <code>i</code> is no longer less than 5.</p> + +<h3 id="HTML_content">HTML content</h3> + +<pre class="brush: html"><div id="example"></div></pre> + +<h3 id="JavaScript_content">JavaScript content</h3> + +<pre class="brush: js">var result = ''; +var i = 0; +do { + i += 1; + result += i + ' '; +} while (i < 5); +document.getElementById('example').innerHTML = result;</pre> + +<h3 id="Result">Result</h3> + +<p>{{ EmbedLiveSample('Examples') }}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Trailing ; is now optional.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.do_while")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/for", "for")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/export/index.html b/files/vi/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..0187b3dbfa --- /dev/null +++ b/files/vi/web/javascript/reference/statements/export/index.html @@ -0,0 +1,186 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +translation_of: Web/JavaScript/Reference/Statements/export +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Lệnh <strong><code>export</code></strong> được sử dụng khi tạo các module JavaScript để export các hàm, đối tượng hoặc giá trị nguyên thủy trong module để chúng có thể được sử dụng bởi các chương trình khác bằng lệnh {{jsxref("Statements/import", "import")}}.</p> + +<div class="note"> +<p>Tính năng này mới chỉ được triển khai trên Safari vào thời điểm hiện tại. Nó cũng được triển khai ở nhiều trình dịch (transpilers), ví dụ như <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a>, <a href="http://babeljs.io/">Babel</a> hay <a href="https://github.com/rollup/rollup">Rollup</a>.</p> +</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">export { <var>name1</var>, <var>name2</var>, …, <var>nameN</var> }; +export { <var>variable1</var> as <var>name1</var>, <var>variable2</var> as <var>name2</var>, …, <var>nameN</var> }; +export let <var>name1</var>, <var>name2</var>, …, <var>nameN</var>; // còn có thể là var, function +export let <var>name1</var> = …, <var>name2</var> = …, …, <var>nameN</var>; // còn có thể là var, const + +export default <em>expression</em>; +export default function (…) { … } // còn có thể là class, function* +export default function name1(…) { … } // còn có thể là class, function* +export { <var>name1</var> as default, … }; + +export * from …; +export { <var>name1</var>, <var>name2</var>, …, <var>nameN</var> } from …; +export { <var>import1</var> as <var>name1</var>, <var>import2</var> as <var>name2</var>, …, <var>nameN</var> } from …;</pre> + +<dl> + <dt><code>nameN</code></dt> + <dd>Định danh được export (để có thể được import thông qua lệnh {{jsxref("Statements/import", "import")}} ở trong script khác).</dd> +</dl> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Có nhiều kiểu export khác nhau. Mỗi kiểu tương ứng với một trong các cú pháp ở phía trên:</p> + +<ul> + <li>Export tên: + <pre class="brush: js">// exports một hàm được định nghĩa phía trước +export { myFunction }; + +// exports một hằng số +export const foo = Math.sqrt(2);</pre> + </li> + <li>Export giá trị mặc định (hàm): + <pre class="brush: js">export default function() {} </pre> + </li> + <li>Export giá trị mặc định (lớp): + <pre class="brush: js">export default class {} </pre> + </li> +</ul> + +<p>Export tên hữu ích khi dùng để export một vài giá trị. Khi import, có thể dùng cùng tên đó để truy xuất đến giá trị tương ứng.</p> + +<p>Về export giá trị mặc định, chỉ có duy nhất một giá trị mặc định được export trên một module. Một giá trị được export mặc định có thể là một hàm, một lớp, một đối tượng hay bất cứ thứ gì khác. Giá trị này được coi là giá trị được export "chính" do nó sẽ là giá trị đơn giản nhất được import.</p> + +<p>Export các giá trị mặc định: Cú pháp sau đây không export một giá trị được export mặc định từ module được import:</p> + +<pre>export * from …;</pre> + +<p>Nếu bạn muốn export giá trị mặc định, hãy dùng cú pháp sau:</p> + +<pre>import mod from "mod"; +export default mod;</pre> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Sử_dụng_export_tên">Sử dụng export tên</h3> + +<p>Trong module, chúng ta có thể dùng code sau:</p> + +<pre class="brush: js">// module "my-module.js" +function cube(x) { + return x * x * x; +} +const foo = Math.PI + Math.SQRT2; +export { cube, foo }; +</pre> + +<p>Với cách này, trong script khác (cf. <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a></code>), chúng ta có:</p> + +<pre class="brush: js">import { cube, foo } from 'my-module'; +console.log(cube(3)); // 27 +console.log(foo); // 4.555806215962888</pre> + +<h3 id="Sử_dụng_export_giá_trị_mặc_định">Sử dụng export giá trị mặc định</h3> + +<p>Nếu chúng ta muốn export một giá trị duy nhất hay có một giá trị trả về mặc định từ module của mình, chúng ta có thể sử dụng export giá trị mặc định:</p> + +<pre class="brush: js">// module "my-module.js" +export default function cube(x) { + return x * x * x; +} +</pre> + +<p>Sau đó, trong script khác, có thể import thẳng giá trị được export mặc định:</p> + +<pre class="brush: js">import cube from 'my-module'; +console.log(cube(3)); // 27 +</pre> + +<p>Chú ý là không thể dùng <code>var</code>, <code>let</code> hay <code>const</code> với <code>export default</code>.</p> + +<h2 id="Đặc_tả">Đặc tả</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc tả</th> + <th scope="col">Trạng thái</th> + <th scope="col">Chú thích</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Định nghĩa ban đầu.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tương_thích_với_trình_duyệt">Tương thích với trình duyệt</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>61 (60 w/ flag)</td> + <td>{{CompatNo}} (54 w/ flag)</td> + <td>{{CompatNo}} (15 w/flag)</td> + <td>{{CompatNo}}</td> + <td>10.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Tính năng</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Hỗ trợ cơ bản</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>10.3</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Statements/import", "import")}}</li> + <li><a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">ES6 in Depth: Modules</a>, Hacks blog đăng bởi Jason Orendorff</li> + <li><a href="http://exploringjs.com/es6/ch_modules.html">Axel Rauschmayer's book: "Exploring JS: Modules"</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/for...of/index.html b/files/vi/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..5bd72040eb --- /dev/null +++ b/files/vi/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,318 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Cú pháp <strong><code>for...of</code></strong> để chạy <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">vòng lặp </a> trên {{jsxref("String")}}, {{jsxref("Array")}}, đối tượng tương tự <code>Array</code> (như {{jsxref("Functions/arguments", "arguments")}} hoặc {{domxref("NodeList")}}), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-forof.html")}}</div> + +<p class="hidden">Ví dụ được lưu trên GitHub repository. Nếu muốn đóng góp, bạn có thể clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gởi lên pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate">for (<em>tên-biến</em> of <em>đối-tượng-chạy-vòng-lặp</em>) { + <em>...câu lệnh...</em> +} +</pre> + +<dl> + <dt><code>tên biến</code></dt> + <dd><br> + Trên mỗi lần lặp, một giá trị của một thuộc tính khác nhau được gán cho biến. biến có thể được khai báo với const, let hoặc var.</dd> + <dt><code>đối tượng để chạy vòng lặp</code></dt> + <dd>Đối tượng có các thuộc tính có thể được lặp lại (<em>iterable</em>).</dd> +</dl> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Lặp_qua_một_jsxrefArray">Lặp qua một {{jsxref("Array")}}</h3> + +<pre class="brush:js notranslate">let iterable = [10, 20, 30]; + +for (let value of iterable ) { + value += 1; + console.log(value); +} +// 11 +// 21 +// 31 +</pre> + +<p>Có thể khai báo bằng <a href="/en-US/docs/Web/JavaScript/Reference/Statements/const"><code>const</code></a> thay cho <a href="/en-US/docs/Web/JavaScript/Reference/Statements/let"><code>let</code></a>, nếu không có thay đổi biến bên trong vòng lặp.</p> + +<pre class="brush:js notranslate">let iterable= [10, 20, 30]; + +for (const value of iterable) { + console.log(value); +} +// 10 +// 20 +// 30 +</pre> + +<h3 id="Lặp_qua_một_jsxrefString">Lặp qua một {{jsxref("String")}}</h3> + +<pre class="brush:js notranslate">const iterable = 'boo'; + +for (const value of iterable) { + console.log(value); +} +// "b" +// "o" +// "o" +</pre> + +<h3 id="Lặp_qua_jsxrefTypedArray">Lặp qua {{jsxref("TypedArray")}}</h3> + +<pre class="brush:js notranslate">const iterable = new Uint8Array([0x00, 0xff]); + +for (const value of iterable) { + console.log(value); +} +// 0 +// 255 +</pre> + +<h3 id="Lặp_qua_một_jsxrefMap">Lặp qua một {{jsxref("Map")}}</h3> + +<pre class="brush:js notranslate">const iterable = new Map([['a', 1], ['b', 2], ['c', 3]]); + +for (const entry of iterable) { + console.log(entry); +} +// ['a', 1] +// ['b', 2] +// ['c', 3] + +for (const [key, value] of iterable) { + console.log(value); +} +// 1 +// 2 +// 3 +</pre> + +<h3 id="Loop_qua_một_jsxrefSet">Loop qua một {{jsxref("Set")}}</h3> + +<pre class="brush:js notranslate">const iterable = new Set([1, 1, 2, 2, 3, 3]); + +for (const value of iterable) { + console.log(value); +} +// 1 +// 2 +// 3 +</pre> + +<h3 id="Lặp_qua_một_đối_tượng_arguments">Lặp qua một đối tượng <code>arguments</code></h3> + +<p>Lặp qua đối tượng {{jsxref("Functions/arguments", "arguments")}} để có tất cả giá trị được truyền vào trong hàm:</p> + +<pre class="brush: js notranslate">(function() { + for (const argument of arguments) { + console.log(argument); + } +})(1, 2, 3); + +// 1 +// 2 +// 3</pre> + +<h3 id="Lặp_qua_một_tập_DOM">Lặp qua một tập DOM</h3> + +<p>Lặp qua một tập DOM như {{domxref("NodeList")}}: ví dụ bên dưới, thêm class <code>read</code> cho các đoạn văn bản nào là con trực tiếp của article:</p> + +<pre class="brush:js notranslate">// Lưu ý: Chỉ hoạt động động trên các platforms có +// hiện thực NodeList.prototype[Symbol.iterator] +const articleParagraphs = document.querySelectorAll('article > p'); + +for (const paragraph of articleParagraphs) { + paragraph.classList.add('read'); +} +</pre> + +<h3 id="Đóng_vòng_lặp">Đóng vòng lặp</h3> + +<p>Trong vòng lặp <code>for...of</code>, có thể ngừng lặp giữa chừng bằng <code>break</code>, <code>continue</code>, <code>throw</code> hoặc <code>return</code>. Trong các trường hợp này, vòng lặp sẽ được ngưng lại.</p> + +<pre class="brush: js notranslate">function* foo(){ + yield 1; + yield 2; + yield 3; +}; + +for (const o of foo()) { + console.log(o); + break; // đóng vòng lặp, tiếp tục thực thi bên ngoài vòng lặp +} +console.log('Xong') +</pre> + +<h3 id="Lặp_qua_generator">Lặp qua generator</h3> + +<p>Bạn cũng có thể lặp qua hàm <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">generators</a>, ví dụ:</p> + +<pre class="brush:js notranslate">function* fibonacci() { // một hàm generator + let [prev, curr] = [0, 1]; + while (true) { + [prev, curr] = [curr, prev + curr]; + yield curr; + } +} + +for (const n of fibonacci()) { + console.log(n); + // truncate the sequence at 1000 + if (n >= 1000) { + break; + } +} +</pre> + +<h4 id="Không_tái_sử_dụng_generator">Không tái sử dụng generator</h4> + +<p>Không nên re-used Generator, ngay cả khi vòng lặp <code>for...of</code> bị kết thúc sớm bằng {{jsxref("Statements/break", "break")}}. Khi thoát khỏi vòng lặp, generator sẽ kết thúc và cố lặp lại lần nữa sẽ không cho thêm bất kỳ kết quả yield nào khác.</p> + +<pre class="brush: js example-bad notranslate">const gen = (function *(){ + yield 1; + yield 2; + yield 3; +})(); +for (const o of gen) { + console.log(o); + break; // Closes iterator +} + +// Không dùng lại generator, đoạn code như thế này không hợp lý! +for (const o of gen) { + console.log(o); // Không bao giờ được gọi +} +</pre> + +<h3 id="Lặp_qua_các_đối_tượng_khác">Lặp qua các đối tượng khác</h3> + +<p>Bạn cũng có thể loop qua các đối tượng tự định nghĩa, nếu có hiện thực <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable">iterable</a>:</p> + +<pre class="brush:js notranslate">const iterable = { + [Symbol.iterator]() { + return { + i: 0, + next() { + if (this.i < 3) { + return { value: this.i++, done: false }; + } + return { value: undefined, done: true }; + } + }; + } +}; + +for (const value of iterable) { + console.log(value); +} +// 0 +// 1 +// 2 +</pre> + +<h3 id="Sự_khác_biệt_giữa_for...of_và_for...in">Sự khác biệt giữa <code>for...of</code> và <code>for...in</code></h3> + +<p>Cú pháp {{jsxref("Statements/for...in", "for...in")}} lặp qua các đối tượng <a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">được đếm</a>, theo một thứ tự tùy ý.</p> + +<p>Cú pháp <code>for...of</code> lặp qua đối tượng dữ liệu <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">có thể lặp</a>.</p> + +<p>Ví dụ sau để thấy sự khác nhau giữa <code>for...of</code> và <code>for...in</code> khi sử dụng với {{jsxref("Array")}}.</p> + +<pre class="brush:js notranslate">Object.prototype.objCustom = function() {}; +Array.prototype.arrCustom = function() {}; + +const iterable = [3, 5, 7]; +iterable.foo = 'hello'; + +for (const i in iterable) { + console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" +} + +for (const i in iterable) { + if (iterable.hasOwnProperty(i)) { + console.log(i); // logs 0, 1, 2, "foo" + } +} + +for (const i of iterable) { + console.log(i); // logs 3, 5, 7 +} +</pre> + +<p>Giải thích ví dụ trên</p> + +<pre class="brush: js notranslate">Object.prototype.objCustom = function() {}; +Array.prototype.arrCustom = function() {}; + +const iterable = [3, 5, 7]; +iterable.foo = 'hello';</pre> + +<p>Tất cả object sẽ kế thừa thuộc tính <code>objCustom</code> và tất cả {{jsxref("Array")}} sẽ kết thừa thuộc tính <code>arrCustom</code> bởi vì chúng ta thêm nó vào bằng {{jsxref("Object.prototype")}} và {{jsxref("Array.prototype")}}. <code>iterable</code> kế thừa cả <code>objCustom</code> và <code>arrCustom</code>.</p> + +<pre class="brush: js notranslate">for (const i in iterable) { + console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" +}</pre> + +<p>Vòng vòng lặp này chỉ log <a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">thuộc tính được đếm</a> của <code>iterable</code>, theo thứ tự được đưa vào. Nó không log các <strong>element</strong> của array <code>3</code>, <code>5</code>, <code>7</code> hoặc <code>hello</code> bởi vì nó là không thuộc tính được đếm. Nó log giá trị <strong>index</strong> cũng như <code>arrCustom</code> và <code>objCustom</code>.</p> + +<pre class="brush: js notranslate">for (let i in iterable) { + if (iterable.hasOwnProperty(i)) { + console.log(i); // logs 0, 1, 2, "foo" + } +}</pre> + +<p>Vòng loop tương tự như ở trên, nhưng sử dụng {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}} để kiểm tra, nếu tìm thấy một property của chính nó chứ không phải kế thừa và log kết quả ra. Các Property <code>0</code>, <code>1</code>, <code>2</code> và <code>foo</code> được log bởi vì nó không phải được kết thừa.</p> + +<pre class="brush: js notranslate">for (const i of iterable) { + console.log(i); // logs 3, 5, 7 +}</pre> + +<p>Vòng lặp và log ra giá trị bên trong đối tượng <code>iterable</code> như một <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">iterable object</a><strong> </strong> được khai báo để lặp, chính là các element bên trong mảng <code>3</code>, <code>5</code>, <code>7</code> và không bao gồm các <strong>property</strong> của object.</p> + +<h2 id="Đặc_điểm">Đặc điểm</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Đặc điểm</th> + <th scope="col">Status</th> + <th scope="col">Ghi chú</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-for-in-and-for-of-statements', 'for...of statement')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hổ_trợ">Trình duyệt hổ trợ</h2> + +<div class="hidden">Nếu muốn đóng góp dữ liệu cho bảng này, vui lòng check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> và gởi chúng tôi pull request.</div> + +<p>{{Compat("javascript.statements.for_of")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/for/index.html b/files/vi/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..613732de85 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/for/index.html @@ -0,0 +1,137 @@ +--- +title: for +slug: Web/JavaScript/Reference/Statements/for +translation_of: Web/JavaScript/Reference/Statements/for +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>The <strong>for statement</strong> creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/block">block statement</a>) to be executed in the loop.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-for.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">for ([<em>initialization</em>]; [<em>condition</em>]; [<em>final-expression</em>]) + <em>statement</em></pre> + +<dl> + <dt><code>initialization</code></dt> + <dd>An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with <code>var</code> or <code>let</code> keywords. Variables declared with <code>var</code> are not local to the loop, i.e. they are in the same scope the <code>for</code> loop is in. Variables declared with let are local to the statement.</dd> + <dd>The result of this expression is discarded.</dd> + <dt><code>condition</code></dt> + <dd>An expression to be evaluated before each loop iteration. If this expression evaluates to true, <code>statement</code> is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the <code>for</code> construct.</dd> + <dt><code>final-expression</code></dt> + <dd>An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of <code>condition</code>. Generally used to update or increment the counter variable.</dd> + <dt><code>statement</code></dt> + <dd>A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement (<code>{ ... }</code>) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (<code>;</code>).</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_for">Using <code>for</code></h3> + +<p>The following <code>for</code> statement starts by declaring the variable <code>i</code> and initializing it to <code>0</code>. It checks that <code>i</code> is less than nine, performs the two succeeding statements, and increments <code>i</code> by 1 after each pass through the loop.</p> + +<pre class="brush: js">for (let i = 0; i < 9; i++) { + console.log(i); + // more statements +} +</pre> + +<h3 id="Optional_for_expressions">Optional <code>for</code> expressions</h3> + +<p>All three expressions in the head of the <code>for</code> loop are optional.</p> + +<p>For example, in the <em>initialization</em> block it is not required to initialize variables:</p> + +<pre class="brush: js">var i = 0; +for (; i < 9; i++) { + console.log(i); + // more statements +} +</pre> + +<p>Like the <em>initialization</em> block, the <em>condition</em> block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.</p> + +<pre class="brush: js">for (let i = 0;; i++) { + console.log(i); + if (i > 3) break; + // more statements +}</pre> + +<p>You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.</p> + +<pre class="brush: js">var i = 0; + +for (;;) { + if (i > 3) break; + console.log(i); + i++; +} +</pre> + +<h3 id="Using_for_without_a_statement">Using <code>for</code> without a statement</h3> + +<p>The following <code>for</code> cycle calculates the offset position of a node in the <em>final-expression</em> section, and therefore it does not require the use of a <code>statement</code> section, a semicolon is used instead.</p> + +<pre class="brush: js">function showOffsetPos(sId) { + + var nLeft = 0, nTop = 0; + + for ( + + var oItNode = document.getElementById(sId); /* initialization */ + + oItNode; /* condition */ + + nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */ + + ); /* semicolon */ + + console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;'); + +} + +/* Example call: */ + +showOffsetPos('content'); + +// Output: +// "Offset position of "content" element: +// left: 0px; +// top: 153px;"</pre> + +<div class="note"><strong>Note:</strong> This is one of the few cases in JavaScript where <strong>the semicolon is mandatory</strong>. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden"><font><font>Bảng tương thích trên trang này được tạo từ dữ liệu có cấu trúc. </font><font>Nếu bạn muốn đóng góp cho dữ liệu, vui lòng xem </font></font><a href="https://github.com/mdn/browser-compat-data"><font><font>https://github.com/mdn/browser-compat-data</font></font></a><font><font> và gửi cho chúng tôi yêu cầu kéo.</font></font></div> + +<p><font><font>{{Compat ("javascript.statements.for")}}</font></font></p> + +<h2 id="Xem_thêm"><font><font>Xem thêm</font></font></h2> + +<ul> + <li><font><font>{{jsxref ("Báo cáo / trống", "tuyên bố trống", "", 0)}}</font></font></li> + <li><font><font>{{jsxref ("Tuyên bố / phá vỡ", "phá vỡ")}}</font></font></li> + <li><font><font>{{jsxref ("Tuyên bố / tiếp tục", "tiếp tục")}}</font></font></li> + <li><font><font>{{jsxref ("Tuyên bố / while", "while")}}</font></font></li> + <li><font><font>{{jsxref ("Tuyên bố / làm ... trong khi", "làm ... trong khi")}}</font></font></li> + <li><font><font>{{jsxref ("Tuyên bố / cho ... trong", "cho ... trong")}}</font></font></li> + <li><font><font>{{jsxref ("Tuyên bố / cho ... của", "cho ... của")}}</font></font></li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/function_star_/index.html b/files/vi/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..388e0f8b34 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,208 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +translation_of: Web/JavaScript/Reference/Statements/function* +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Khai báo <code><strong>function*</strong></code> (từ khóa <code>function</code> tiếp theo là dấu sao) định nghĩa một <em>generator function</em>, một phương thức trả về đối tượng {{jsxref("Global_Objects/Generator","Generator")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}</div> + + + +<div class="noinclude"> +<p>Bạn cũng có thể khai báo generator functions bằng constructor {{jsxref("GeneratorFunction")}} , hoặc cú pháp function expression.</p> +</div> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox notranslate">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>Tên phương thức</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>Các tham số truyền vào cho phương thức.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>Các câu lệnh bên trong phương thức</dd> +</dl> + +<h2 id="Diễn_giải">Diễn giải</h2> + +<p>Generators là một hàm có thể thoát và sau đó gọi lại lần nữa. Giá trị của biến trong các lần gọi được lưu lại trong các lần gọi tiếp theo.<br> + <br> + Pattern là cách hàm <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a></code> được viết ra.</p> + +<p>Gọi một generator function không thực thi các lệnh bên trong hàm ngày lập tức; Thay vào đó, một object <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">iterator</a> được trả về. Khi iterator gọi đến phương thức <code>next()</code> , lúc này các lệnh bên trong hàm được thực thi cho đến khi gặp câu {{jsxref("Operators/yield", "yield")}} , sau câu lệnh {{jsxref("Operators/yield", "yield")}} là giá trị sẽ trả về, hoặc gọi đến một generator function khác. Phương thức <code>next()</code> trả về một object với property <code>value</code> chứa giá trị yielded và property <code>done</code> , giá trị kiểu boolean, xác định generator yielded trả về đã là cuối cùng chưa. Gọi phương thức <code>next()</code> với một tham số sẽ chạy hàm generator tiếp tục, thay thế câu <code>yield</code> nơi hàm đã dừng lại trước đó với tham số từ <code>next()</code>. </p> + +<p>Câu lệnh <code>return</code> trong generator, khi chạy, sẽ kết thúc generator (ví dụ property <code>done</code> trả về sẽ có giá trị <code>true</code>). Nếu giá trị đã được trả về, nó sẽ được set cho property <code>value</code>.<br> + Giống như câu lệnh <code>return</code> , thrown error trong generator sẽ kết thúc generator -- trừ khi bắt lại bằng bên trong generator.<br> + Khi một generator kết thúc, các câu gọi <code>next</code> tiếp theo sau sẽ không được thực thi, nó chỉ trả về object có dạng: <code>{value: undefined, done: true}</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Ví_dụ_đơn_giản">Ví dụ đơn giản</h3> + +<pre class="brush: js notranslate">function* idMaker() { + var index = 0; + while (index < index+1) + yield index++; +} + +var gen = idMaker(); + +console.log(gen.next().value); // 0 +console.log(gen.next().value); // 1 +console.log(gen.next().value); // 2 +console.log(gen.next().value); // 3 +// ...</pre> + +<h3 id="Ví_dụ_với_yield*">Ví dụ với yield*</h3> + +<pre class="brush: js notranslate">function* anotherGenerator(i) { + yield i + 1; + yield i + 2; + yield i + 3; +} + +function* generator(i) { + yield i; + yield* anotherGenerator(i); + yield i + 10; +} + +var gen = generator(10); + +console.log(gen.next().value); // 10 +console.log(gen.next().value); // 11 +console.log(gen.next().value); // 12 +console.log(gen.next().value); // 13 +console.log(gen.next().value); // 20 +</pre> + +<h3 id="Truyền_tham_số_vào_trong_Generators">Truyền tham số vào trong Generators</h3> + +<pre class="brush: js notranslate">function* logGenerator() { + console.log(0); + console.log(1, yield); + console.log(2, yield); + console.log(3, yield); +} + +var gen = logGenerator(); + +gen.next(); // 0 +gen.next('pretzel'); // 1 pretzel +gen.next('california'); // 2 california +gen.next('mayonnaise'); // 3 mayonnaise +</pre> + +<h3 id="Return_bên_trong_generator">Return bên trong generator</h3> + +<pre class="brush: js notranslate">function* yieldAndReturn() { + yield "Y"; + return "R"; + yield "unreachable"; +} + +var gen = yieldAndReturn() +console.log(gen.next()); // { value: "Y", done: false } +console.log(gen.next()); // { value: "R", done: true } +console.log(gen.next()); // { value: undefined, done: true } +</pre> + +<h3 id="Generators_không_dùng_constructable">Generators không dùng constructable</h3> + +<pre class="brush: js notranslate">function* f() {} +var obj = new f; // throws "TypeError: f is not a constructor +</pre> + +<h3 id="Generator_khai_báo_bằng_expression">Generator khai báo bằng expression</h3> + +<pre class="brush: js notranslate">const foo = function* () { + yield 10; + yield 20; +}; + +const bar = foo(); +console.log(bar.next()); // {value: 10, done: false}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES2015', '#sec-generator-function-definitions', 'function*')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-generator-function-definitions', 'function*')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td>Changed that generators should not have [[Construct]] trap and will throw when used with <code>new</code>.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator-function-definitions', 'function*')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hỗ_trợ">Trình duyệt hỗ trợ</h2> + +<div> + + +<p>{{Compat("javascript.statements.generator_function")}}</p> +</div> + +<h2 id="Lưu_ý_dành_riêng_cho_Firefox">Lưu ý dành riêng cho Firefox</h2> + +<h4 id="Generators_và_iterators_trước_phiên_bản_Firefox_26">Generators và iterators trước phiên bản Firefox 26</h4> + +<p>Older Firefox versions implement an older version of the generators proposal. In the older version, generators were defined using a regular <code>function</code> keyword (without an asterisk) among other differences. See <a href="/en-US/docs/Web/JavaScript/Reference/Statements/Legacy_generator_function">Legacy generator function </a>for further information.</p> + +<h4 id="IteratorResult_object_returned_instead_of_throwing"><code>IteratorResult</code> object returned instead of throwing</h4> + +<p>Starting with Gecko 29 {{geckoRelease(29)}}, the completed generator function no longer throws a {{jsxref("TypeError")}} "generator has already finished". Instead, it returns an <code>IteratorResult</code> object like <code>{ value: undefined, done: true }</code> ({{bug(958951)}}).</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}} object</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> + <li>{{jsxref("Operators/yield", "yield")}}</li> + <li>{{jsxref("Operators/yield*", "yield*")}}</li> + <li>{{jsxref("Function")}} object</li> + <li>{{jsxref("Statements/function", "function declaration")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>Nguồn trang khác: + <ul> + <li><a href="http://facebook.github.io/regenerator/">Regenerator</a> an ES2015 generator compiler to ES5</li> + <li><a href="http://www.youtube.com/watch?v=qbKWsbJ76-s">Forbes Lindesay: Promises and Generators: control flow utopia -- JSConf EU 2013</a></li> + <li><a href="https://www.youtube.com/watch?v=ZrgEZykBHVo&list=PLuoyIZT5fPlG44bPq50Wgh0INxykdrYX7&index=1">Hemanth.HM: The New gen of *gen(){}</a></li> + <li><a href="https://github.com/mozilla/task.js">Task.js</a></li> + <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch4.md#iterating-generators-asynchronously">Iterating generators asynchronously</a></li> + </ul> + </li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/index.html b/files/vi/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..460884b7d9 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/index.html @@ -0,0 +1,143 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.</p> + +<h2 id="Statements_and_declarations_by_category">Statements and declarations by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Control_flow">Control flow</h3> + +<dl> + <dt>{{jsxref("Statements/block", "Block")}}</dt> + <dd>A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.</dd> + <dt>{{jsxref("Statements/break", "break")}}</dt> + <dd>Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.</dd> + <dt>{{jsxref("Statements/continue", "continue")}}</dt> + <dd>Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.</dd> + <dt>{{jsxref("Statements/Empty", "Empty")}}</dt> + <dd>An empty statement is used to provide no statement, although the JavaScript syntax would expect one.</dd> + <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> + <dd>Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.</dd> + <dt>{{jsxref("Statements/switch", "switch")}}</dt> + <dd>Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.</dd> + <dt>{{jsxref("Statements/throw", "throw")}}</dt> + <dd>Throws a user-defined exception.</dd> + <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> + <dd>Marks a block of statements to try, and specifies a response, should an exception be thrown.</dd> +</dl> + +<h3 id="Declarations">Declarations</h3> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Functions_and_classes">Functions and classes</h3> + +<dl> + <dt>{{jsxref("Statements/function", "function")}}</dt> + <dd>Declares a function with the specified parameters.</dd> + <dt>{{jsxref("Statements/function*", "function*")}}</dt> + <dd>Generators functions enable writing <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterators</a> more easily.</dd> + <dt>{{jsxref("Statements/async_function", "async function")}}</dt> + <dd>Declares an async function with the specified parameters.</dd> + <dt>{{jsxref("Statements/return", "return")}}</dt> + <dd>Specifies the value to be returned by a function.</dd> + <dt>{{jsxref("Statements/class", "class")}}</dt> + <dd>Declares a class.</dd> +</dl> + +<h3 id="Iterations">Iterations</h3> + +<dl> + <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> + <dd>Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.</dd> + <dt>{{jsxref("Statements/for", "for")}}</dt> + <dd>Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.</dd> + <dt>{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}</dt> + <dd>Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.</dd> + <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> + <dd>Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.</dd> + <dt>{{jsxref("Statements/for...of", "for...of")}}</dt> + <dd>Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators">iterators and generators</a>), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</dd> + <dt>{{jsxref("Statements/while", "while")}}</dt> + <dd>Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.</dd> +</dl> + +<h3 id="Others">Others</h3> + +<dl> + <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> + <dd>Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.</dd> + <dt>{{jsxref("Statements/export", "export")}}</dt> + <dd>Used to export functions to make them available for imports in external modules, another scripts.</dd> + <dt>{{jsxref("Statements/import", "import")}}</dt> + <dd>Used to import functions exported from an external module, another script.</dd> + <dt>{{jsxref("Statements/label", "label")}}</dt> + <dd>Provides a statement with an identifier that you can refer to using a <code>break</code> or <code>continue</code> statement.</dd> +</dl> + +<dl> + <dt>{{deprecated_inline}} {{jsxref("Statements/with", "with")}}</dt> + <dd>Extends the scope chain for a statement.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: function*, let, for...of, yield, class</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Operators</a></li> +</ul> diff --git a/files/vi/web/javascript/reference/statements/throw/index.html b/files/vi/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..c3116c8847 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,193 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +translation_of: Web/JavaScript/Reference/Statements/throw +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Câu lệnh <strong><code>throw</code> </strong> sẽ đưa ra một exception theo cách chúng ta định nghĩa. Các câu lệnh phía sau <code>throw</code> sẽ không được chạy, và sẽ gọi hàm callback <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>catch</code></a> đầu tiên tìm thấy. Nếu không có hàm <code>catch</code>, chương trình sẽ không chạy nữa.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-throw.html")}}</div> + +<p class="hidden">Source này được lưu trên GitHub repository. Nếu muốn đóng góp cho ví dụ này, bạn clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gởi lên pull request.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">throw <em>expression</em>; </pre> + +<dl> + <dt><code>expression</code></dt> + <dd>Một diễn giải.</dd> +</dl> + +<h2 id="Giải_thích">Giải thích</h2> + +<p>Sử dụng câu lệnh <code>throw</code> để đưa ra một exception. Giá trị của expression trả về có thể string, number, boolean, hay Object. Mỗi câu <code>throw </code>chỉ trả về một exception</p> + +<pre class="brush: js">throw 'Error2'; // 1 exception dạng string +throw 42; // 1 exception giá trị 42 +throw true; // 1 exception với giá trị boolean là true +throw new Error('Required'); // tạo một error object với nội dung Required +</pre> + +<p>Câu lệnh <code>throw</code> tuân thủ nguyên tắc <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a> , nghĩa là không được phép xuống dòng giữa từ khóa <code>throw</code> và <code>expression</code>.</p> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Throw_một_object">Throw một object</h3> + +<p>Exception có thể là một object. Lúc này có thể tham chiếu đến các property của object bên trong khối lệnh <code>catch</code> . Ví dụ sau, tạo một object với kiểu là <code>UserException</code> và sử dụng nó trong câu <code>throw</code>.</p> + +<pre class="brush: js">function UserException(message) { + this.message = message; + this.name = 'UserException'; +} +function getMonthName(mo) { + mo = mo - 1; // Thay đổi giá trị của index array tương ứng cho tháng (1 = Jan, 12 = Dec) + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', + 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + if (months[mo] !== undefined) { + return months[mo]; + } else { + throw new UserException('InvalidMonthNo'); + } +} + +try { + // statements to try + var myMonth = 15; // 15 nằm ngoài giá trị cho phép + var monthName = getMonthName(myMonth); +} catch (e) { + monthName = 'unknown'; + console.log(e.message, e.name); // truyền exception object vào câu lệnh xử lý nếu có lỗi +} +</pre> + +<h3 id="Một_ví_dụ_khác_sử_dụng_object">Một ví dụ khác sử dụng object</h3> + +<p>Trong ví dụ sau, kiểm tra input, chỉ cho phép là giá trị U.S. zip code. Nếu giá trị zip code này không đúng format, throw một exception object là <code>ZipCodeFormatException</code>.</p> + +<pre class="brush: js">/* + * Creates a ZipCode object. + * + * Accepted formats for a zip code are: + * 12345 + * 12345-6789 + * 123456789 + * 12345 6789 + * + * If the argument passed to the ZipCode constructor does not + * conform to one of these patterns, an exception is thrown. + */ + +function ZipCode(zip) { + zip = new String(zip); + pattern = /[0-9]{5}([- ]?[0-9]{4})?/; + if (pattern.test(zip)) { + // giá trị zip code value sẽ là giá trị đầu tiên khớp trong string + this.value = zip.match(pattern)[0]; + this.valueOf = function() { + return this.value + }; + this.toString = function() { + return String(this.value) + }; + } else { + throw new ZipCodeFormatException(zip); + } +} + +function ZipCodeFormatException(value) { + this.value = value; + this.message = 'does not conform to the expected format for a zip code'; + this.toString = function() { + return this.value + this.message; + }; +} + +/* + * Đoạn script validate address theo kiểu US addresses. + */ + +const ZIPCODE_INVALID = -1; +const ZIPCODE_UNKNOWN_ERROR = -2; + +function verifyZipCode(z) { + try { + z = new ZipCode(z); + } catch (e) { + if (e instanceof ZipCodeFormatException) { + return ZIPCODE_INVALID; + } else { + return ZIPCODE_UNKNOWN_ERROR; + } + } + return z; +} + +a = verifyZipCode(95060); // returns 95060 +b = verifyZipCode(9560); // returns -1 +c = verifyZipCode('a'); // returns -1 +d = verifyZipCode('95060'); // returns 95060 +e = verifyZipCode('95060 1234'); // returns 95060 1234 +</pre> + +<h3 id="Rethrow_một_exception">Rethrow một exception</h3> + +<p>Chúng ta có thể sử dụng <code>throw</code> để rethrow một exception sau khi đã catch nó. Trong ví dụ sau, catch lại exception nếu là giá trị lớn hơn 50 thì rethrow. Exception này sẽ được đưa lên hàm trên một cấp hoặc lên trên cùng cho các hàm catch khác.</p> + +<pre class="brush: js">try { + throw n; // throws một exception với giá trị là số +} catch (e) { + if (e <= 50) { + // câu lệnh xử lý cho exception từ 1-50 + } else { + // không có xử lý cho trường hợp exception này, rethrow + throw e; + } +} +</pre> + +<h2 id="Specification">Specification</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Khởi tạo. Hiện thực trong JavaScript 1.4</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Trình_duyệt_hổ_trợ">Trình duyệt hổ trợ</h2> + + + +<p>{{Compat("javascript.statements.throw")}}</p> + +<h2 id="Xem_thêm">Xem thêm</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try...catch</code></a></li> +</ul> diff --git a/files/vi/web/javascript/reference/template_literals/index.html b/files/vi/web/javascript/reference/template_literals/index.html new file mode 100644 index 0000000000..3626937740 --- /dev/null +++ b/files/vi/web/javascript/reference/template_literals/index.html @@ -0,0 +1,238 @@ +--- +title: Template literals (Template strings) +slug: Web/JavaScript/Reference/Template_literals +translation_of: Web/JavaScript/Reference/Template_literals +--- +<div>{{JsSidebar("More")}}</div> + +<p>Mẫu nguyên thủy là chuỗi string nguyên thủy cho phép áp dụng vào các biểu thức. Bạn có thể sử dụng các chuỗi nhiều dòng và các chuỗi chức năng nội suy với chúng. Chúng được gọi là "chuỗi mẫu" trong các phiên bản trước của đặc tả ES2015.</p> + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox">`string text` + +`string text line 1 + string text line 2` + +`string text ${expression} string text` + +tag `string text ${expression} string text` +</pre> + +<h2 id="Mô_tả">Mô tả</h2> + +<p>Mẫu nguyên thủy được đóng bởi dấu 'nháy-ngược' (` `) (<a href="https://en.wikipedia.org/wiki/Grave_accent">grave accent</a> - nằm ở góc trái dưới phím Esc) thay vì sử dụng nháy đơn hoặc nháy kép. Mẫunguyên thủy có thể bao gồm placeholders (trong thẻ input có 1 thuộc tính placeholder). Chúng được biểu thị bằng ký hiệu đô la và dấu ngoặc nhọn (<code>${expression}</code>). Các biểu thức trong placeholders và văn bản giữa các dấu 'nháy-ngược' (` `) được đưa vào hàm. Hàm mặc định chỉ ghép các thành phần thành một chuỗi đơn. Nếu có một biểu thức thực hiện trước một mẫu nguyên thủy (<code>tag</code> - ở đây gọi là thẻ), thì được gọi là một "tagged template" (mẫu được gắn thẻ). Trong trường hợp này, biểu thức gắn thẻ (thường là một hàm) được gọi cùng với mẫu nguyên thủy, biểu thức mà sau đó bạn có thể thao tác trước khi trả ra kết quả. Để thoát dấu 'nháy-ngược' trong một mẫu nguyên thủy, hãy đặt dấu gạch chéo ngược \ trước dấu nháyngược (phần này nên note lại và cần tham khảo thêm các ví dụ sau).</p> + +<pre class="brush: js">`\`` === '`' // --> true</pre> + +<h3 id="Các_chuỗi_nhiều_dòng_chuỗi_đa_dòng">Các chuỗi nhiều dòng (chuỗi đa dòng)</h3> + +<p>Bất kỳ các dòng ký tự mới được chèn vào trong nguồn (mã nguồn) đều là một phần của mẫu nguyên thủy. Việc sử dụng các chuỗi mặc định, bạn sẽ phải sử dụng các cú pháp dưới đây để có được các chuỗi đa dòng (sử dụng ký tự \n):</p> + +<pre class="brush: js">console.log('string text line 1\n' + +'string text line 2'); +// "string text line 1 +// string text line 2"</pre> + +<p>Để có được kết quả tượng tự thì sử dụng cú pháp mẫu nguyên thủy, bạn có thể viết như sau:</p> + +<pre class="brush: js">console.log(`string text line 1 +string text line 2`); +// "string text line 1 +// string text line 2"</pre> + +<h3 id="Biểu_thức_nội_suy">Biểu thức nội suy</h3> + +<p>Để nhúng các thiểu thức (hàm, phép tính, ...) vào trong chuỗi mặc định, bạn sẽ sử dụng cú pháp dưới đây:</p> + +<pre class="brush: js">var a = 5; +var b = 10; +console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.'); +// "Fifteen is 15 and +// not 20."</pre> + +<p>Giờ đây, với các mẫu nguyên thủy, bạn có thể sử dụng các thay thế cú pháp như thế này để dễ đọc hơn:</p> + +<pre class="brush: js">var a = 5; +var b = 10; +console.log(`Fifteen is ${a + b} and +not ${2 * a + b}.`); +// "Fifteen is 15 and +// not 20."</pre> + +<h3 id="Các_mẫu_lồng_nhau_mẫu_nằm_trong_mẫu_khác">Các mẫu lồng nhau (mẫu nằm trong mẫu khác)</h3> + +<p>Trong một số trường hợp nhất định, lồng một mẫu là cách dễ nhất và có thể dễ đọc hơn để có các chuỗi có khả năng cấu hình. Bên trong một mẫu được tạo, nó đơn giản để cho phép các dấu nháy ngược bên trong chỉ đơn giản bằng cách sử dụng chúng trong một placeholder <code>${ }</code> bên trong mẫu. Ví dụ, nếu điều kiện đúng: thì trả về mẫu nguyên thủy.</p> + +<p>Trong ES5:</p> + +<pre class="brush: js">var classes = 'header' +classes += (isLargeScreen() ? + '' : item.isCollapsed ? + ' icon-expander' : ' icon-collapser'); +</pre> + +<p>Trong ES2015 với mẫu nguyên thủy và không đặt lồng nhau:</p> + +<pre class="brush: js">const classes = `header ${ isLargeScreen() ? '' : + (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;</pre> + +<p>Trong ES2015 với 2 mẫu nguyên thủy đặt lồng nhau:</p> + +<pre class="brush: js">const classes = `header $<strong>{</strong> isLargeScreen() ? '' : + `icon-${item.isCollapsed ? 'expander' : 'collapser'}`<strong> </strong><strong>}`</strong>;</pre> + +<h3 id="Các_mẫu_được_gắn_thẻ">Các mẫu được gắn thẻ</h3> + +<p>Một hình thức nâng cao hơn của mẫu nguyên thủy là các mẫu được gắn thẻ. Các thẻ cho phép bạn chuyển đổi các mẫu nguyên thủy sử dụng hàm. Tham số đầu tiên của hàm gắn thẻ bao gồm một mảng các chuỗi. Các tham số còn lại được gắn với các biểu thức. Cuối cùng, hàm của bạn có thể trả về chuỗi được thao tác (hoặc nó có thể trả về bất kỳ kết quả gì theo mục đích lập trình trong ví dụ tiếp theo). Tê của hàm được sử dụng cho thẻ bạn có thể đặt tên theo cách bạn muốn.</p> + +<pre class="brush: js">var person = 'Mike'; +var age = 28; + +function myTag(strings, personExp, ageExp) { + var str0 = strings[0]; // "That " + var str1 = strings[1]; // " is a " + + // There is technically a string after + // the final expression (in our example), + // but it is empty (""), so disregard. + // var str2 = strings[2]; + + var ageStr; + if (ageExp > 99){ + ageStr = 'centenarian'; + } else { + ageStr = 'youngster'; + } + + // We can even return a string built using a template literal + return `${str0}${personExp}${str1}${ageStr}`; +} + +var output = myTag`That ${ person } is a ${ age }`; + +console.log(output); +// That Mike is a youngster</pre> + +<p>Các hàm gắn thẻ không cần trả về một chuỗi, như được hiển thị ở ví dụ dưới đây.</p> + +<pre class="brush: js">function template(strings, ...keys) { + return (function(...values) { + var dict = values[values.length - 1] || {}; + var result = [strings[0]]; + keys.forEach(function(key, i) { + var value = Number.isInteger(key) ? values[key] : dict[key]; + result.push(value, strings[i + 1]); + }); + return result.join(''); + }); +} + +var t1Closure = template`${0}${1}${0}!`; +t1Closure('Y', 'A'); // "YAY!" +var t2Closure = template`${0} ${'foo'}!`; +t2Closure('Hello', {foo: 'World'}); // "Hello World!" +</pre> + +<h3 id="Các_chuỗi_chưa_xử_lý_chuỗi_thô">Các chuỗi chưa xử lý (chuỗi thô)</h3> + +<p>thuộc tính <code>raw</code> khá đặc biệt, có thể trong tham số đầu tiên để gán thẻ hàm, nó cho phép bạn truy cập các chuỗi thô như khi chúng được đưa vào, không cần sử lý <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings">escape sequences</a>.</p> + +<pre class="brush: js">function tag(strings) { + console.log(strings.raw[0]); +} + +tag`string text line 1 \n string text line 2`; +// logs "string text line 1 \n string text line 2" , +// including the two characters '\' and 'n' +</pre> + +<p>Ngoài ra, phương thức {{jsxref("String.raw()")}} tồn tại để tạo các chuỗi thô giống như hàm mẫu mặc định và chuỗi nối.</p> + +<pre class="brush: js">var str = String.raw`Hi\n${2+3}!`; +// "Hi\n5!" + +str.length; +// 6 + +str.split('').join(','); +// "H,i,\,n,5,!" +</pre> + +<h3 id="Mẫu_được_gắn_thẻ_và_trình_tự_thoát">Mẫu được gắn thẻ và trình tự thoát</h3> + +<h4 id="ES2016_behavior">ES2016 behavior</h4> + +<p>Trong ECMAScript 2016, các mẫu được gắn thẻ tuân theo quy tắc của các trình tự thoát sau đây:</p> + +<ul> + <li>Unicode escapes bắt đầu bởi "\u", ví dụ <code>\u00A9</code></li> + <li>Unicode code point escapes chỉ định bởi "\u{}", ví dụ <code>\u{2F804}</code></li> + <li>Hexadecimal escapes bắt đầu bởi "\x", ví dụ <code>\xA9</code></li> + <li>Octal nguyên thủy escapes bắt đầu bởi "\0o" và được gán thêm bằng một hay nhiều chữ số, ví dụ <code>\0o251</code></li> +</ul> + +<p>Điều này có nghĩa là một mẫu được gắn thẻ như sau là có vấn đề, bởi vì mỗi ngữ pháp ECMAScript, một phân tích trông như đúng trình tự Unicode escape:</p> + +<pre class="brush: js">latex`\unicode` +// Throws in older ECMAScript versions (ES2016 and earlier) +// SyntaxError: malformed Unicode character escape sequence</pre> + +<h4 id="ES2018_sửa_đổi_các_chuỗi_thoát_bất_hợp_pháp">ES2018 sửa đổi các chuỗi thoát bất hợp pháp</h4> + +<p>Các mẫu được gắn thẻ sẽ cho phép nhúng các ngôn ngữ (ví dụ <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSLs</a>, or <a href="https://en.wikipedia.org/wiki/LaTeX">LaTeX</a>), trong đó các chuỗi thoát khác là phổ biến. ECMAScript đề xuất <a href="https://tc39.github.io/proposal-template-literal-revision/">Template Literal Revision</a> (giai đoạn 4, được tích hợp trong tiêu chuẩn ECMAScript 2018) xóa giới hạn cú pháp của chuỗi thoát ECMAScript khỏi các mẫu được gắn thẻ.</p> + +<p>Tuy nhiên, các chuỗi thoát bất hợp pháp vẫn phải được giữ lại. Chúng sẽ hiển thị như thành phần {{jsxref("undefined")}} trong mảng “cooked”:</p> + +<pre class="brush: js">function latex(str) { + return { "cooked": str[0], "raw": str.raw[0] } +} + +latex`\unicode` + +// { cooked: undefined, raw: "\\unicode" }</pre> + +<p>Chú ý rằng hạn chế trình tự thoát chỉ được loại bỏ khỏi các mẫu được gắn thẻ chứ không phải từ các mẫu chữ không được đánh dấu:</p> + +<pre class="brush: js example-bad">let bad = `bad escape sequence: \unicode`;</pre> + +<h2 id="Thông_số_kỹ_thuật">Thông số kỹ thuật</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition. Defined in several section of the specification: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-template-literals">Template Literals</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tagged-templates">Tagged Templates</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in several section of the specification: <a href="https://tc39.github.io/ecma262/#sec-template-literals">Template Literals</a>, <a href="https://tc39.github.io/ecma262/#sec-tagged-templates">Tagged Templates</a></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.grammar.template_literals")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("String.raw()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="https://gist.github.com/WebReflection/8f227532143e63649804">Template-like strings in ES3 compatible syntax</a></li> + <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/">"ES6 in Depth: Template strings" on hacks.mozilla.org</a></li> + <li><a href="https://styled-components.com/">https://styled-components.com/</a></li> +</ul> diff --git a/files/vi/web/reference/api/index.html b/files/vi/web/reference/api/index.html new file mode 100644 index 0000000000..9701acb039 --- /dev/null +++ b/files/vi/web/reference/api/index.html @@ -0,0 +1,59 @@ +--- +title: Tài liệu tham khảo Web API +slug: Web/Reference/API +translation_of: Web/Reference/API +--- +<p><span class="seoSummary">Web cung cấp một loạt các API để thực hiện những công việc hữu ích khác nhau. Các API này có thể được truy cập bằng cách sử dụng mã JavaScript, cho phép bạn làm bất cứ điều gì trên Web, từ những điều chỉnh nhỏ cho tới bất kỳ {{domxref("window")}} hay là {{domxref("element")}}, để tạo ra những hiệu ứng đồ họa và âm thanh phức tạp với những API như <a href="/en-US/docs/Web/WebGL">WebGL</a> và <a href="/en-US/docs/Web_Audio_API">Web Audio</a>.</span></p> + +<p>Mỗi giao diện cá nhân trên tất cả các API đã được liệt kê tại <a href="/en-US/docs/Web/API">chỉ mục.</a></p> + +<p>Ngoài ra còn có một <a href="/en-US/docs/Web/Reference/Events">danh sách của tất cả các sự kiện có sẵn</a> trong tài liệu tham khảo sự kiện.</p> + +<div class="cleared topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/DOM">Document Object Model</a></dt> + <dd>DOM là một API cho phép truy cập và chỉnh sửa các tài liệu hiện hành. Nó cho phép thao tác tới {{domxref("Node")}} và {{domxref("Element")}} của tài liệu. HTML, XML và SVG đã mở rộng DOM để nó có thể thao tác được tới những phần tử cụ thể của chúng.</dd> + <dt>Những API thiết bị</dt> + <dd>Thiết lập từ những API này cho phép truy cập vào các tính năng phần cứng khác nhau có sẵn cho các trang Web và các phần mềm. Ví dụ: <a href="/en-US/docs/WebAPI/Using_Light_Events">API cảm biến ánh sáng</a>, <a href="/en-US/docs/WebAPI/Battery_Status" title="WebAPI/Battery_Status">API tình trạng pin</a>, <a href="/en-US/docs/Using_geolocation" title="Using_geolocation">API định vị</a>, <a href="/en-US/docs/WebAPI/Pointer_Lock" title="API/Pointer_Lock_API">API khóa con trỏ</a>, <a href="/en-US/docs/WebAPI/Proximity" title="WebAPI/Proximity">API tiệm cận</a>, <a href="/en-US/docs/WebAPI/Detecting_device_orientation" title="WebAPI/Detecting_device_orientation">API định hướng thiết bị</a>, <a href="/en-US/docs/WebAPI/Managing_screen_orientation" title="WebAPI/Detecting_device_orientation">API định hướng màn hình</a>, <a href="/en-US/docs/WebAPI/Vibration" title="WebAPI/WebBluetooth">API rung</a>.</dd> + <dt>Những API truyền tin</dt> + <dd>Là những API để cho các trang Web và các ứng dụng có thể kết nối, giao tiếp với các trang khác hoặc các thiết bị khác. Ví dụ: <a href="/en-US/docs/WebAPI/Network_Information" title="WebAPI/Network_Information">API thông tin mạng</a>, <a href="/en-US/docs/WebAPI/Using_Web_Notifications" title="/en-US/docs/WebAPI/Using_Web_Notifications">Thông báo Web (notifications)</a>, <a href="/en-US/docs/WebAPI/Simple_Push" title="WebAPI/Push_Notifications">API đẩy đơn giản (push)</a>.</dd> + <dt id="Data_management_APIs">Những API quản lý dữ liệu</dt> + <dd>Dữ liệu người dùng có thể được lưu trữ và quản lý bằng cách sử dụng các thiết lập của các API. Ví dụ: <a href="/en-US/docs/WebAPI/FileHandle_API" title="WebAPI/FileHandle_API">API xử lý file (fileHandle)</a>, <a href="/en-US/docs/IndexedDB" title="IndexedDB">IndexedDB</a>.</dd> +</dl> + +<p>Ngoài các API có sẵn cho bất kỳ trang Web hay ứng dụng nào, một tập các API mạnh hơn là có sẵn cho các ứng dụng đặc quyền và đã được chứng nhận.</p> + +<dl> + <dt>Những API đặc quyền</dt> + <dd>Một ứng dụng đặc quyền là một ứng dụng được cài đặt đã được trao quyền cụ thể từ người dùng. Các API đặc quyền bao gồm: <a href="/en-US/docs/WebAPI/TCP_Socket" title="WebAPI/TCP_Socket">TCP Socket API</a>, <a href="/en-US/docs/WebAPI/Contacts" title="WebAPI/Contacts">API liên hệ</a>, <a href="/en-US/docs/WebAPI/Device_Storage_API" title="WebAPI/Device_Storage_API">API lưu trữ dữ liệu</a>, <a href="/en-US/docs/DOM/Using_the_Browser_API" title="DOM/Using_the_Browser_API">API trình duyệt</a>, <a href="/en-US/docs/WebAPI/Camera" title="WebAPI/Camera">API máy ảnh</a>.</dd> + <dt>Những API chứng nhận</dt> + <dd>Một ứng dụng chấng nhận là một ứng dụng cấp thấp thực hiện những hoạt động quan trọng trong một hệ điều hành như Firefox OS. Có ít các ứng dụng đặc quyền tương tác với các ứng dụng này thông qua <a href="/en-US/docs/WebAPI/Web_Activities" title="WebAPI/Web_Activities">Web Activities</a>. Các ứng dụng chứng nhận bao gồm:<a href="/en-US/docs/WebAPI/WebBluetooth" title="WebAPI/WebBluetooth"> Bluetooth API</a>, <a href="/en-US/docs/WebAPI/Mobile_Connection" title="WebAPI/Mobile_Connection">API kết nối di động</a>, <a href="/en-US/docs/WebAPI/Network_Stats" title="WebAPI/Network_Stats">API thống kê số liệu mạng</a>, <a href="/en-US/docs/WebAPI/WebTelephony" title="WebAPI/WebTelephony">gọi điện</a>, <a href="/en-US/docs/WebAPI/WebSMS" title="WebAPI/WebSMS">WebSMS</a>, <a href="/en-US/docs/WebAPI/WiFi_Information" title="WebAPI/WiFi_Information">API thông tin wifi</a>, <a href="/en-US/docs/WebAPI/Power_Management" title="WebAPI/Power_Management">API quản lý năng lượng</a>, <a href="/en-US/docs/WebAPI/Settings" title="WebAPI/Settings">API cài đặt</a>, <a href="/en-US/docs/WebAPI/Idle" title="WebAPI/Device_Storage_API">API không hoạt động</a>, <a href="/en-US/docs/WebAPI/Permissions" title="WebAPI/Permissions">API quyền truy cập</a>, <a href="/en-US/docs/WebAPI/Time_and_Clock" title="WebAPI/Time_and_Clock">API ngày giờ</a>.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Community" id="Cộng_đồng">Cộng đồng</h2> + +<p>Tham gia cộng đồng Web API thông qua danh sách gửi thư hoặc nhóm thảo luận:</p> + +<ul> + <li><a class="external" href="https://lists.mozilla.org/listinfo/dev-webapi">qua danh sách gửi thư</a></li> + <li><a href="news://news.mozilla.org/mozilla.dev.webapi">qua một nhóm thảo luận</a></li> + <li><a class="external" href="http://groups.google.com/group/mozilla.dev.webapi">qua một nhóm Google</a></li> + <li><a class="external" href="http://groups.google.com/group/mozilla.dev.webapi/feeds">qua một nguồn cấp Web</a></li> +</ul> + +<p>Ngoài ra, hãy chắc chắn để tham gia vào các cuộc thảo luận trực tiếp ở kênh <a href="irc://irc.mozilla.org/webapi">#webapi</a> trên <a class="external" href="https://wiki.mozilla.org/IRC">IRC</a>.</p> + +<h2 class="Related_Topics" id="Bài_viết_liên_quan">Bài viết liên quan</h2> + +<p>Những bài viết sau đây có thể sẽ thú vị:</p> + +<ul> + <li><a href="/en-US/docs/Web/API">Danh sách tất cả các giao diện Web API</a></li> +</ul> +</div> +</div> + +<p> </p> diff --git a/files/vi/web/reference/index.html b/files/vi/web/reference/index.html new file mode 100644 index 0000000000..3e328a32a5 --- /dev/null +++ b/files/vi/web/reference/index.html @@ -0,0 +1,29 @@ +--- +title: Web technology reference +slug: Web/Reference +tags: + - Landing + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/Reference +--- +<p>{{draft()}}<br> + The open Web is built using a number of technologies that require an adequate knowledge in order to use them. Below you'll find the links to our reference material for each of them.</p> + +<h2 class="Documentation" id="Web_technologies">Web technologies</h2> + +<p>It is recommended that you already <a href="https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web">got started with the web</a>, however it isn't absolutely necessary.</p> + +<dl> + <dt><strong><a href="/en-US/docs/Glossary/HTML">HTML</a></strong> — structuring the Web</dt> + <dd>The <strong>HyperText Markup Language</strong> is used to define and describe semantically the content (<a href="/en-US/docs/Glossary/markup">markup</a>) of a Web page in a well-structured format.<br> + HTML provides a means to create structured documents, made up of blocks called <a href="/en-US/docs/Web/HTML/Element">HTML elements</a> that are delineated by <em><a href="/en-US/docs/Glossary/Tag">tags</a></em>, written using angle brackets: some introduce content into the page directly, others provide information about document text and may include other tags as sub-elements. Obviously, browsers do not display them, since they are used to interpret the content of the page.<br> + <br> + <a href="/en-US/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a> | <a href="/en-US/Learn/HTML">Learn HTML</a> | <a href="/en-US/docs/Web/Guide/HTML/HTML5">HTML5</a> | <a href="/en-US/docs/Web/Guide/HTML">Developer guide</a> | <a href="/en-US/docs/Web/HTML/Element">Element reference</a> | <strong><a href="/en-US/docs/Web/HTML/Reference">reference</a></strong></dd> + <dt><strong><a href="/en-US/docs/Glossary/CSS">CSS</a></strong> — styling the Web</dt> + <dd>The <strong>Cascading Style Sheets</strong> are used to describe the appearance of Web content.<br> + <br> + <a href="/en-US/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a> | <a href="/en-US/docs/Web/Guide/CSS/Getting_started">Getting started with CSS</a> | <a href="/en-US/Learn/CSS">Learn CSS</a> | <a href="/en-US/docs/Web/CSS/CSS3">CSS3 </a>| <a href="/en-US/docs/Web/Guide/CSS">Developer guide</a> | <a href="/en-US/docs/Web/CSS/Common_CSS_Questions">Common CSS questions</a> | <strong><a href="/en-US/docs/Web/CSS/Reference">reference</a></strong></dd> +</dl> diff --git a/files/vi/web/svg/index.html b/files/vi/web/svg/index.html new file mode 100644 index 0000000000..b342e1ceb9 --- /dev/null +++ b/files/vi/web/svg/index.html @@ -0,0 +1,94 @@ +--- +title: SVG +slug: Web/SVG +tags: + - 2D Graphics + - Graphics + - NeedsTranslation + - Reference + - SVG + - TopicStub + - Web + - 'l10n:priority' +translation_of: Web/SVG +--- +<div class="callout-box"><strong><a href="/en-US/docs/SVG/Tutorial">Getting Started</a></strong><br> +This tutorial will help get you started using SVG.</div> + +<p><span class="seoSummary"><strong>Scalable Vector Graphics (SVG)</strong> is an <a href="/en-US/docs/XML">XML</a>-based markup language for describing two-dimensional <a class="external" href="https://en.wikipedia.org/wiki/Vector_graphics">vector graphics</a>.</span> SVG is essentially to graphics what <a href="/en-US/docs/Web/HTML">HTML</a> is to text.</p> + +<p>SVG is similar to Adobe's proprietary Flash technology, but it is a text-based open Web standard instead of a closed binary format. It is explicitly designed to work with other web standards such as <a href="/en-US/docs/CSS">CSS</a>, <a href="/en-US/docs/DOM">DOM</a>, and <a href="/en-US/docs/Web/SVG/SVG_animation_with_SMIL">SMIL</a>.</p> + +<div class="cleared row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Documentation">Documentation</h2> + +<dl> + <dt><a href="/en-US/docs/Web/SVG/Element">SVG element reference</a></dt> + <dd>Details about each SVG element.</dd> + <dt><a href="/en-US/docs/Web/SVG/Attribute">SVG attribute reference</a></dt> + <dd>Details about each SVG attribute.</dd> + <dt><a href="/en-US/docs/DOM/DOM_Reference#SVG_interfaces">SVG DOM interface reference</a></dt> + <dd>Details about the SVG DOM API, for interaction with JavaScript.</dd> + <dt><a href="/en-US/docs/Web/SVG/Applying_SVG_effects_to_HTML_content">Applying SVG effects to HTML content</a></dt> + <dd>SVG works together with {{Glossary("HTML")}}, {{Glossary("CSS")}} and {{Glossary("JavaScript")}}. Use SVG to <a href="/en-US/docs/SVG_In_HTML_Introduction">enhance a regular HTML page or web application</a>.</dd> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/SVG">View All...</a></span></p> + +<h2 class="Community" id="Community">Community</h2> + +<ul> + <li>View Mozilla forums... {{DiscussionList("dev-tech-svg", "mozilla.dev.tech.svg")}}</li> +</ul> + +<h2 class="Tools" id="Tools">Tools</h2> + +<ul> + <li><a href="http://www.w3.org/Graphics/SVG/Test/">SVG Test Suite</a></li> + <li><a href="http://jiggles.w3.org/svgvalidator/">SVG Validator</a> (Discontinued)</li> + <li><a href="/en-US/docs/tag/SVG:Tools">More Tools...</a></li> + <li>Other resources: <a href="/en-US/docs/XML">XML</a>, <a href="/en-US/docs/CSS">CSS</a>, <a href="/en-US/docs/DOM">DOM</a>, <a href="/en-US/docs/HTML/Canvas">Canvas</a></li> +</ul> +</div> + +<div class="section"> +<h2 class="Related_Topics" id="Examples">Examples</h2> + +<ul> + <li>Google <a href="http://maps.google.com">Maps</a> (route overlay) & <a href="http://docs.google.com">Docs</a> (spreadsheet charting)</li> + <li><a href="http://starkravingfinkle.org/projects/demo/svg-bubblemenu-in-html.xml">SVG bubble menus</a></li> + <li><a href="http://jwatt.org/svg/authoring/">SVG authoring guidelines</a></li> + <li>An overview of the <a href="/en-US/docs/Mozilla_SVG_Project">Mozilla SVG Project</a></li> + <li><a href="/en-US/docs/SVG/FAQ">Frequently asked questions</a> regarding SVG and Mozilla</li> + <li><a href="/en-US/docs/SVG/SVG_as_an_Image">SVG as an image</a></li> + <li><a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SVG animation with SMIL</a></li> + <li><a href="http://plurib.us/1shot/2007/svg_gallery/">SVG art gallery</a></li> + <li>More samples (<a href="http://www.carto.net/papers/svg/samples/">carto.net</a>)</li> +</ul> + +<h3 id="Animation_and_interactions">Animation and interactions</h3> + +<p>Like HTML, SVG has a document model (DOM) and events, and is accessible from JavaScript. This allows developers to create rich animations and interactive images.</p> + +<ul> + <li>Some real eye-candy SVG at <a href="http://svg-wow.org/">svg-wow.org</a></li> + <li>Firefox extension (<a href="http://schepers.cc/grafox/">Grafox</a>) to add a subset of {{Glossary("SMIL")}} animation support</li> + <li>Interactive <a href="http://people.mozilla.com/~vladimir/demos/photos.svg">photos</a> manipulation</li> + <li><a href="http://starkravingfinkle.org/blog/2007/07/firefox-3-svg-foreignobject/">HTML transformations</a> using SVG's <code>foreignObject</code></li> +</ul> + +<h3 id="Mapping_charting_games_3D_experiments">Mapping, charting, games & 3D experiments</h3> + +<p>While a little SVG can go a long way to enhanced web content, here are some examples of heavy SVG usage.</p> + +<ul> + <li><a href="http://www.codedread.com/yastframe.php">Tetris</a></li> + <li><a href="https://web.archive.org/web/20131019072450/http://www.treebuilder.de/svg/connect4.svg" title="Archive link provided because source now requires authentication.">Connect 4</a></li> + <li><a href="http://www.carto.net/papers/svg/us_population/index.html">US population map</a></li> + <li><a href="http://www.treebuilder.de/default.asp?file=441875.xml">3D box</a> & <a href="http://www.treebuilder.de/default.asp?file=206524.xml">3D boxes</a></li> + <li><a href="http://jvectormap.com/">jVectorMap</a> (interactive maps for data visualization)</li> + <li><a href="http://jointjs.com">JointJS</a> (JavaScript diagramming library)</li> +</ul> +</div> +</div> diff --git a/files/vi/web/svg/tutorial/index.html b/files/vi/web/svg/tutorial/index.html new file mode 100644 index 0000000000..bc313966be --- /dev/null +++ b/files/vi/web/svg/tutorial/index.html @@ -0,0 +1,59 @@ +--- +title: SVG Tutorial +slug: Web/SVG/Tutorial +tags: + - Intermediate + - NeedsContent + - NeedsHelp + - NeedsTranslation + - NeedsUpdate + - SVG + - 'SVG:Tutorial' + - TopicStub +translation_of: Web/SVG/Tutorial +--- +<p>Scalable Vector Graphics, <a href="/en-US/Web/SVG" title="en-US/Web/SVG">SVG</a>, is a W3C XML dialect to mark up graphics. It is partially implemented in Firefox, Opera, WebKit browsers, Internet Explorer and other browsers.</p> + +<p>This tutorial aims to explain the internals of SVG and is packed with technical details. If you just want to draw beautiful images, you might find more useful resources at <a class="external" href="https://inkscape.org/en/learn/" title="http://inkscape.org/doc/">Inkscape's documentation page</a>. Another good introduction to SVG is provided by the W3C's <a class="external" href="http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html" title="http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html">SVG Primer</a>.</p> + +<div class="note">The tutorial is in an early stage of development. If you're able, please help out by chipping in and writing a paragraph or two. Extra points for writing a whole page!</div> + +<h5 id="Introducing_SVG_from_Scratch">Introducing SVG from Scratch</h5> + +<ul> + <li><a href="/en-US/Web/SVG/Tutorial/Introduction" title="en-US/Web/SVG/Tutorial/Introduction">Introduction</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Getting_Started" title="en-US/Web/SVG/Tutorial/Getting_Started">Getting Started</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Positions" title="en-US/Web/SVG/Tutorial/Positions">Positions</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Basic_Shapes" title="en-US/Web/SVG/Tutorial/Basic_Shapes">Basic Shapes</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Paths" title="en-US/Web/SVG/Tutorial/Paths">Paths</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Fills_and_Strokes" title="en-US/Web/SVG/Tutorial/Fills_and_Strokes">Fills and Strokes</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Gradients" title="en-US/Web/SVG/Tutorial/Gradients">Gradients</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Patterns" title="en-US/Web/SVG/Tutorial/Patterns">Patterns</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Texts" title="en-US/Web/SVG/Tutorial/Texts">Texts</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Basic_Transformations" title="en-US/Web/SVG/Tutorial/Basic_Transformations">Basic Transformations</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Clipping_and_masking" title="en-US/Web/SVG/Tutorial/Clipping_and_masking">Clipping and masking</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Other_content_in_SVG" title="en-US/Web/SVG/Tutorial/Other content in SVG">Other content in SVG</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Filter_effects" title="en-US/Web/SVG/Tutorial/Filter effects">Filter effects</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/SVG_fonts" title="en-US/Web/SVG/Tutorial/SVG fonts">SVG fonts</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/SVG_Image_Tag" title="en-US/Web/SVG/Tutorial/SVG Image Tag">SVG Image tag</a></li> + <li><a href="/en-US/Web/SVG/Tutorial/Tools_for_SVG" title="en-US/Web/SVG/Tutorial/Tools_for_SVG">Tools for SVG</a></li> + <li><a href="/en-US/docs/Web/SVG/Tutorial/SVG_and_CSS">SVG and CSS</a></li> +</ul> + +<p>The following topics are more advanced and hence should get their own tutorials.</p> + +<h5 id="Scripting_SVG_with_JavaScript">Scripting SVG with JavaScript</h5> + +<p>TBD</p> + +<h5 id="SVG_filters_tutorial">SVG filters tutorial</h5> + +<p>TBD</p> + +<h5 id="Animations_with_SMIL_in_SVG">Animations with SMIL in SVG</h5> + +<p>TBD</p> + +<h5 id="Creating_fonts_in_SVG">Creating fonts in SVG</h5> + +<p>TBD</p> diff --git a/files/vi/web/svg/tutorial/svg_image_tag/index.html b/files/vi/web/svg/tutorial/svg_image_tag/index.html new file mode 100644 index 0000000000..9b5c077b20 --- /dev/null +++ b/files/vi/web/svg/tutorial/svg_image_tag/index.html @@ -0,0 +1,32 @@ +--- +title: SVG image element +slug: Web/SVG/Tutorial/SVG_Image_Tag +translation_of: Web/SVG/Tutorial/SVG_Image_Tag +--- +<p>{{ PreviousNext("Web/SVG/Tutorial/SVG_Fonts", "Web/SVG/Tutorial/Tools_for_SVG") }}</p> + +<p>Element SVG {{ SVGElement("image") }} cho phép bạn hiển thị hình ảnh bên trong một object SVG:</p> + +<p>TRong ví dụ đơn giản này, một ảnh jpg được tham chiếu bởi một thuộc tính {{ SVGAttr("href") }} sẽ hiển thị bên trong một object SVG:</p> + +<pre class="brush: xml"><?xml version="1.0" standalone="no"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" + "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg width="5cm" height="4cm" version="1.1" + xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink"> + <image href="firefox.jpg" x="0" y="0" height="50px" width="50px"/> +</svg></pre> + +<p>Đây là một vài điều quan trọng bạn cần lưu ý (được tham khảo từ <a class="external" href="http://www.w3.org/TR/SVG/struct.html#ImageElement" title="http://www.w3.org/TR/SVG/struct.html#ImageElement">W3 specs</a>):</p> + +<ul> + <li> + <p>Nếu bạn không đặt giá trị cho thuộc tính x hoặc y thì chúng sẽ có giá trị mặc định là 0.</p> + </li> + <li> + <p>Nếu bạn không đặt giá trị cho thuộc tính height hoặc width thì chúng sẽ có giá trị mặc định là 0.</p> + </li> + <li>Nếu thuộc tính height hoặc width có có giá trị là 0, image sẽ không được render(không hiển thị).</li> +</ul> + +<p>{{ PreviousNext("Web/SVG/Tutorial/SVG_Fonts", "Web/SVG/Tutorial/Tools_for_SVG") }}</p> diff --git a/files/vi/web/tutorials/index.html b/files/vi/web/tutorials/index.html new file mode 100644 index 0000000000..8beb00b838 --- /dev/null +++ b/files/vi/web/tutorials/index.html @@ -0,0 +1,238 @@ +--- +title: Hướng dẫn +slug: Web/Tutorials +translation_of: Web/Tutorials +--- +<p>Những đường dẫn trong trang này sẽ đưa bạn đến với những hướng dẫn và các tài liệu luyện tập.<strong>Dù bạn vừa mới bắt đầu, đang học những bài vỡ lòng, hoặc là một nhà phát triển web kỳ cựu, bạn luôn có thể tìm được những tài nguyên hữu ích để làm tốt công việc của mình.</strong> Những tài nguyên này được tạo ra bởi những công ty luông hướng về tương lai và các nhà phát triển web.Họ là những người nắm giữ những ngôn ngữ mở và các bài thực hành phát triển web tốt nhất. Chính họ đã tài trợ và cho phép chuyển ngữ qua giấy phép nội dung mở và bản quyền miễn phí Creative Commons</p> + +<h2 id="Cho_những_ai_hoàn_toàn_mới_với_Web">Cho những ai hoàn toàn mới với Web</h2> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web">Làm quen với Web</a></dt> + <dd><em>Làm quen với Web</em> là một chuỗi các bài viết xúc tích, thực tế giới thiệu về phát triển web. Bạn sẽ thiết đặt các công cụ cần thiết để xây dựng một trang web và chạy những dòng code đơn giản</dd> +</dl> + +<h2 class="Documentation" id="Documentation" name="Documentation">HTML Tutorials</h2> + +<h3 id="Cấp_độ_nhập_môn">Cấp độ nhập môn</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Giới thiệu về HTML</a></dt> + <dd>Đây là bước nền tảng, giúp bạn làm quen với các khái niệm và cú pháp, cách áp dụng HTML vào văn bản, tạo những siêu dẫn , và cách sử dụng HTML để cấu trúc một trang web</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/HTML/Element">MDN Danh sách phần tử HTML</a></strong></dt> + <dd>Một danh sách phần tử HTML hoàn chỉnh và cách các trình duyệt khác nhau hỗ trợ chúng</dd> + <dt><strong><a href="https://www.theblogstarter.com/html-for-beginners">Tạo một Trang Web đơn giản với HTML</a>(The Blog Starter)</strong></dt> + <dd>An HTML guide for beginners that includes explanations of common tags, including HTML5 tags. Also includes a step-by-step guide to creating a basic web page with code examples.</dd> + <dt><strong><a href="http://wikiversity.org/wiki/Web_Design/HTML_Challenges" rel="external">HTML Challenges</a> (Wikiversity)</strong></dt> + <dd>Sử dụng những thử thách này để mài dũa kỹ năng HTML của bạn (Ví dụ, "Tôi có nên dùng phần tử <h2> hay một phần tử <strong>?"), hãy sử dụng chúng có chủ ý.</dd> +</dl> +</div> +</div> + +<h3 id="Intermediate_level">Intermediate level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding">Multimedia and embedding</a></dt> + <dd>This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt> </dt> + <dt><a href="/en-US/docs/Learn/HTML/Tables">HTML tables</a></dt> + <dd>Representing tabular data on a webpage in an understandable, {{glossary("Accessibility", "accessible")}} way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries.</dd> +</dl> +</div> +</div> + +<h3 id="Advanced_level">Advanced level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Forms">HTML forms</a></dt> + <dd>Forms are a very important part of the Web — these provide much of the functionality you need for interacting with web sites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side parts of forms.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/Tips_for_Authoring_Fast-loading_HTML_Pages">Tips for authoring fast-loading HTML pages</a></strong></dt> + <dd>Optimize web pages to provide a more responsive site for visitors and reduce the load on your web server and Internet connection.</dd> +</dl> +</div> +</div> + +<h2 class="Documentation" id="Documentation" name="Documentation">CSS Tutorials</h2> + +<h3 id="Introductory_level">Introductory level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics">CSS basics</a></dt> + <dd>CSS (Cascading Style Sheets) is the code you use to style your webpage. <em>CSS Basics</em> takes you through what you need to get started. We'll answer questions like: How do I make my text black or red? How do I make my content show up in such-and-such a place on the screen? How do I decorate my webpage with background images and colors?</dd> + <dt><a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a></dt> + <dd>This module goes in depth with how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/CSS/Styling_boxes">Styling boxes</a></dt> + <dd>Next up, we look at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model then look at controlling box layouts by setting padding, borders and margins, setting custom background colors, images and other features, and fancy features such as drop shadows and filters on boxes.</dd> + <dt><a href="/en-US/docs/Learn/CSS/Styling_text">Styling text</a></dt> + <dd>Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/Common_CSS_Questions">Common CSS Questions</a></strong></dt> + <dd>Common questions and answers for beginners.</dd> +</dl> +</div> +</div> + +<h3 id="Intermediate_level_2">Intermediate level</h3> + +<div class="row topicpage-table" style="width: 100%;"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout">CSS layout</a></dt> + <dd>At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_Reference">CSS reference</a></strong></dt> + <dd>Complete reference to CSS, with details on support by Firefox and other browsers.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="http://www.alistapart.com/articles/fluidgrids/" rel="external">Fluid Grids</a> (A List Apart)</strong></dt> + <dd>Design layouts that fluidly resize with the browser window, while still using a typographic grid.</dd> + <dt><strong><a href="http://en.wikiversity.org/wiki/Web_Design/CSS_challenges" rel="external">CSS Challenges</a> (Wikiversity)</strong></dt> + <dd>Flex your CSS skills, and see where you need more practice.</dd> +</dl> +</div> +</div> + +<h3 id="Advanced_level_2">Advanced level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><strong><a href="/en-US/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms">Using CSS transforms</a></strong></dt> + <dd>Apply rotation, skewing, scaling, and translation using CSS.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_transitions">CSS transitions</a></strong></dt> + <dd>CSS transitions, part of the draft CSS3 specification, provide a way to animate changes to CSS properties, instead of having the changes take effect instantly.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="http://www.html5rocks.com/tutorials/webfonts/quick/" rel="external">Quick Guide to Implement Web Fonts with @font-face</a> (HTML5 Rocks)</strong></dt> + <dd>The @font-face feature from CSS3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way.</dd> + <dt><strong><a href="http://davidwalsh.name/starting-css" rel="external">Starting to Write CSS</a> (David Walsh)</strong></dt> + <dd>An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS.</dd> +</dl> +</div> +</div> + +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas tutorial</a></dt> + <dd>Learn how to draw graphics using scripting using the canvas element.</dd> + <dt><strong><a href="http://html5doctor.com/" rel="external">HTML5 Doctor</a></strong></dt> + <dd>Articles about using HTML5 right now.</dd> +</dl> +</div> + +<h2 class="Documentation" id="Documentation" name="Documentation">Javascript Tutorials</h2> + +<h3 id="Introductory_level_2">Introductory level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt> </dt> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a></dt> + <dd>In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key JavaScript features in detail, such as variables, strings, numbers and arrays.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks">JavaScript building blocks</a></dt> + <dd>In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics">Getting started with JavaScript</a></dt> + <dd>What is JavaScript and how can it help you?</dd> + <dt><strong><a href="http://www.codecademy.com/">Codecademy</a> (Codecademy)</strong></dt> + <dd>Codecademy is a easy way to learn how to code JavaScript. It's interactive and you can do it with your friends.</dd> +</dl> +</div> +</div> + +<h3 id="Intermediate_level_3">Intermediate level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects">Introducing JavaScript objects</a></dt> + <dd>In JavaScript, most things are objects, from core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs</a></dt> + <dd>When writing client-side JavaScript for web sites or applications, you won't go very far before you start to use APIs — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. In this module we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work. </dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/A_re-introduction_to_JavaScript">A re-Introduction to JavaScript</a></strong></dt> + <dd>A recap of the JavaScript programming language aimed at intermediate-level developers.</dd> + <dt><strong><a href="http://eloquentjavascript.net/" rel="external">Eloquent JavaScript</a></strong></dt> + <dd>A comprehensive guide to intermediate and advanced JavaScript methodologies.</dd> + <dt><strong><a href="http://speakingjs.com/es5/" rel="external">Speaking JavaScript</a> (Dr. Axel Rauschmayer)</strong></dt> + <dd>For programmers who want to learn JavaScript quickly and properly, and for JavaScript programmers who want to deepen their skills and/or look up specific topics.</dd> + <dt><strong><a href="http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/" rel="external">Essential JavaScript Design Patterns</a> (Addy Osmani)</strong></dt> + <dd>An introduction to essential JavaScript design patterns.</dd> +</dl> +</div> +</div> + +<h3 id="Advanced_level_3">Advanced level</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></dt> + <dd>A comprehensive, regularly updated guide to JavaScript for all levels of learning from beginner to advanced.</dd> + <dt><strong><a href="https://github.com/getify/You-Dont-Know-JS" rel="external">You Don't Know JS</a> (Kyle Simpson)</strong></dt> + <dd>A series of books diving deep into the core mechanisms of the JavaScript language.</dd> + <dt><strong><a href="http://bonsaiden.github.com/JavaScript-Garden/" rel="external">JavaScript Garden</a></strong></dt> + <dd>Documentation of the most quirky parts of JavaScript.</dd> + <dt><strong><a href="http://exploringjs.com/es6/" rel="external">Exploring ES6</a> (Dr. Axel Rauschmayer)</strong></dt> + <dd>Reliable and in-depth information on ECMAScript 2015.</dd> +</dl> +</div> + +<div class="section"><strong><a href="http://shichuan.github.io/javascript-patterns" rel="external">Javascipt Patterns</a></strong> + +<dl> + <dd>A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM.</dd> + <dt><strong><a href="http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/">How browsers work</a></strong></dt> + <dd>A detailed research article describing different modern browsers, their engines, page rendering etc.</dd> + <dt><a href="https://github.com/bolshchikov/js-must-watch">JavaScript Videos</a> (GitHub)</dt> + <dd>A collection of JavaScript videos to watch.</dd> +</dl> +</div> +</div> + +<h3 id="Extension_Development">Extension Development</h3> + +<div class="row topicpage-table" style="width: 100%;"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions">WebExtensions</a></dt> + <dd>WebExtensions is a cross-browser system for developing browser add-ons. To a large extent the system is compatible with the <a class="external-icon external" href="https://developer.chrome.com/extensions">extension API</a> supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/extensions/">Microsoft Edge</a> with <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Porting_from_Google_Chrome">just a few changes</a>. The API is also fully compatible with <a href="https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox">multiprocess Firefox</a>.</dd> +</dl> +</div> +</div> |