javascript literal initialisation loop
I have an object which has several properties that are set when the object is created.
This object recently changed to object literal notation, but I've hit a bit of a problem that searching on the net doesn't reveal.
Simply stated I need to do this:
Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
var self = {
id: _id,
// other properties
links: [],
for (var i=0,j=0;i<8;i++) { //<- doesn't like this line
var k = parseInt(_links[i]);
if (k 开发者_开发技巧> 0) {
this.links[j++] = k;
}
},
// other methods
};
return self;
};
How do I initialise a property in the constructor in object literal notation?
You can create the array on the fly using an anonymous function:
Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) { var self = { id: _id, // other properties links: (function() { var a = []; for (var i=0;i<8;i++) { var k = parseInt(_links[i]); if (k > 0) { a.push(k); } } return a; })(), // other methods }; return self; };
You can do it after the literal is defined:
Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) { var self = { id: _id, // other properties links: [], // other methods }; for (var i=0,j=0;i<8;i++) { var k = parseInt(_links[i]); if (k > 0) { self.links[j++] = k; } } return self; };
For this specific example, you could use an anonymous function, like this:
Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
var self = {
id: _id,
// other properties
links: (function(){
var links = [];
for (var i=0;i<8;i++) {
var k = parseInt(_links[i]);
if (k > 0) {
links.push(k);
}
}
return links;
})(),
// other methods
};
return self;
};
You can't. Object notation doesn't allow this. However, you can add the properties AFTER initializing your object.
By the way, self
is a defined object already, which is an alias for the window object. While you ARE defining a temporary object named self [and thus, you aren't getting rid of window.self] this isn't something you shold be doing. Act as if self
was a keyword and your current usage of it is illegal.
精彩评论