I think that this is not possible in JS but I thought I would double check before moving on.
I have created a simple prototype on my array object, its purpose is to sort the array by a key value.
The function is working correctly however I want to make it a bit more reusable, by passing in a key into the function. However when I pass in a value it is a string so does not reference correctly. Does any one know how to solve this problem so in my example below I can sort by the passed in key1 not the hard-coded key1.
My code is this and a fiddle is up here http://jsfiddle.net/9KLk8/1/
Array.prototype.keySort=function(key1)
{
this.sort(function(a,b) {return (a.height > b.height) ? 1 : ((b.height > a.height) ? -1 : 0);} );
}
var a1 = [
{ key: 1, height : 100 },
{ key: 2, height: 700 },
{ key: 3, height: 200 }
];
a1.keySort("height");
console.log(a1);
Use the brackets syntax:
Array.prototype.keySort=function(key1)
{
this.sort(function(a,b) {return (a[key1] > b[key1]) ? 1 : ((b[key1] > a[key1]) ? -1 : 0);} );
}
Jsfiddle: http://jsfiddle.net/2hb4K/
Yes, you can do this, because with JavaScript, you can access properties either with dotted notation and a literal ( a.height
), or with bracketed notation and a string ( a["height"]
). In the latter case, the string doesn't have to be a literal string, it can be the result of any expression, including a variable reference.
So a[key1]
would access the property named by the key1
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.