Passing an array as parameter in JavaScript - javascript

I have an array, and I want to pass it as a parameter in a function such as:
function something(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i].value);
}
}
I'm getting that arrayP[0] is undefined, which might be true as inside the function I never wrote what kind of array arrayP is. So,
Is is possible to pass arrays as parameters?
If so, which are the requirements inside the function?

Just remove the .value, like this:
function(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i]); //no .value here
}
}
Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]?

Related

Passing multiple value to single variable as function parameter

I want to pass multiple values as a parameter to a single variable in js. how can I access these value from this variable as the parameter?
the code below is just to show you what I'm trying to achieve.
function getsum(a,b)
{
// do something
}
getsum((0,-1),-1);// for now I use parentheses (0,-1).
please help how can I pass multiple values?
You could use an array and then access the elements of the array:
function getsum(a,b)
{
// First element
firstElement = a[0];
// Second element
secondElement = a[1];
// do something
}
getsum([0,-1],-1);
use either object or array to acquire this
function getsum(a,b)
{
console.log("a,b",a,b)
// do something
}
getsum({val0:0,val1:-1},-1);
function getsum(a,b)
{
console.log("a,b",a,b)
// do something
}
getsum([0,-1],-1);
You can't. (0,-1) makes use of the comma operator. It evaluates as -1. The 0 never reaches the function.
Use an array or object instead.

New to JavaScript: Can I pass a List into this function and have it still work?

