Skip to content

Instantly share code, notes, and snippets.

@lizzie
Created June 6, 2013 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizzie/5721493 to your computer and use it in GitHub Desktop.
Save lizzie/5721493 to your computer and use it in GitHub Desktop.
remove array item dynamically by each
<!doctype html>
<html>
<head>
<title>Test Each</title>
<script src="http://assets.spmjs.org/seajs/seajs/2.0.0/sea.js"></script>
</head>
<body>
<script>
(function () {
seajs.config({
alias:{
"$":'jquery/jquery/1.7.2/jquery-debug',
"_":'gallery/underscore/1.4.4/underscore'
}
});
seajs.use(["$", "_"], function ($, _) {
console.log("$.each ------------");
var arr1 = [10, 20, 30, 40, 50],
arr2 = [10, 20, 30, 40, 50],
arr3 = [10, 20, 30, 40, 50],
arr4 = [10, 20, 30, 40, 50],
arr5 = [10, 20, 30, 40, 50];
$.each(arr1, function (i, v) { // $.each 缓存了 arr1.length
console.log(i, v);
erase(v, arr1);
});
console.log(arr1);
console.log("element.each ------------");
// jQuery 对象, 把 array 中的值全部缓存了一遍
// 当前的 v 值不是从 arr2 中取到的
$(arr2).each(function (i, v) {
console.log(i, v);
erase(v, arr2);
});
console.log(arr2);
console.log("for/for in ------------");
for (var i = 0; i<arr3.length; i++) {
console.log(i, arr3[i]);
erase(arr3[i], arr3);
}
console.log(arr3);
// https://github.com/documentcloud/underscore/blob/master/underscore.js#L77
console.log("_.each/Array.prototype.forEach ------------");
_.each(arr4, function(v, i) {
console.log(i, v);
erase(v, arr4);
});
console.log(arr4);
console.log("backward ------------");
for (var i = arr5.length - 1; i>=0; i--) {
console.log(i, arr5[i]);
erase(arr5[i], arr5);
}
console.log(arr5);
function erase(target, array) {
for (var i = 0; i < array.length; i++) {
if (target === array[i]) {
//delete array[i]
array.splice(i, 1);
return array;
}
}
}
});
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment