what is happening in following javascript function - javascript

below i have given a javascript code picture `` can any one help me in this code. what do this code. help me in this
function(){
var _ = function()
// The arguments object is an array-like object. It has a length property
// that corresponds to the number of arguments passed into the function
{
var r={},a=arguments;
for(var i=0; i<a.length; i+=2)
r[a[i]]=a[i+1];
return r;
}
}

Here's an example of the script in use with some arguments.
var _ = function() {
var r = {};
var a = arguments;
for(var i=0; i<a.length; i+=2) {
r[a[i]]=a[i+1];
}
console.log(r);
return r;
}
_('a','1','b','2');

The outer function does not make much sense but the inner function named '_' does this essentially _(1,2,3,4) function call will return {1:2,3:4}. Basically, odd arguments are keys and even arguments are values of the returned json object

Function _ converts list of arguments into object
_(name1, value1, name2, value2, ...)
// returns { name1: value1, name2: value2, ... }

Related

May someone help me why my console returns only 0 when i input this data in console? [duplicate]

In PHP there is func_num_args and func_get_args, is there something similar for JavaScript?
For modern Javascript or Typescript:
class Foo {
reallyCoolMethodISwear(...args) { return args.length; }
}
function reallyCoolFunction(i, ...args) { return args[i]; }
const allHailTheLambda = (...args) => {
return args.constructor == Array;
};
const x = new Foo().reallyCoolMethodISwear(0, 1, 2, 3, 4);
const y = reallyCoolFunction(3, 0, 1, 2, 3, 4, 5, 6);
const z = allHailTheLambda(43110, "world");
console.log(x, y, z); // 5 3 true
For ancient Javascript:
Use arguments. You can access it like an array. Use arguments.length for the number of arguments.
The arguments is an array-like object (not an actual array). Example function...
function testArguments () // <-- notice no arguments specified
{
console.log(arguments); // outputs the arguments to the console
var htmlOutput = "";
for (var i=0; i < arguments.length; i++) {
htmlOutput += '<li>' + arguments[i] + '</li>';
}
document.write('<ul>' + htmlOutput + '</ul>');
}
Try it out...
testArguments("This", "is", "a", "test"); // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9); // outputs [1,2,3,4,5,6,7,8,9]
The full details: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
ES6 allows a construct where a function argument is specified with a "..." notation such as
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
The arguments object is where the functions arguments are stored.
The arguments object acts and looks like an array, it basically is, it just doesn't have the methods that arrays do, for example:
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
Array.slice(begin[, end])
Array.indexOf(searchElement[, fromIndex])
I think the best way to convert a arguments object to a real Array is like so:
argumentsArray = [].slice.apply(arguments);
That will make it an array;
reusable:
function ArgumentsToArray(args) {
return [].slice.apply(args);
}
(function() {
args = ArgumentsToArray(arguments);
args.forEach(function(value) {
console.log('value ===', value);
});
})('name', 1, {}, 'two', 3)
result:
> value === name
> value === 1
> value === Object {}
> value === two
> value === 3
You can also convert it to an array if you prefer. If Array generics are available:
var args = Array.slice(arguments)
Otherwise:
var args = Array.prototype.slice.call(arguments);
from Mozilla MDN:
You should not slice on arguments because it prevents optimizations in
JavaScript engines (V8 for example).
As many other pointed out, arguments contains all the arguments passed to a function.
If you want to call another function with the same args, use apply
Example:
var is_debug = true;
var debug = function() {
if (is_debug) {
console.log.apply(console, arguments);
}
}
debug("message", "another argument")
Similar answer to Gunnar, with more complete example:
You can even transparently return the whole thing:
function dumpArguments(...args) {
for (var i = 0; i < args.length; i++)
console.log(args[i]);
return args;
}
dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });
Output:
foo
bar
true
42
["yes","no"]
{"banana":true}
https://codepen.io/fnocke/pen/mmoxOr?editors=0010
Yes if you have no idea that how many arguments are possible at the time of function declaration then you can declare the function with no parameters and can access all variables by arguments array which are passed at the time of function calling.
In ES6 you can do something like this:
function foo(...args)
{
let [a,b,...c] = args;
console.log(a,b,c);
}
foo(1, null,"x",true, undefined);
Hope this helps:
function x(...args) {
console.log( {...[...args] } );
}
x({a:1,b:2}, 'test');
Output:
{ '0': { a: 1, b: 2 }, '1': 'test' }
Hope this could be the helpful code:
function lazyLoadIcons(){
for(let i = 0; i < arguments.length; i++) {
var elements = document.querySelectorAll(arguments[i]);
elements.forEach(function(item){
item.classList.add('loaded');
});
}
}
lazyLoadIcons('.simple-2col', '.ftr-blue-ad', '.btm-numb');
~ Rahul Daksh
In ES6, use Array.from:
function foo()
{
foo.bar = Array.from(arguments);
foo.baz = foo.bar.join();
}
foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"
For non-ES6 code, use JSON.stringify and JSON.parse:
function foo()
{
foo.bar = JSON.stringify(arguments);
foo.baz = JSON.parse(foo.bar);
}
/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]
/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]
If preservation is needed instead of stringification, use the internal structured cloning algorithm.
If DOM nodes are passed, use XMLSerializer as in an unrelated question.
with (new XMLSerializer()) {serializeToString(document.documentElement) }
If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.
References
Structure Clone CommonJS Module
JS Object Clone
MDN: Array.from()

Iterating over an array of functions

