Javascript: Arrays and For Loop Basics - javascript

I'm new to javascript and have been trying to teach myself the basics. I do have some experience with C++.
I came across this example in the source I'm using for studying and the for loop looks strange to me:
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Would someone mind explaining why there is a [0] and [1] near the end of these statements?
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];

A clearer way to write this statement is this:
var parts = cookiearray[i].split('='),
name = parts[0],
value = parts[1];

That doesn't have anything to do with the for-loop itself. Split returns an array of tokens; the string is split up at the given delimiter. You're simply accessing the first and second tokens in this array.

String.split creates an array using the assigned delimiter (in this case '='). The [0] and [1] are selecting the first and second elements of the array respectively (Javascript array element indexes start at zero).

Those are used to access the items in the arrays that you create.
It's more clear what they do, and also better for performance, if you put the array in a variable and access that. That way you don't have to create two identical arrays:
var cookie = cookiearray[i].split('=');
var name = cookie[0];
var value = cookie[1];

The code is splitting each cookie pair key=value into key ([0]) and value ([1]).

A for loop is an iterator. You can sort of think of it like a counter, or stepping progression. If you want to do something x number of times, then a for loop is your best friend. The issue, when you are first learning, is figuring out how to use them effectively.
I'll give you a relevant and nonrelevant (simplified) example:
Nonrelevant:
// Increase the value of x and print the new value to the console 20 times.
var x = 6;
for(var i = 0; i < 20; i++) {
x++;
console.log("Value of x: " + x);
}
If you take a close look it's really rather logical. You define an iteration variable i, tell it when to stop (i < 20...so stop if i = 20), how to progress with each iteration (i++ or i + 1).
So the code will enter the loop when i = 0...it will add 1 to the value of x (x++), resulting in x = 7. It does the same for each iteration, so when i = 1, x (7) + 1 = 8, so on and so forth until i = 20, then the code breaks out of the loop and continues on it's merry little way. When it breaks we have just added 1 to x 20 times. Since x used to equal 6, it now equals 26.
Relevant:
// Given array of length 10, print each element to the console
for (var i = 0; i < cookiearray.length; i++){
console.log(cookiearray[i]);
}
So here the for loop is the same, it simply iterates until i equals the length (number of elements, in this case) of the array (so 10 times). When i = 0, our code prints the element of the array at cookiearray[0]...when i = 1 it prints cookiearray[1]...so on and so forth for the entirety of the array.
What may confuse you in the example is the split function. Split returns an array. So this line:
name = cookiearray[i].split('=')[0];
...actually means assign the first element of the new array created from splitting the cookiearray's element at position i.
Let's assume that cookiearray[0] = "Hello=World". When i = 0, our code splits the string "Hello=World" into a new array where the element at the 0 position is "Hello", it then assigns this to the local variable name. So name = "Hello".

Related

how can I pop all array list

ı couldn't pop() every array list. at the end remain two array elements
function ürünSil(){
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"]
for(let i in diller){
let sonİcerik = diller.pop()
document.write(diller + "<br />")
}
}
you can empty your array like this also:
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"];
while(diller.length > 0) {
diller.pop();
}
console.log(diller)
The length of the array changes each time on pop() so when there are 3 items removed from the array , the present index for i on your code will be 2 and hence the actual length is also 2, so the for() loops does not trigger further.
The solution could be to preserve the initial length value and use that value in the loop:
function ürünSil(){
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"]
const length = diller.length;
for(let i = 0; i<length; i++){
let sonİcerik = diller.pop()
console.log(sonİcerik);
}
}
ürünSil()
use while loop instead of for.
while (diller.length != 0) {
diller.pop();
document.write(diller + '<br />');
}
This happens because pop reduces the length of the array, which impacts the times the loop will iterate. Instead just have the while condition check whether the array still has elements, without any i.
Unrelated, but
don't use document.write for this. Use console.log, or if you want to add data to the HTML document, then use other DOM methods.
have the good habit of ending your statements with semicolon. You don't want to fall for the sometimes tricky effects of automatic semicolon insertion.
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"];
while (diller.length) {
let sonİcerik = diller.pop();
console.log(sonİcerik);
}

Trying to make a Javascript Array Print out using Inputted value

my first question would be am I correctly getting the value from id "textOne" into my var a? Second, I am supposed to have my while loop run "while the variable that represents the index value that I want to print" is greater than or equal to the minimum array value. Is my While loop condition correct?
I just basically want this to print out the correct number of indexes within my array based on the user input ranging from 1-5.
Thanks in advance.
<input type="button" value="Click" onclick="JobDuties()" />
to see my top
<input type="text" id="textOne" />
job duties here
<p id="answer"></p>
<script type="text/javascript">
function JobDuties()
{
var x = "";
var a = document.getElementById('textOne').value;
var b = a - 1;
myduties = new Array();
myduties[0] = "Saab";
myduties[1] = "Volvo";
myduties[2] = "BMW";
myduties[3] = "Toyota";
myduties[4] = "Ford";
}
while (a>=0)
{
x = x + myduties[b];
document.getElementById("answer").innerHTML=x;
}
</script>
I will assume you want to print out the correct array value, not arrays, as there are not multiple. PS> People do not like homework questions on here if you do not say so because answering completely does not help you learn. I will partially answer.
You do not need to loop through the array to look up a value.
You can initialize the array more easily.
["Saab", "Volvo", ... ]
You can reference a position in the array, like so for Saab as it is zero indexed
myduties[0]
If you are going to loop, which I am still not seeing why you would do that.
Code below:
var i = 1; //The variable you increment up to the use input variable a
while(i =< myduties.length){
if(i == a){ //if i and a are same then that position
//in the array will have the car type the user requested
myduties[i-1] //and set it to the DOM or document element similar to what you already had
}
i = i + 1; //Increment i towards the one less than the length of the array
}
Not perfect or checked but that should provide you with some pointers.

