2014年4月15日 星期二

【jQuery】Remove item from json array

var jsonArray = [
    {name: 'Alice', id: 001},
    {name: 'Bob', id: 002},
    {name: 'Namei', id: 003}
];

假設想刪除 jsonArray 其中一個 json 物件, 該如何實作?

function findAndRemove(array, property, value) {
    for (var key in array) {
        if (array[key][property] == value) {
            array.splice(key, 1);
        }
    }
}
/* remove a json object with property of 'name' whose value is 'Namei' */
findAndRemove(jsonArray, 'name', 'Namei');

splice 為 JavaScript Array 的一個 Method
定義為: The splice() method adds/removes items to/from an array, and returns the removed item(s).
Add's Parameter: array.splice(index, howmany, item1, ....., itemX)
index 指定插入元素於陣列的位置; howmany 插入多少元素; item 為插入元素
Remove's Parameter: array.splice(index, howmany)
index 若為負值,則表示距離陣列尾端的位置; howmany: If set to 0, no items will be removed.

2014年4月7日 星期一

【CSS】:nth-child v.s. jQuery:eq

之前沒研究清楚,
誤以為 CSS's :nth-child  跟 jQuery's :eq
兩者的 selector 是相同效果,
但其實這兩者之間定義不完全相同。

先來看看 jQuery's :eq( index ) 的定義,
Reduce the set of matched elements to the one at the specified index.
如果 index 為正值,則是以 0 對映到首個element;
   index 為負值,則從最後一個element計數。

再來看看 CSS's :nth-child( n ) 的定義,
The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.
n can be a number, a keyword, or a formula.
差異在於 CSS 會先找其parent的所有child element,再判斷是否符合條件。

舉例而言:
<div>
    <p>This is a heading</p>
    <div id="one" class="foo"></div>
    <div id="two" class="foo"></div>
    <div id="three" class="foo"></div>
</div>
以CSS Syntax來講, .foo:nth-child(2) 會找到 div#one ,
因為 #one 是容器內第二個元素,類別也符合條件。
但若 .foo:nth-child(1) 則找不到符合的元素,
因為容器內第一個元素是 p tag ,但卻不符合類別的條件。
補充 jQuery's :nth-child 定義,
Selects all elements that are the nth-child of their parent.
另外 jQuery's implementation of :nth- selectors is strictly derived from the CSS specification
所以 jQuery's :eq 只回傳第一個符合條件的元素;
而 jQuery's :nth-child 則會回傳所有符合條件的元素。