<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery map & grep</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
function Product(category, name) {
this.category = category;
this.name = name;
}
var items = [
new Product("Phone", "iPhone4S"),
new Product("Phone", "Lumia 920"),
new Product("Phone", "小米"),
new Product("Pad", "Nexus7"),
new Product("Pad", "iPad")
];
//範例一:取得產品名稱字串陣列
var names = [];
for (var i = 0; i < items.length; i++) {
names.push(items[i].name);
}
//同場加映:JSON.stringify時傳入額外參數加上縮排
alert(JSON.stringify(names, null, 4));
//範例二:篩選手機類的產品陣列
var phones = [];
$.each(items, function(i, item) {
if (item.category == "Phone")
phones.push(item);
});
alert(JSON.stringify(phones, null, 4));
//jQuery改良版
//範例三:取得產品名稱字串陣列$.map()
var names = $.map(items, function(item) {
return item.name;
});
alert(JSON.stringify(names, null, 4));
//範例四:篩選手機類的產品陣列$.grep()
var phones = $.grep(items, function(item) {
return item.category == "Phone";
});
alert(JSON.stringify(phones, null, 4));
</script>
</body>
</html>