Taking values from one array and to obtain a different value from a separate array. JavaScript

I'm not entirely sure how to word what I am asking here but I have an assignment where two arrays are present. One array contains strings which are the makes of cars. The second array contains the price of that car. The program is to run a for loop through the first array, identify the values that contain that specific make, and then add the prices up in the second array.
This is what I have:
<html>
<script>
make = new Array();
make[0]='honda';
make[1]='toyota';
make[2]='pontiac';
make[3]='honda';
price = new Array();
price[0]=35000;
price[1]=35000;
price[2]=40000;
price[3]=45000;
function totalByColor(parameter1){
total=0;
for(i=0;i<make.length;i++){
if(make[i]=='honda'){
for(b=0;b<price.length;b++){
make[i]=price[b]; //This is where I need help!
total = total + price[b];
};
} else {
};
return total;
};
return total;
};
</script>
<input type='button' value='test' onclick="alert('Return = '+totalByColor('honda'))">
</html>
So I need to set the program up to identify the value in make[0] is relevant to price[0] and make[3] is relevant to price[3], so price[0] and price[3] can be added together in the second for loop, any one have any idea? Thanks in advance for any help or guidance on this issue
If the indices are the same, you don't need another for loop; just use your var i:
var total = 0;
for (var i = 0, len = make.length; i < len; i++) {
if (make[i] === 'honda') {
total += price[i];
}
}
return total;
total should be a local variable, and is defined as 0 first, then you can use += to redefine total as total + price[i]. It's shorthand for total = total + price[i]. I also included var before the i in the for loop, because it should be local, and not global; and, you don't need so many semi-colons: after brackets for example } (so long as it's not an object you are defining). One more thing is that you have a return statement in your for loop, which means it will only loop over one value before ending the function. The return statement should be after the for loop.

Javascript array + index

Im still needing help with this, and have edited the jsfiddle post to show my problem. http://jsfiddle.net/7ztEf/6/
I want to return number to associated index value [0] =0 [1]=1 as you can see the index string returns all numbers. Thanks again Paul
I have a number generator script that returns values to DIV ID's. I need to hook into this somehow, to enable replacing color based upon the number value i.e. > 1 && <= 20 = red etc.
function myNumbers(numbers, type) {
for (var x in numbers) {
document.getElementById(type + x).innerHTML = numbers[x];
}
}
This script fills each of the DIVs named num0 ... num3 with a random number.
I have managed to query the first value of numbers[x] but need to set an index order to loop through the rest, or something.
Use Array.forEach.
numbers.forEach(function (number, index) {...})
Don't use for..in for arrays. They're meant to be used on objects so using for..in on arrays will return such things as the length element.
Either use forEach as ethagnawl mentioned or use the traditional for loop:
for (var x=0; x < numbers.length; x++) {
document.getElementById(type + x).innerHTML = numbers[x];
}

Javascript - storing the index of all array values in a variable

Say I have an array in JS: var fruits = [apple,orange,banana]
I want to store the index of each fruit in variables such that at any point in time, if I add more stuff to the array, I will still know that the index of apple is X. So in this case, 0 is apple, but if I add something to the beginning of that away, the index of apple changes.
The more verbose way I can think of is to loop through the array
for (var i=0;i<fruits.length;i++) {
switch(fruits[i]) {
case:"apple"
var indexApple = i;
break;
//etc
}
}
Another way I can think of is use the value of the arrays as the variable name.
for (var i=0;i<fruits.length;i++) {
//psedo code
var 'index' + fruits[i] = i;
}
So in the end I'd have var indexApple = 0, indexOrange = 1, etc. THe key to the second method is to be able to create a dynamic variable by concatenating the string 'index' and the value of the array to create that variable. Not sure how to do that.
Note: Ideally I want the variables that store the index to be dynamically generated. Such that I only I can modify/add to the fruits array, and a new variable will be generated to store the index.
it seems like ensuring your the value of the index is legitimate will be difficult. i would include jquery and use the inArray method which returns the index of the item in the array.
function showIndexes() {
var appleIndex = $.inArray(fruits, "Apple"); //returns 0
var guavaIndex = $.inArray(fruits, "Guava"); //returns -1
fruits.unshift("Guava");
appleIndex = $.inArray(fruits, "Apple"); //returns 1
guavaIndex = $.inArray(fruits, "Guava"); //returns 0
}
The simplest solution is simply to build an Object which gives you nearly O(1) lookup time, and will scale with your array:
function LinkFruits(fruits) {
FruitLookup = {}
fruits.forEach((fruit,ind) => FruitLookup[fruit] = ind)
}
Now you can simply "lookup" your index from the FruitLookup table when needed like:
console.log("The index of apple is",FruitLookup.apple,"and for orange is",FruitLookup.orange)
Now if you modify your array you simply need to run LinkFruits(fruits).
Technical Note: If you want to fully automate this process you can look into Array.observe() which is now deprecated. Or overload the push and pop methods of this array to trigger the update before falling back to the default prototype methods.

Categories