Can I assign an array value to a variable? - javascript

I can't seem to assign an array value to a variable. It always returns undefined.
In my code I have set currentWord = text[wordPos]. At the end of the code I have console logged currentWord, and text[wordPos]. My thinking says that they should return the same value, but they don't. currentWord returns undefined, and text[wordPos] returns the correct value (the first word in the 'text' array).
Solved. I had mistakenly forgot that I had 2 arrays, and thought the text array was not empty, but it was. The words array is the array I had filled in separate file.
var text = Array();
var wordPos = 0;
var currentWord = text[wordPos];
function gen() {
text = [];
var random;
for (var i = 0; i < 10; i++) {
random = words[Math.floor(Math.random() * 50)];
text.push(random);
}
document.getElementById('text').innerHTML = text.join(" ");
console.log(currentWord);
console.log(text[wordPos]);
}

Currentwork is undefined because you create an array object but never push a value into it. It transfers the current value of the variable not the reference.

There is no value at index 0 of text. If you assign some values to the text array you should be good!

Updated:
Read the OP's note above about the two arrays in the original example. In light of this information, the following script simulates an imported array words of 50 distinct values in order to generate a text of ten space-delimited numbers and indicate its first value:
// simulating an array imported from a separate file
var words = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50];
function gen() {
var wordPos = 0;
var currentWord = "";
var arr = [];
var randomVal;
var d = document;
d.g = d.getElementById;
var pText = d.g('text');
// get each of 10 values by randomly selecting an element's key
for (var i = 0; i < 10; i++) {
randomVal = words[ Math.floor( Math.random() * 50 ) ];
arr.push( randomVal );
}
pText.innerHTML = arr.join(" ");
currentWord = arr[wordPos];
console.log("Current word: ",currentWord );
}
gen();
<p id="text"></p>
This script randomly selects 10 numbers and adds them to an empty array by means of variable randomVal. This variable acquires a value in each iteration of the for-loop, during which the variable is passed to the push() method of arr in order to append it to the array. Once the loop terminates, the script joins the elements of arr on a blank space character, which yields a string whose numeric values are space-delimited.
One can discern that the script is working correctly when the console.log statement displays the first numeric value appearing in the text.

Related

Random Selection in a Column

I've modified a code to select a data randomly from A Column cells. The problem I'm facing is, I'm only able to get the data from A1. and rest of the data are not showing. Where did I go wrong?
function getData () {
var SS = SpreadsheetApp.getActiveSheet()
var Avals = SS.getRange("A1:A").getValues();
var numberOfValues = Avals.filter(String).length;
var data = SS.getRange(1,1,numberOfValues).getValues();
for(var i = 0; i < data.length; i++)
{
var j = Math.floor(Math.random()*(data[i].length)); //method of randomization
var element = data[i][j];
return element;
logger.log(element);
}
}
Explanation:
getValues() returns a 2D array. In your case you have a single column, therefore data has the format of: [[a1],[a2],[a3],..]]. data[i] will give you a single element of this array. For example data[0] is [a1] and as you can understand [a1].length is equal to 1 regardles of the chosen index. In other words, data[i].length is 1 for every i and therefore you are always getting the first element.
It is also worth mentioning that you have a return statement inside the for loop and therefore i gets only the first value 0 since the function is terminated when reaches the return statement. You don't need a for loop if you want to get a single random element from the column.
Since data[i].length is equal to 1 this expression Math.random()*(data[i].length) returns a number between 0 and 1 but less than 1. Therefore Math.floor(Math.random()*(data[i].length)) always returns 0 and as a result data[0][0] is equal to the value of the first cell A1.
Please notice that logger.log(element) is wrong. It should be Logger.log(element); but you are not getting any error since return is before that line and the function never reaches that line.
Finally, I used flat() to convert the 2D array to 1D and therefore data.length returns the correct length of the array but also you can now index it with one variable.
Solution:
function getData () {
const SS = SpreadsheetApp.getActive();
const sh = SS.getActiveSheet();
const Avals = sh.getRange("A1:A").getValues();
const numberOfValues = Avals.filter(String).length;
const data = sh.getRange(1,1,numberOfValues).getValues().flat();
const j = Math.floor(Math.random()*(data.length)); //method of randomization
const element = data[j];
Logger.log(element);
return element;
}

JavaScript Array.shift not working

I have been programming a system that is supposed to delete the first index of an array. Instead of changing an array from (i.e) "1,2,3,4,5" to "2,3,4,5" the console gives an error: "Uncaught TypeError: num.splice is not a function". I have heard that num.splice is not a function, it is an operation (or something) to delete the first indexed value of the array. I am confused that when I use an example code from w3Schools, there is no outputted error in the console. I don't understand why this happens.
(I have given the entire code just in case it has to do with syntax issues)
function dCrypt() {
var num = document.getElementById("demoin").value; // ex: a127
var key = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var mod = 0;
var out = 0;
var prep = 0;
var pre = 0;
num.split("");
mod = num[0];
pre = key.indexOf(mod);
num.splice(0,1);
for (i=0;i <= pre;i++) {
prep += 26;
}
out = Math.floor(num + pre);
document.getElementById("demoout").innerHTML = out;
}
Thanks in advance!
When you split 'num' you have to reassign it
num = num.split("");
Referring to your link from w3schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
As you can see the var num is string(and not an array) and has the value of the element with id demoin.
Since you are trying to splice a string and not an array. The error shows up in the console.
Solution:
Either store the value of your split in an array(it could be num itself) and then splice that array.
num = num.split("");
...
num.splice(0,1);

