var c=$('<canvas></canvas>')[0].getContext('2d')
for(m in c){console.log(m)}
This prints a list of methods in CanvasRenderingContext2D. How can I do the same for an Array. I want to get "splice", "pop", "push", etc. Obviously for(m in Array.prototype){console.log(m)} won't work.
Most methods and properties of built-in objects are internally marked as non-enumerable, so they will not be enumerated in a for-in loop.
ECMAScript 5 has an Object.getOwnPropertyNames method that returns an array of all property names, so you can do:
Object.getOwnPropertyNames(Array.prototype)
but this isn't supported by all browsers yet.
Do this:
for (m in Array) {
console.log(m)
}
Output:
from
type
implement
extend
alias
mirror
$family
$constructor
pop
push
reverse
shift
sort
splice
unshift
concat
join
slice
indexOf
lastIndexOf
filter
forEach
every
map
some
reduce
reduceRight
each
clone
invoke
clean
associate
link
contains
append
getLast
getRandom
include
combine
erase
empty
flatten
pick
hexToRgb
rgbToHex
overloadSetter
overloadGetter
hide
protect
apply
call
attempt
pass
delay
periodical
create
bind
bindWithEvent
run
I have no idea how to do it with plain js. I usually have underscorejs loaded ant it have an it have a function that returns all the functions of an object
http://documentcloud.github.com/underscore/#functions
You could check underscorejs code to check how they do it.
Related
I'm relatively new to javascript and very new to jquery.
I have noticed that the jquery set returned by jQuery() selector shares a lot of similarities with javascript array e.g. elements in the jquery set can be accessed by the square bracket [] syntax
So I was wondering, is there any foundamental difference between jquery set and javascript array? Or they can be thought of as two ways of representing the same thing?
From their own docs (found here):
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().
So a jquery object is sort of array like, but it's not an array. Basically, an array will have methods the jquery object lacks, and the jquery object has methods that arrays lack. I would generally try not to treat the jquery objects as arrays, and instead try to use a jquery method whenever tempted to use an array method (ie, use .each instead of the array method .forEach).
EDIT:
After reading more about the jquery objects, they do share a lot of methods with arrays, such as .find. Moreover, it also provides a .toArray method which can be used to convert the jquery object into an actual javascript array.
As the person who was responsible for this jQuery feature, I thought I would share some historical notes.
If you study the jQuery API, you may notice something odd: the object returned by $()/jQuery() is not only an "array-like" object with a .length property and [i] access to its elements, but it also has a couple of fairly redundant methods: .get(i) and .size().
.get(i) is very similar to an array's [i]: it returns one of the elements of the jQuery array/object. And .size() is the same as .length.
In fact, if you look at the implementation of .size() you will see that it simply returns the .length property:
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
There is a little more to .get(). If you don't pass an argument, it is the same as .toArray(), and if you do pass an argument it allows both positive and negative indexes. Negative indexes count backwards from the end of the array similar to Python or Ruby.
But for the simple case of a non-negative index, .get(i) boils down to:
// Get the Nth element in the matched element set
get: function( num ) {
return this[ num ];
},
Why all this redundancy? .size() and .get(i) just do the same thing as the usual .length or [i], so why have both?
In the very first jQuery release in January 2006 (long before 1.0), the object returned by $() was not an "array-like" object. It was just a JavaScript object with .get(i) and .size() methods. The actual list of DOM elements was a separate "private" property of the jQuery object, and you were supposed to use those methods to access its elements and length.
As I worked with that initial jQuery release, it seemed a bit clumsy to have to call .get(i) and .size() to access the elements of the returned jQuery object. This object seemed to be a lot like an array, but you couldn't access its elements the same way as a normal array. So I thought, why not make it act more like a real array with [i] and .length?
It was a fairly simple change to do that, so we ran with it, but we kept the old .get(i) and size() methods for compatibility with code that already used those.
Now a confession: I don't remember the reason for making the return object an array-like object instead of directly inheriting from Array. (It was 11 years ago after all!)
We would have preferred making this object an actual array, but there was a good reason why that would work. Perhaps I will remember after sleeping on it, but in the meantime, this is how we got to the place where the jQuery return object is "array-like" but not a true array.
A jQuery object is a wrapper around an array of DOM elements. So a "jQuery array" is a jQuery object.
There are a few loops in javascript including forEach, some, map, and reduce. However, from what I currently understand, none of these are appropriate if you want to iterate through an array and return the value of a particular index. It seems like I am pretty much left with the standard for loop only. Is that true?
So for instance, if I have an array of objects... and I would like to find the index of the item with a particular value... could I use anything other than the regular for loop?
Array.prototype.findIndex() , as suggested by #Andreas in comments.
You can pass in a function to findIndex() method and define your equality criteria in that function.
It will return the index of first array element, that satisfies the equality criteria defined in your function.
There is also the for ... of ...:
for (variable of iterable) {
statement
}
You can use a JavaScript library http://underscorejs.org. It have plenty of functions. for your purpose you can use _.indexOf . it will eturns the index at which value can be found in the array
example:
var data=[1, 2, 3];
var index= _.indexOf(data, 2);
out put will be 1
Array.prototype.findIndex() or Array.prototype.indexOf() like everyone said.
You could use foreach() rather than regular for.It is the simplest and you can iterate and get the index. For more info: JavaScript Array forEach() Method
I have a nested object e.g:
data.object = [Object],[Object],[Object],[Object]
I want to completely remove the 3rd Object, so data.object[2] should no longer exist and I should see:
data.object = [Object],[Object],[Object]
Using delete retains the 3rd object but as undefined:
data.object = [Object],[Object],undefined,[Object]
I understand that _.omit can be used in a similar way but my attempts do not work:
_.omit(data.object,data.object[2])
No need to use underscore or any other third party library
data.object.splice(2, 1);
There is a standard JS function for that. It mutates the given array in-place, and removes the 1 element at the index 2.
References:
Array.prototype.splice()
One of my friends uses [].slice.call() to fill an array with matched elements.
I wonder how this works. I just know the Array.prototype.push to fill an array.
Also I have seen there is a difference in both techniques to fill an array.
So my questions are:
How does Array.prototype.slice help to fill an array?
What are the roles of Array.prototype.slice and Array.prototype.push to make objects and arrays?
Fiddle
var arr=[];
var arr=[].slice.call($('[id^=name]'));
//arr.push($('[id^=name]'))
console.log(arr)
The .slice() method of arrays returns a shallow copy of a portion of an array. It's written as a method on the Array prototype, so the array it operates on is the array in whose context it's invoked. Normally that'd be something like this:
var newArray = oldArray.slice(2, 4);
When you call the .slice() method with .call(), you can control the value of this explicitly. In your friend's code, he's passing a jQuery object as the this value. Because there are no other parameters, .slice() returns a shallow copy of the jQuery object in its entirety, as a new array. (Like some other similar methods, .slice() will work on anything that looks like an array: basically, anything that has a .length property and numerically-indexed properties of interest. A jQuery object fits that description.)
However, since jQuery already has a built-in method to return a plain array of all matched elements, your friend should not bother doing that anymore:
var plainArray = $('[id^=name]').get();
That does exactly the same thing. Using .slice() isn't wrong, but it's kind-of pointless.
How about $('[id^=name]').get()?
The [].slice.call method leverages the array-like length and numeric key properties of jQuery objects to re-use the intentionally generic methods of Array.prototype. The method Array.prototype.slice is documented by the standard to return a new Array object by performing a specific algorithm that accesses numeric-keyed properties in sequence of the this object - regardless of its type - assigning the values to sequential elements of the new Array.
I wouldn't use either approach, because jQuery has get(), which is documented to return an array of the elements matched. Why use a more obscure or less direct approach?
I does't have any specified reason for this case, but The thing i know is, .slice() also used to create another instance of an array, And here the slice add a space to its instance because it have no parameters.
Javascript is the language where you perform a Single operations in 1000's of different ways ! its depend on your choice!
But, We must have to follow the syntax that is made for particular operation.
I am writing an Array-derived class in JavaScript and need to know which functions to overload so that I can be aware of changes made to the array.
I know Array.push() and Array.splice() are mutating. Is there a definitive list of any others?
You can find the list on MDN as Mutator methods (along with Accessor and Iteration methods):
copyWithin
fill
pop
push
reverse
shift
sort
splice
unshift
You can also use .concat(), before using your mutation method, to ensure you are not mutating your arrays, eg
const dontMutateMe = [4,5,1,2,3];
const sortArray = dontMutateMe.concat().sort(...)
I found this website called Doesitmutate
Have the list of all functions - and tells whether it mutates or not.