Array.prototype.orderby=function()
{
let self=this;
let arr=[self[0]], i=1;
for(;i<self.length; i++)
{
let index=arr.findIndex(f=>f > self[i]);
arr.splice(index==-1?arr.length: index, 0, self[i]);
}
return arr;
}
Array.prototype.orderdescby=function()
{
let self=this;
let arr=[self[0]], i=1;
for(;i<self.length; i++)
{
let index=arr.findIndex(f=>f < self[i]);
arr.splice(index==-1?arr.length:index,0,self[i]);
}
return arr;
}
const points = [40, 100, 1, 500, 25, 107,0];
console.log(points.orderby())
console.log(points.orderdescby())
Thursday, 18 July 2024
Wednesday, 17 July 2024
Javascript String extend for new function.
Javascript String extend for new function.
First Approch:
Second Approch:
First Approch:
String.prototype.toArray=function(){
let arr=[];
for(let ch of this){
arr.push(ch);
}
return arr;
}
let name="suresh";
console.log(name.toArray()); //output [ 's', 'u', 'r', 'e', 's', 'h' ]
Second Approch:
String.prototype.toArray=function(){
return this.split('');
}
let name="suresh";
console.log(name.toArray()); //output [ 's', 'u', 'r', 'e', 's', 'h' ]
Difference between functions and methods in JavaScript:
JavaScript Functions:
- A function is a block of code designed to perform a specific task.
- It can be defined using the
functionkeyword, followed by a name and optional parameters. - The body of the function is enclosed in curly braces.
- Functions are executed when something calls or invokes them.
- Example:
function addName(a, b) { return a + " " + b; } console.log(addName("Suresh", "Sharma")); // Output: Suresh Sharma
JavaScript Methods:
- A method is a function associated with an object.
- It is a property of an object that contains a function definition.
- Methods are functions stored as object properties.
- They can be accessed using the following syntax:
object.methodName(). - Methods operate on the data contained in a class (i.e., the object it belongs to).
- Example:
let employee = { empname: "Suresh Sharma", department: "Software", details: function () { return this.empname + " works in "+ this.department +"Department."; }};
In summary:
- A function can stand alone and be called directly by its name.
- A method is a function associated with an object property.
- Methods implicitly pass the object on which they were called.