String to arrays

I have below String that needs to be divided into multiple array after 5 comma separated values. Then I need to put each array values to textbox values using script. I tried the below code to split and assign to array but not working. Is there any way this can be resolved? <%=ab%> is the JavaScript variable that contains the below code.
[768.234.232, 768.234.232, 574,10-10-2012, 10-10-2012, 768.234.232, 768.234.232, 987, 10-10-2012, 10-10-2012]
function functionOne() {
var list = "<%=ab%>";
var ab = new Array();
var i = 0;
for (i = 0; i < 10; i++) {
ab[i] = list.split(",", 3);
alert(ab[i]);
}
}
"needs to be divided into multiple array after 5 comma seperated values"
You seem to be saying that the result should be one array with five values in it and then a second array with the next five values in it, etc. If so, you can do the following:
var list = "<%=ab%>";
list = list.slice(1,-1); // remove the enclosing []
var allValues = list.split(/\s*,\s*/); // split on comma with optional whitespace
var a = [];
for (var i = 0; i < allValues.length; i+=5) {
a.push( allValues.slice(i, i+5<=allValues.length ? i+5 : allValues.length) );
}
After running the above, a will be array that contains other arrays. a[0] is an array of the first five items, so, e.g., a[0][2] is the third item. a[1] is an array of the next five items. If there were more than ten items in the original list then a[2] would be an array of the next five, etc. If the total number of items is not divisible by five then the last array would hold the remainder.
Demo: http://jsfiddle.net/9xAxz/
"Then I need to put each array values to textbox values"
Um... does that mean one item per textbox? If so, why did you want to divide up after five values? Do you mean five items per textbox? Either way are you talking about dynamically creating textboxes? If so you can follow the above code with something like this:
var tb;
for (i = 0; i < a.length; i++) {
tb = document.createElement('input');
tb.value = a[i].join(", ");
document.body.appendChild(tb);
}
Demo: http://jsfiddle.net/9xAxz/1/
If I'm completely off base on any of the above, well... think about editing your question to make it clearer. I suppose I should've clarified before answering, but please update the question to show what your desired output is for that input.
function functionOne() {
var list = "<%=ab%>".split(/,\s?/g);
for (var i = 0; i < list.length; i++) {
t = document.createElement('input');
t.type = 'text';
t.value = list[i];
document.body.appendChild(t);
}
}
functionOne();
http://jsfiddle.net/WJPHt/1/

Javascript - Compare value to Associative array index

I have the following code:
var license_price = 0;
var num_licenses = jQuery('#num_licenses').val();
var lp = {};
lp[1]=12.50;
lp[10]=15.50;
lp[50]=50.00;
for(var index in lp) {alert(index);
if (num_licenses >= index){
license_price = parseFloat(lp[index]);
}
}
//alert(license_price);
jQuery('#total_price').val((num_licenses * license_price));
This code determines the value entered in the num_licenses box, then goes through the array lp and assigns a price based on the value of each key. So, if num_licenses = 8, the price should be 12.50 each, if the num_licess = 60, the price should be $60.
It works for all values except 2 - 9. If I enter 2-9, the price from fp[10] is used. But, if it is 1, then I get 12.50.
take care,
lee
When you iterate over the object's indices they are typed as strings. Your > comparison is actually sorting them alphabetically rather than numerically. Parse its numeric value to get this working. (alphabetically '2' occurs after all values starting with '1', including '10', so '2' > '10', etc.)
for(var index in lp) {
alert(index);
if(lp.hasOwnProperty(index)) { // prevent comparison when property inherited
if (num_licenses >= parseInt(index,10) ){
license_price = parseFloat(lp[index]);
}
}
}
The problem is that you are comparing a string to an integer. The result of the val() function is a string. Therefore, if your input is '2' , the result of '2' <= 10 is false. You should convert it first to an integer using the parseInt() function.
Here's what it should look like:
var license_price = 0;
var num_licenses = parseInt(jQuery('#num_licenses').val(),10);
var lp = {};
lp[1]=12.50;
lp[10]=15.50;
lp[50]=50.00;
for(var index in lp) {alert(index);
if (num_licenses >= index){
alert("Greater than " + index);//added this for debugging
license_price = parseFloat(lp[index]);
}
}
//alert(license_price);
jQuery('#total_price').val((num_licenses * license_price));
Note that I added a parseInt() call to the value. I also added some alert calls so you can see what is happening.
Here is a link to a jsFiddle snippet so that you can test it out: http://jsfiddle.net/CmbvW/8/
In your code lp is a Object not a array, so index is a property name with type String.
Try to change your code to
var lp = [];
then the index will be a number.

Javascript dynamic array of strings

Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Code is appreciated.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
First is the prompt() function which displays a popup asking the user for some input.
Pros: easy. Cons: ugly, can't go back to edit easily.
Second is using html <input type="text"> fields.
Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.
For the prompt method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
Put a single input field on the page.
Add an onfocus handler to it.
Check if there is another input element after this one, and if there is, check if it's empty.
If there is, don't do anything.
Otherwise, create a new input, put it after this one and apply the same handler to the new input.
When the user clicks OK, loop through all the <input>s on the page and store them into an array.
eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
var junk=new Array();
junk.push('This is a string.');
Et cetera.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
Printing Order
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
Page Submission
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.
<script type="text/javascript">
var arr = [];
function add() {
var inp = document.getElementById('num');
arr.push(inp.value);
inp.value = '';
}
function show() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var con = document.getElementById('container');
con.innerHTML = html;
}
</script>
<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Categories

Resources