Friday, December 12, 2014

Array like object in JavaScript

"Array like object" is look like Array.
Has index to access elements.
Has length property.
But they do not have Array's methods like push(), pop(), splice(), sort() etc

Example : arguments is an array like object

function myFunction() {
console.log(arguments); // ["one", "two", "three"]
console.log(arguments.length); // 3
}
myFunction("one", "two", "three");
view raw gistfile1.js hosted with ❤ by GitHub



arguments -> ["one", "two", "three"]
0 -> "one"
1 -> "two"
2 -> "three"
length -> 3
view raw gistfile1.js hosted with ❤ by GitHub

"Array like object" do not have Array's methods but we can invoke Array's methods explicitly.

function myFunction() {
Array.prototype.push.call(arguments, "four");
console.log(arguments) // ["one", "two", "three", "four"]
console.log(arguments.length) // 4
console.log(arguments[3]) // "four"
}
myFunction("one", "two", "three");
view raw gistfile1.js hosted with ❤ by GitHub

See the link of example
Array like object in JavaScript

No comments:

Post a Comment