As the title says, I'm new to JavaScript and not completely sure on certain syntax's.
After looking for a while I found the following function:
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
All I need to know is if I pass a List of Strings into the functions parameter, will it still work, or when it says array is that defining what kind of variable it is? If it won't currently work with a List what needs to change?
You can pass any Array or Array-like object containing string items, no matter how the parameter is named, and your function will work as expected.
Array-like object is an object, that has a length property with value >=0 and properties 0..length-1. Array-like object offen does not implement Array methods. The Array can be distinguished from Array-like object using a instanceof Array or Array.isArray(a), while the typeof a returns 'object' in both cases.
when it says array is that defining what kind of variable it is?
No. It is defining the name of the variable that the argument will be assigned to in the scope of the function.
JavaScript (at least ES5 which you are using here) doesn't have any type enforcement for function arguments, so you can pass whatever values you like.
The function does expect the value you pass to be an object with a length property and a number of properties with names that are integers (i.e. it expects the value to be like an array (see also duck typing)).
List is not a standard JavaScript data type. If you have created a List object, then you can pass it so long as it is array-like.
arrayis just the name of the expected parameter.
It can be of any type (Javascript doesn't have types)
So: Yes, your list will still "work" (as long as it supports the functions that are called on it, of course)
It will still work. Truly speaking in javascript there is an array no list as such. Hence even if you call the function with below arguments:
makeUL(["Cpp","Java","Javascript"])
The output would be :
<ul>
<li>Cpp</li>
<li>Java</li>
<li>Javascript</li>
</ul>
I'm assuming you mean Array. but i think your function is just returning a DOM element, so you wont directly see that in browser unless you append it into DOM tree.
var listofstrings = ['item 1','item 2','item 3'];
document.getElementByName('body').appendChild(makeUL(listofstring));

Array type being picked up as array value

I have some simple Javascript looping through an array of items (Tridion User Groups) to check if the user is a member of a specific group.
I can easily code around the issue shown below ( see && extensionGroup !== 'true') but I want to understand why the isArray = true is counted as a value in the array - any ideas?
The screenshot below demonstrates that the value extensionGroups has been set thus
var extensionGroups = ["NotEvenARealGroup", "Author", "ExampleGroupAfterOneUserIsActuallyIn"];
but returns the isArray value as a 4th value?
updated to show images a little clearer
You're using for in to iterate an array; don't do that. Use for (or forEach):
for(var i = 0; i < extensionGroups.length; i++) {
var extensionGroup = extensionGroups[i];
// ...
}
The reason this fails is because for in is used to iterate over an object's properties in JavaScript. Iterating over an array in this way means you get anything else assigned to it, such as this property or length.
And if you're able to use Array#forEach, it's probably most appropriate here:
extensionGroups.forEach(function(extensionGroup) {
// ...
});
For..in, technically speaking, doesn't iterate through values. It iterates through property names. In an array, the values ARE properties, under the hood. So when you iterate over them with for..in you get funky stuff like that happening.
Which highlights my next point: don't use for..in. Don't use it for arrays -- don't use it for anything, really. Ok -- maybe that's going a bit too far. How about this: if you feel the need to use for..in, think hard to see if it's justifiable before you do it.

Javascript use reserved keyword as key

Doing so
var x = new Array();
x['length']=5;
will make x an array of 5 undefined items, but I actually want to have the value '5' stored at key 'length'.
Is that possible?
In javascript arrays do not have keys. You are looking for objects:
var x = {}
x.length = 5;
I have to parse a file containing many words and store the number of occurences of each word
Use an object, and make the words the keys. You aren't storing sequential / ordered data, so you shouldn't use an array.
var word_count = {};
for (var i; i < words.length; i++) {
var word = words[i];
if (word_count[word]) {
word_count[word]++;
} else {
word_count[word] = 1;
}
If you want to do this you'd be better off creating an object rather than an array. This should give you what you want.
var x = {};
x['length'] = 5;
You can call methods on a javascript object using two different syntaxes. The familiar 'dot' syntax with parens to invoke the method, and the square bracket syntax. You can 'call' a method on a javascript object using the syntax myObj["methodname"](args). This is handy when you want to construct the method name dynamically using strings. Remember, objects in javascript are very much like a hash table (dictionary) where keys denote property and function names. If a key's value holds a function, it can be invoked (using parentheses).
In your example, Array has a method called 'length'. You are inadvertently calling its setter (which sets the length of the array to empty values, i.e., undefined).
Putting that all aside, you really do want a hash (associative array) in this case. An array is an offset indexed data structure.
A simple object literal like myObj = {} will suffice to give you hash semantics (again, objects in javascript are already like hashes) and you can then call myObj.whatever = "some value"
You could use objects instead of arrays to store your data. But if you need to use Arrays (you might need to use their functionality), You could cripple the words and store them as array keys.
Use some kind of simple rule to follow to bypass all the possible keywords. For example prefix all your array keys with a "_" character. This way you could always restore the original words from the keys, by simply removing their first character, and you are sure you are not referencing any specific property of the Array objects (like the length property).

Creating multi-dimensional arrays in javascript, error in custom function

I was trying to define an array (including other arrays as values) in a single javascript statement, that I can loop through to validate a form on submission.
The function I wrote to (try to) create inline arrays follows:
function arr(){
var inc;
var tempa = new Array(Math.round(arguments.length/2));
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
This is called three times here to assign an array:
window.validArr = arr(
'f-county',arr('maxlen',10, 'minlen',1),
'f-postcode',arr('maxlen',8, 'minlen',6)
);
However in the javascript debugger the variable is empty, and the arr() function is not returning anything. Does anyone know why my expectations on what this code should do are incorrect?
(I have worked out how to create the array without this function, but I'm curious why this code doesn't work (I thought I understood javascript better than this).)
Well from what your code does, you're not really making arrays. In JavaScript, the thing that makes arrays special is the management of the numerically indexed properties. Otherwise they're just objects, so they can have other properties too, but if you're not using arrays as arrays you might as well just use objects:
function arr(){
var inc;
var tempa = {};
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
What you're seeing from the debugger is the result of it attempting to show you your array as a real array should be shown: that is, its numerically indexed properties. If you call your "arr()" function as is and then look at (from your example) the "f-county" property of the result, you'll see something there.
Also, if you do find yourself wanting a real array, there's absolutely no point in initializing them to a particular size. Just create a new array with []:
var tempa = [];
Your code works. Just inspect your variable, and you will see that the array has the custom keys on it. If not expanded, your debugger shows you just the (numerical) indixed values in short syntax - none for you.
But, you may need to understand the difference between Arrays and Objects. An Object is just key-value-pairs (you could call it a "map"), and its prototype. An Array is a special type of object. It has special prototype methods, a length functionality and a different approach: to store index-value-pairs (even though indexes are still keys). So, you shouldn't use an Array as an associative array.
Therefore, their literal syntax differs:
var array = ["indexed with key 0", "indexed with key 1", ...];
var object = {"custom":"keyed as 'custom'", "another":"string", ...};
// but you still can add keys to array objects:
array.custom = "keyed as 'custom'";

Categories