Chia sẻ kiến thức IT ứng dụng: AI, Backend, Frontend, Full Stack, DevOps & Cloud, and More.

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, July 5, 2017

How to parse JSON (infotable) element names via JavaScript


To pull the object names out of a JSON object, iterate through the JSON object and display the value at each index location

  • Example:
    var myJson = {
    "element1": "hello",
    "element2": 12,
    "element3": true,
    "element4": {
        "subelement1": "one",
        "sebelement2": 2
    }};
     
    for (var el in myJson) {
        console.log("Element name: " + el + ", element value:" + myJson[el] + ", element type: " + typeof(myJson[el]));
    }

JSON array
  • Example:
    var propertiesPort = ['port1', 'port2', 'port3', 'port4', 'port5', 'port6', 'port7', 'port8', 'port9', 'port10', 'port11', 'port12' ];
    for(var i = 0; i<propertiesPort .length; i++){

                    var portName = propertiesPort [i];

    }

    hoặc:

    for
     each (row in thingList.rows) { 
        //Now each row is already assigned to the row variable in the loop
        var thingName = row.name;
    } 

Thursday, February 23, 2017

JavaScript căn bản - part 2


1. JavaScript Array splice() Method


Definition and Usage
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Note: This method changes the original array.

Syntax
array.splice(index, howmany, item1, ....., itemX)

Parameter Values

ParameterDescription
indexRequired. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
howmanyOptional. The number of items to be removed. If set to 0, no items will be removed
item1, ..., itemXOptional. The new item(s) to be added to the array
Return Value: A new Array, containing the removed items (if any)

Example

At position 2, add the new items, and remove 1 item:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");
=> result = Banana,Orange,Lemon,Kiwi,Mango

Example

At position 2, remove 2 items:
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.splice(2, 2);

Example

At position 2, remove 0 items and add 2 items:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "abc" , "Kiwi");
=> result = [Banana,Orange,abc,Kiwi,Apple,Mango]

2. valueOf() Method

<script>
function myFunction() {
    var str = "Hello World!";
    var res = str.valueOf();
    document.getElementById("demo").innerHTML = res;
}
</script>

3. Set and Map

Set:
mySet[Symbol.iterator]

Return value

The Set iterator function, which is the values() function by default.

Example:
vm.fileSetUpload = new Set();
var rmID = $('#btnRemoveSetupFileSrv').val();
vm.fileSetUpload.add(rmID.valueOf());
const iterator1 = vm.fileSetUpload[Symbol.iterator]();
vm.arrRmAttachFile = [];
for (var v of vm.fileSetUpload) {
    vm.arrRmAttachFile.push(v);
}         
Map:
vm.filesMapUpload = new Map();
for (var i = 0; i < e.length; i++) {
    vm.filesMapUpload.set(e[i].name, e[i]);
   
}
var fNames = '';
vm.filesMapUpload.forEach(function(value, key, map) {
    fNames = fNames + key + ":";
});
var rmID = $('#btnRemoveSetupFileCli').val();
vm.filesMapUpload.delete(rmID);
vm.filesArrayUpload = [];
vm.filesMapUpload.forEach(function(value, key, map) {
       vm.filesArrayUpload.push(value);
});

4.Reduce method

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

link:
https://www.freecodecamp.org/news/reduce-f47a7da511a9/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce


5.Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.


REF:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


Wednesday, December 7, 2016

JavaScript căn bản - part 1

1. Javascript là gì?

Javascript là ngôn ngữ lập trình của HTML và Web  chạy trên browser dưới dạng các script.


A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
  • Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
    The window object represents an open window in a browser.
  • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
  • Form object − Everything enclosed in the <form>...</form> tags sets the form object.
  • Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes. They have events, attributes, styles.
Here is a simple hierarchy of a few important objects -

Closures: Một số link tham khảo về Closures là

2. Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:
   1. HTML to define the content of web pages
   2. CSS to specify the layout of web pages
   3. JavaScript to program the behavior of web pages

3. Ví dụ 1: JavaScript can change HTML content

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

<!DOCTYPE html>
<html>
<body>
​
<h1>My First JavaScript</h1>
​
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
​
<p id="demo"></p>
​
</body>
</html> 

4. Ví dụ 2: JavaScript can change CSS style

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>


</body>

</html> 

5. Ví dụ 3: JavaScript can change HTML attributes

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>

</html>
<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>


</body>

</html> 
Tương tự, để hiển thị phần tử đang ở trạng thái hidden thì dùng đặt style.display='block'

7. Ví dụ 5: JavaScript với sự kiện onchange

<html>
<head>
<script type="text/javascript"> 
function updateInputValue(ishVal){
// ID of current element
var elementID = document.getElementById('CurrentUnitId').value;
document.getElementById(elementID).value = ishVal;
}

function updateTextBox(textboxID) {
//var txtID = document.getElementById(textboxID);
var orgID = document.getElementById('organizationSearchName');
orgID.value = '';
document.getElementById('CurrentUnitId').value = textboxID;
var tempElement = document.createElement("markActionURL");
tempElement.type = "hidden";
tempElement.value = '${actionUrl}';
document.getElementById('CommonTagsTreeChooserUnitID').appendChild(tempElement);
openTreeChooserDialog('organizationSearch','${actionUrl}');

}

function updateInput(ish){
   document.getElementById("fieldname").value = ish;
}

</script>

</head>
<body>
<input type="text" name="fieldname" id="fieldname" />  
<input type="text" name="thingy" onchange="updateInput(this.value)" />
</body>

</html>

this.value là value của phần tử đang xét.

8. Ví dụ 6: JavaScript chạy trưc tiếp một hàm cùng với trang web

Dùng đoạn mã sau nhúng vào body của trang html:
<script type="text/javascript">javascript:changeColumnWidthR2();</script>

khi load trang web, browser sẽ gọi hàm changeColumnWidthR2()。

Nội dung của hàm changeColumnWidthR2
<script type="text/javascript">
function changeColumnWidthR2(){
    $('#ColumnLabelEmployeeName').attr('style','width: 15%');
    $('#ColumnLabelCompany).attr('style','width: 35%');
    $('#ColumnLabelPosition').attr('style','width: 15%');
    $("#Output_Other_Help").html("<font color='red'><center>Click checkbox để chọn organization.</center></font>");
}
</script>


Ngoài ra, có thể gọi những hàm javascript mà không cần tới prefix javascript:
ví dụ:
<script>
    focusTextboxElement("frmSearch");
    pressSearchButton();

</script>

9. Điều kiện true/false với 1 biến số

var inputValue = null | undefined | NaN | empty string ("") | 0 | false
if(inputValue)
  alert('false');
else
  alert('true value');
=> trả về giá trị false cho biến số inputValue.

10. What does this mean: "undefined object property"?


What does this mean: "undefined object property"?
Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

var o = { a: undefined }
Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false
We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

11. JSON - check an Integer variable is valid

if(!(zoneId % 1 === 0)) {
    isZoneIdValid = false;
    result.code = 422;
    result.message = "zoneid = " + zoneId + " khong hop le";
}

if(jsonInput.maxItems >= 0)
    maxItems = jsonInput.maxItems;

12. JSON - check empty in javascript

- function isEmpty(value){
    return (typeof value === "undefined" || value === null || value.length === 0 || value === "undefined");
}
- hasOwnProperty
if(jsonInput.hasOwnProperty('maxItems')) {}


PHỔ BIẾN

CHUYÊN MỤC

TỔNG LƯỢT XEM