Array.js Test
by liuxiangchao
HTML
<script type="text/javascript">
function test() {
[1, 2, 3].$each(function (k, v) {
pp_log("index:" + k + " value:" + v);
});
}
function pp_log(message) {
var box = $("#log-box");
box.append("<p>" + message + "</p>");
};
setTimeout(test, 1000);
</script>
<div id="log-box">
</div>
CSS
#log-box p {
line-height: 1.5;
padding: 0;
margin: 0;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,"Fira Sans","Droid Sans","Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
border: 1px #ccc soid;
}
JavaScript
/**
* Array.js - v0.0.1
*
* - $contains(v) / $include(v)
* - $removeValue(v)
* - $remove(index)
* - $removeIf(fn)
* - $keepIf(fn)
* - $replace(newValues)
* - $clear()
* - $each(fn)
* - $unique(fn)
* - $get(index)
* - $getAll(index1, index2, ...) / $getAll(indexes1, indexes2, ...)
* - $first()
* - $last()
* - $set(index, value)
* - $copy()
* - $isEmpty()
* - $all(fn)
* - $any(fn)
* - $map(fn) / $collect(fn)
* - $reduce(fn)
* - $find(fn)
* - $findAll(fn) / $filter(fn)
* - $reject(fn)
* - $grep(pattern)
* - $keys(value, strict) / $indexesOf(value, strict)
* - $sort(compare)
* - $rsort(compare)
* - $arsort(compare)
* - $diff(array2)
* - $intersect(array2)
* - $max(compare)
* - $min(compare)
* - $swap(index1, index2)
* - $sum(fn)
* - $product(fn)
* - $pad(value, size)
* - $fill(value, length)
* - $shuffle()
* - $rand(size)
* - $size() / $count()
* - $push(value1, value2, ...)
* - $pushAll(array2)
* - $insert(index, obj1, ...)
* - $asc(field)
* - $desc(field)
* - $asJSON(field)
* - Array.$range(start, end, step)
* - Array.$isArray(obj)
*
* @author 刘祥超 <[email protected]>
*/
/**
* 判断数组中是否包含某个值
*/
Array.prototype.$contains = function (v) {
var that = this;
if (that == null) {
return false;
}
for (var i = 0; i < that.length; i++) {
if (that[i] == v) {
return true;
}
}
return false;
};
/**
* 同$contains(v)
*/
Array.prototype.$include = function (v) {
var that = this;
if (that == null) {
return false;
}
return that.$contains(v);
};
/**
* 从数组中删除某个值
*/
Array.prototype.$removeValue = function (v) {
var that = this;
if (that == null) {
return true;
}
var newArray = [];
for (var i = 0; i < that.length; i++) {
if (that[i] != v) {
newArray.push(that[i]);
}
}
that.$clear();
that.$pushAll(newArray);
return true;
};
/**
* 从数组中删除某个位置上的值
*/
Array.prototype.$remove = function (index) {
var that = this;
if (that == null) {
return true;
}
that.splice(index, 1);
return...