I'm going through a porting exercise going from JavaScript to TypeScript and have hit the following issue.
In the original JavaScript code I've got:
var children = someJQueryElement.children('div');
var sortedChildren = children.sort(someSortFunction);
In TypeScript (1.4) all the jQuery methods return JQuery which isn't an array and therefore can't have sort called on it.
How should I go about solving this?
As an idea, have you tried to tell TypeScript to treat it as an array using casting?
var children = someJQueryElement.children('div');
var sortedChildren = (<Array>children).sort(someSortFunction);
This seems like a fairly tedious solution, though, if you have to do this in many places. Hopefully someone has a better answer.
You can change to a normal array using .get()
children.get().sort(someSortFunction);
You can use Array.slice.apply to pass in the array-like object and convert it to a proper array.
var children = [].slice.apply(someJQueryElement.children('div'));
This is also a useful practice if you're not using jQuery but want to convert any other array-like objects, like arguments, for example.
Related
I've been trying to store data for multiple entities, so I thought a good way to organize it like I did in AS3 would be to store it under another variable, like
StoreInventories.Shellys
and then perform array methods on them as needed,
Eg:
StoreInventories.Shellys.push ("Stuff")
But this doesn't seem to work, something about
TypeError: StoreInventories.Shellys.push is not a function
that the console keeps spitting out. How am I supposed to get this functionality?
Sorry if I'm abusing terms - jargon isn't my strong suit and I haven't undergone any formal training.
Method push() is defined for Array class. So you need to create an array first.
Here is the code:
var StoreInventories = {};
StoreInventories.Shellys = [];
StoreInventories.Shellys.push("Stuff");
says I've this :
var user = [{'id':1,'gender':'male'},{'id':2,'gender':'female'}]
I want to use push() to insert
'owner':true
into the first array so that it become like this
var user = [{'id':1,'gender':'male','owner':true},{'id':2,'gender':'female'}]
I tried
user[0].push({'owner':true});
but it doesn't work tht way.
#Kim Gysen gave you a solution that works. I think you're getting the logic between Arrays and Objects confused I just wanted to give you a solution using only JavaScript that may help you understand just what's going on here. Using libraries like jQuery are a great way to save time but for you I think it would be helpful to have a more comprehensive understanding.
user[0]['owner'] = true;
In the code above you are accessing your array by the 0th index which in this case is "'id':1" and adding a new property to it using Bracket Notation. Another way to do this would be using Dot Notation:
user[0].owner = true;
Think about the process of adding a property to an object:
var myObj = {};
myObj['newKey'] = "I'm a new value";
myObj['newKey2'] = "I'm an even newer value!";
The reason I gave you an answer is it may seem convenient to use jQuery but understanding JavaScript principles and syntax will help you out in the long run. Some good resources for you I'd suggest are CodeSchool and CodeAcademy
You are not pushing an object into an array, you are pushing an object into an object.
You can do this by using jquery's extend method.
var object = $.extend({}, object1, object2);
I've got an array, and it's got a method I threw onto it called add, which I use as a wrapper around push. I've found myself using push a few times when I should have used add, and now I'm thinking it would be nice to assign a reference to my add method to the array's native push. Thus, calling push on the array would call add.
Do internals depend on externally available native methods like push? How would this affect compatibility? Is this a bad idea? If so, why?
Some code:
PR.state = {
views: []
};
_.extend(PR.state.views, {
add: function(view) {
var parent = view.parent;
if ((!this.length && view instanceof PR.Views.App) || (parent && _.contains(this, parent)))
this.push(view);
}
});
// I am thinking:
PR.state.views.push = PR.state.views.add;
I would strongly advise against changing the behavior of a standard array method. If you really want a custom method, then just create a new method and give it it's own unique name and use that.
Changing the behavior of existing methods could have all sorts of bad consequences:
Incompatibility with code retrieved from any other source.
Creates a non-standard and unexpected implementation if anybody else ever works on this project. This is like adding in a time bomb to trip up some future developer.
Training yourself to use your own custom method instead of .push() is just something that a decent developer would do. Just do it.
Creating a newly named method with an appropriate and descriptive name improves the readability, understandability and maintainability of your code. Replacing an existing method with something that works differently does the opposite.
It's not so bad if you just replace the method on one instance of an array, not the whole array prototype, but it's still not a good idea.
What a stupid question. If I replace push with add, then what happens when I call push from add? :< :< I haven't tested it, but I suspect that while Array.prototype.push will still be available, unless I use Array.prototype.push explicitly, calling add will result in a mondo endless loop.
This might be a noob question, but I'm wondering if there's a way to select a json object without having to loop through key value pairs. I've done similar things with e4x, but I'm not sure how to do it syntactically for js. For example
var data = { "objects":[
{"foo":"x","bar":"a"},
{"foo":"y","bar":"b"}
]}
So instead of a for loop, some way to declare
var someObject = data.objects[where objects.foo == x]
You may do that w/o manually iterate over data, but some code should iterate over object anyway (so doesn't expect lightning speed on rather large objects).
There's a library for that: jsonpath
This question was asked two years ago before jsonQ. jsonQ allows us to write code to find siblings, traverse trees etc. without having to write a bunch of loops inside loops. While the question wanted a way to find it in native JS, I think my 2-year-old question is a bit naive now. I was really looking for a library like jsonQ to avoid writing a bunch of ugly loops (though I could do the work myself).
I was searching and just found this: https://github.com/lloyd/JSONSelect. I haven't tried it yet but it seems to be a good choice.
The question is old, but may this answer can help someone.
To select an item from list, you can use Javascript filter function:
var data = { "objects":[
{"foo":"x","bar":"a"},
{"foo":"y","bar":"b"}
]}
var someobject = filterObject('x');
function filterObject(fooValue) {
return data.objects.filter(function(item) {
return item.foo == fooValue;
}
}
I want to know if it is possible to declare an array in Javascript of the type "com.peregrine.servicecenter.PWS.Common.MessageType". In java it is easy but in javascript I have not idea. Thanks.
sure it's possible:
var myArray = [];
remember that javascript is not a statically typed language, so you don't need to declare an array of a specific type.... just an array. Now, given the type you're referring to, I don't think that's exactly what you're asking though...
No, it is not possible. The Array in JS doesn't care what you've put in it, or even that the array indexes are numeric. Java, on the other hand, requires strict typing of both. I'd even go so far as to say that even Object[] is a completely different paradigm from [].
You cannot declare an array to exclusively consist of a particular type. However, you can declare an array (var myArray = [];) and you can add objects of your intended type to it (myArray.push(myMessageType);).
You can declare the array in such a way.
var arr = [];
it can contain object or array of object by calling
arr.push(x)
Reference
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Array functions in jQuery