[英]How can you add a function to all objects in a JavaScript array?
I am using Angular, but basically my controller has an array of objects that are returned from an AJAX query via HTTP, and I want to decorate each object in the array with a function to prettify a boolean property on the object so it renders as Yes/No instead of true/false. 我使用的是Angular,但是基本上我的控制器有一个对象数组,这些对象是通过HTTP从AJAX查询返回的,并且我想用一个函数修饰数组中的每个对象,以对该对象的布尔属性进行修饰,使其呈现为Yes。 / No代替true / false。 I don't mind using jQuery or Angular, if there's a way to do this with either of them.
我不介意使用jQuery或Angular,如果有一种方法可以使用它们之一。
You can do something like this: 您可以执行以下操作:
function prettify(prop){
if(prop) return "Yes"
else return "No"
}
$.each(arr, function(index, item) {
item.myFunction = prettify;
});
If you actually want to add a method to each object instance, you can simply expando them: 如果您确实想向每个对象实例添加一个方法,则只需展开它们即可:
$.each(theArray, function(i, obj) {
obj.prettyBool = function() {
return obj.theProperty ? 'Yes' : 'No';
};
});
loop through your array and for each item in the array assign an event listener to it with a handler function. 遍历数组,并使用处理程序函数为数组中的每个项目分配一个事件侦听器。
$.each(myArray, function(index, item) {
item.on('event', eventHandlerFunction);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.