I have the following JavaScript code:
function f(){
}
var arrOfFuncs = [f, f, f, f];
for (var i in arrOfFuncs){
console.log(typeof i);
console.log(i);
}
When I run the script it prints:
string
0
string
1
...
string
3
Since I am iterating over an array of functions, isn't "typeof i" supposed to be "function" and i.toString() supposed to be "function f(){}"?
No. The for…in construct iterates over the keys of an object or array, not its values.
You can use a simple for loop:
for (var i = 0; i < arrOfFuncs.length; i++){
console.log(typeof arrOfFuncs[i]);
console.log(arrOfFuncs[i]);
}
Or modify your for…in loop like this:
for (var i in arrOfFuncs){
console.log(typeof arrOfFuncs[i]);
console.log(arrOfFuncs[i]);
}
Or you could use the forEach method (introduced in ECMAScript 5.1):
arrOfFuncs.forEach(function(f) {
console.log(typeof f);
console.log(f);
});
When you iterate over keys of an object with for(var in in ...) i will equal the key - in the case of an array you are getting the indices as well as properties of the array (0, 1, 2, length, etc) and the type of that index or property key might very well be a string.
You want to access the value of the array at that key, so you need to do arrOfFuncs[i] - that said, it is probably better to use either .forEach or some equivalent if you can or use
for (var i = 0, l = arrOfFuncs.length; i < l; i++) {
var value = arrayOfFuncs[i];
}
Because you avoid the risk of accessing properties on the array you don't intend to access.
in your code i is the key it's not value. so your code should be like this to get function type:
function f(){
}
var arrOfFuncs = [f, f, f, f];
for (var i in arrOfFuncs){
console.log(typeof arrOfFuncs[i]);
console.log(arrOfFuncs[i]);
}
When you use for..in you are running over keys and not over values.
Read about JavaScript for..in loops.
This code will do what you want:
function f(){
}
var arrOfFuncs = [f, f, f, f];
for (var i in arrOfFuncs){
console.log(typeof arrOfFuncs[i]);
console.log(i);
}
JSFIDDLE
in for in iteration over arrays, i doesn't represent the element, it represents the index.
the below code works:
var array = [function f(){}, function k(){}];
for (var i in array) {
console.log(array[i]); //function()
console.log(typeof array[i]); //function
}

D3.csv accessor function for loop

I have a csv with many rows and I want to manipulate the data in accessor function before visualizing it. In every example I have seen so far this function returns something like that:
return {
key1: value1,
key2: value2,
key3: value3
...
};
An I want to use for loop to avoid writing every key-value pair manually like this (I know it's not valid but it represents the idea)
d3.csv("data/vitoAgeScrpdNew3x.csv", function(d) {
return {
for (var i=0;i<d3.keys(d).length; i++){
d3.keys(d)[i]: +d3.values(d)[i]
}
};
}
How to make this properly? Thanks!
UPDATE:
Tried for..in. Returns just one property
for(var prop in d) {
return {
prop: d[prop]
}
};
You need to create and fill with values an object you want to return beforehand, i.e.:
d3.csv("data/vitoAgeScrpdNew3x.csv", function(d) {
myObj = {};
for (var i=0;i<d3.keys(d).length; i++) {
myObj[ d3.keys(d)[i] ] = +d3.values(d)[i];
}
return myObj;
}

Passing Variable Number of arguments in javascript function argument-list

Can I pass a variable number of arguments into a Javascript function? I have little knowledge in JS. I want to implement something like the following:
function CalculateAB3(data, val1, val2, ...)
{
...
}
You can pass multiple parameters in your function and access them via arguments variable. Here is an example of function which returns the sum of all parameters you passed in it
var sum = function () {
var res = 0;
for (var i = 0; i < arguments.length; i++) {
res += parseInt(arguments[i]);
}
return res;
}
You can call it as follows:
sum(1, 2, 3); // returns 6
Simple answer to your question, surely you can
But personally I would like to pass a object rather than n numbers of parameters
Example:
function CalculateAB3(obj)
{
var var1= obj.var1 || 0; //if obj.var1 is null, 0 will be set to var1
//rest of parameters
}
Here || is logical operator for more info visit http://codepb.com/null-coalescing-operator-in-javascript/
A Is there a "null coalescing" operator in JavaScript? is a good read
Yes, you can make it. Use variable arguments like there:
function test() {
for(var i=0; i<arguments.length; i++) {
console.log(arguments[i])
}
}

string as object reference to object variable

var string = 'object.data.path';
That's a string that resembles a path to variable.
How can I return the corresponding variable from that string?
Something like transforming the string into return object.data.path;
The thing behind this is that the string could be much longer (deeper), like:
var string = 'object.data.path.original.result';
function GetPropertyByString(stringRepresentation) {
var properties = stringRepresentation.split("."),
myTempObject = window[properties[0]];
for (var i = 1, length = properties.length; i<length; i++) {
myTempObject = myTempObject[properties[i]];
}
return myTempObject;
}
alert(GetPropertyByString("object.data.path"));
this assumes that your first level object (in this case called object is global though.
Alternatively, although not recommended, you could use the eval function.
Assuming you don't want to just use eval you could try something like this:
function stringToObjRef(str) {
var keys = str.split('.'),
obj = window;
for (var i=0; i < keys.length; i++) {
if (keys[i] in obj)
obj = obj[keys[i]];
else
return;
}
return obj;
}
console.log(stringToObjRef('object.data.path.original.result'));
Uses a for loop to go one level down at a time, returning undefined if a particular key in the chain is undefined.

Categories

Resources