Accessing a counter in a variable name in Javascript (code inside) - javascript

I am looking to do something very similar to the following PHP code but in javascipt:
for ($weenumber = 1; $weenumber <= 30; $weenumber++)
{
$weenumber = str_pad($weenumber, 2, "0", STR_PAD_LEFT);
echo $_POST["entry{$weenumber}_cash"];
}
Basically accessing the loop number padded with a trailing 0 if less than 10 but I dont know the syntax in JS to do this :(
Sorry for noob style question

I think that you mean a leading zero rather than a trailing zero...
You can for example use the conditional operator:
(n < 10 ? '0' : '') + n
You could also implement a general purpose function:
function padLeft(str, len, ch) {
while (str.length < len) str = ch + str;
return str;
}
To access an object property by name in Javascript you use brackets. Example:
var value = obj['entry' + (n < 10 ? '0' : '') + n + '_cash'];
If n contains 4, this will be the same as obj.entry04_cash.

Whether or not there's a specific function to do this, if you know how to use an if clause, and you know how to perform string concatentation (using the + operator if you didn't), then you should be able to easily roll you own version of str_pad by hand (which works for numbers below 100).
Think about the cases involved (there are only two) and what you need to output in either case.

This is the code you should use:
for(var i=0; i<30; i++){
document.writeln(i<10 ? "0"+i : i);
}
change document.writeln() with any function you want to handle the data

for (weenumber = 1; weenumber <= 30; weenumber++) {
weenumber = str_pad(weenumber, 2, "0", STR_PAD_LEFT);
}
For the str_pad() function, you can use PHPJS library:
http://phpjs.org/functions/str_pad:525
This library will also ease transition from php to javascript for you. Check it out.

for(var i=0; i<30; i++)
{
var index = i;
if(i<10) index = "0" + index
var elem = document.getElementById("entry"+index);
}

var someArray = [/*...*/];
for (var i= 1;i<= 30;i++)
{
var weenumber = i+"";
for(var j=weenumber.length;j<2;j++)
weenumber = "0" + weenumber;
var key = "entry" + weenumber + "_cash";
document.write(someArray[key]);
}

Here's a function you can use for zeropadding:
function zeroPad(nr,base){
var len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
}
//usage
alert(zeroPad(3,10)); //=> 03
or extend the Number prototype
Number.prototype.zeroPad = Number.prototype.zeroPad ||
function(base){
var nr = this, len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
};
//usage
var num = 1;
alert(num.zeroPad(100)); //=> 001
Now for the variable name part: if it's a global variable (not advisable) that variable is a property of the global object, in a browser that's window. You can get a variable by its dynamic name using the equivalent of: window['myvariable'+myJustResolvedNumericValue]. Within an object (instance) you can use the same bracket notation: myObject['myvariable'+myJustResolvedNumericValue].
Using this information, in javascript your function could look like:
for (var weenumber = 1; weenumber <= 30; weenumber++)
{
// execute something using the variable that uses the counter in the
// variable name as parameter
executeSomeFunction(window['entry'+weenumber.padLeft(10) + '_cash']);
}

Related

Reverse a string using two-pointer method in JS

I am trying to reverse a string. I am aware of .reverse function and other methods in Js to do so, but i wanted to do it this two-pointer method.
The problem is the string is not getting updated. Is there anything i am not aware of strings. Whats wrong here ?
function reverseString(s) {
let lengthOfStr = 0;
if ((s.length - 1) % 2 == 0) {
lengthOfStr = (s.length - 1) / 2
} else {
lengthOfStr = ((s.length - 1) / 2) + 1;
}
let strLengthLast = s.length - 1;
for (let i = 0; i <= lengthOfStr; i++) {
let pt1 = s[i];
let pt2 = s[strLengthLast];
s[i] = pt2;
s[strLengthLast] = pt1;
console.log('----', s[i], s[strLengthLast]);
strLengthLast--;
}
return s;
}
console.log(reverseString('hello'));
Unlike in C, strings in JavaScript are immutable, so you can't update them by indexing into them. Example:
let s = 'abc';
s[1] = 'd';
console.log(s); // prints abc, not adc
You'd need to do something more long-winded in place of s[i] = pt2;, like s = s.substring(0, i) + pt2 + s.substring(i + 1);, and similarly for s[strLengthLast] = pt1; (or combine them into one expression with 3 calls to substring).
I'm not sure why it doesnt update the string, but if you handle the replacement as an array/list it works as follows:
function reverseString(s) {
let lengthOfStr = 0;
sSplit = s.split("");
if ((s.length - 1) % 2 === 0) {
lengthOfStr = (s.length - 1) / 2
}
else {
lengthOfStr = ((s.length - 1) / 2) + 1;
}
let strLengthLast = s.length - 1;
for (let i = 0; i <= lengthOfStr; i++) {
let pt1 = sSplit[i];
let pt2 = sSplit[strLengthLast];
sSplit[i] = pt2;
sSplit[strLengthLast] = pt1;
console.log('----', sSplit[i], sSplit[strLengthLast],sSplit);
strLengthLast--;
}
return sSplit.join("");
}
console.log(reverseString('Hello'));
returns: Hello => olleH
As covered in comment, answers and documentation, strings are immutable in JavaScript.
The ability to apparently assign a property value to a primitive string value results from early JavaScript engine design that temporarily created a String object from primitive strings when calling a String.prototype method on the primitive. While assigning a property to the temporary object didn't error, it was useless since the object was discarded between calling the String method and resuming execution of user code.
The good news is that this has been fixed. Putting
"use strict";
at the beginning of a JavaScript file or function body causes the compiler to generate a syntax error that primitive string "properties" are read-only.
There are many ways of writing a function to reverse strings without calling String.prototype.reverse. Here's another example
function strReverse(str) {
"use strict";
let rev = [];
for( let i = str.length; i--;) {
rev.push(str[i]);
}
return rev.join('');
}
console.log( strReverse("Yellow") );
console.log( strReverse("").length);
I tried that way, hopefully might be helpful for someone.
const input = 'hello'; /*input data*/
const inputArray = [...input]; /*convert input data to char array*/
function reverseString(inputArray) {
let i = 0;
let j = inputArray.length -1 ;
while(i < j ) {
const temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
i++;
j--;
}
};
reverseString(inputArray);
console.log(inputArray)
const finalResult = inputArray.join("");
console.log(finalResult);
Thanks.

What does this specific line of code mean/do in Javascript

I'm practicing my coding and I'm still kind of new. While looking for solutions to practice problems I see this kind of code used in loops and I'm curious what this line of code does.
counter[string[i]] = (counter[string[i]] || 0) + 1;
here it is in the full code that is used to count most occured character in a string if this helps
var string = "355385",
counter = {};
for (var i = 0, len = string.length; i < len; i += 1) {
counter[string[i]] = (counter[string[i]] || 0) + 1;
}
var biggest = -1, number;
for (var key in counter) {
if (counter[key] > biggest) {
biggest = counter[key];
number = key;
}
}
console.log(number);
It is basically saying
If counter[string[i]] is falsy (undefined, 0, empty string, null etc) use 0 to add to 1 otherwise use its existing value to add to 1 and make this addition the new value for counter[string[i]]
It is using the logical OR operator ||
See JavaScript OR (||) variable assignment explanation

Treat the prev element in JavaScript array when creating object dynamically

I want to do something like:
var arr = []
for var(i=0;i<x;i++){
arr.push{ get num(){return this.previousArrayElement.num + randomNumber}}
}
how can I treat "previousArrayElement"?
I think you are just trying to create an array of size x containing numbers in order of size and separated by randomNumber intervals? Something like this would work:
var x = 100;
var arr = [0]
for (i=1; i<x; i++) {
arr.push( arr[i-1] + Math.random() );
}
Note that by starting the array out with an initial value (index 0) and beginning your iteration with the second value (index 1) you don't have to worry about accessing the 0-1 element at the first iteration.
I hope that helps!
Not 100% sure this is what you want. Expected output shown is not valid syntax and details provided are very open to interpretation
var arr = []
for (var i=0; i < x; i++){
var num = i > 0 ? arr[i-1].num : 0;
num= num + randomNumber; // is this an existing variable?
arr.push({ num: num}); // used object with property `num` based on example `previousArrayElement.num `
}

Using search method from string

I'm trying to count the number of times certain words appear in the strings. Every time I run it I get a
uncaught TypeErro: undefined is not a function
I just actually need to count the number of times each "major" appears.
Below is my code:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray.search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);
Here is my csv file which is stored in a 1d array.
"NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"
"Smith, John A","Computer Science","Senior","E"
"Johnson, Brenda B","Computer Science","Senior","E"
"Green, Daisy L","Information Technology","Senior","E"
"Wilson, Don A","Information Technology","Junior","W"
"Brown, Jack J","Multimedia","Senior","E"
"Schultz, Doug A","Network Administration","Junior","E"
"Webber, Justin","Business Administration","Senior","E"
"Alexander, Debbie B","Multimedia","Senior","E"
"St. John, Susan G","Information Technology","Junior","D"
"Finklestein, Harold W","Multimedia","Freshman","E"
You need to search inside each string not the array. To only search inside the "Major" column, you can start your loop at index 1 and increment by 4 :
var multimedia = 0;
for(var i = 1; i < sortedarray.length; i += 4)
{
if(sortedarray[i].indexOf("Multimedia") > -1)
{
multimedia += 1;
}
}
console.log(multimedia);
What you're probably trying to do is:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].indexOf("Multimedia") !== -1)
{
multimedia++;
}
}
console.log(multimedia);
I use indexOf since search is a bit of overkill if you're not using regexes.
Also, I replaced the += 1 with ++. It's practically the same.
Here's a more straightforward solution. First you count all the words using reduce, then you can access them with dot notation (or bracket notation if you have a string or dynamic value):
var words = ["NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"...]
var count = function(xs) {
return xs.reduce(function(acc, x) {
// If a word already appeared, increment count by one
// otherwise initialize count to one
acc[x] = ++acc[x] || 1
return acc
},{}) // an object to accumulate the results
}
var counted = count(words)
// dot notation
counted.Multimedia //=> 3
// bracket notation
counted['Information Technology'] //=> 3
I don't know exactly that you need this or not. But I think its better to count each word occurrences in single loop like this:
var occurencesOfWords = {};
for(var i = 0; i < sortedarray.length; i++)
{
var noOfOccurences = (occurencesOfWords[sortedarray[i]]==undefined?
1 : ++occurencesOfWords[sortedarray[i]]);
occurencesOfWords[sortedarray[i]] = noOfOccurences;
}
console.log(JSON.stringify(occurencesOfWords));
So you'll get something like this in the end:
{"Multimedia":3,"XYZ":2}
.search is undefined and isn't a function on the array.
But exists on the current string you want to check ! Just select the current string in the array with sortedarray[i].
Fix your code like that:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);

How to dynamically create variable name?

I need to create javascript objects that base on user defined number. So if user defines 20, then I need to create 20 variables.
var interval_1=0, interval_2=0, interval_3=0, interval_4=0, interval_5=0... interval_20=0;
how do I do it so the name of the object can be dynamically created?
for (i=0; i<=interval; i++){
var interval_ + i.toString() = i;
}
Erm, use an array?
for( i=0; i<=count; i++) array[i] = i;
Use an array:
var i, count, interval = [];
// user defines count, 20 for example
count = 20;
for (i = 0; i < count; i++) {
interval.push(i);
}
// interval[0] === 0
// interval[19] === 19
// interval.length === 20
Note, this starts the index at 0 and goes up to count - 1. Do not use i <= count unless you start i at 1.
Here is a jsFiddle to illustrate. Hit F12 to open dev tools in most browsers and look at console, or change console.log() to alert().
Link: http://jsfiddle.net/willslab/CapBN/1/
Alternatively, you could setup a single object with properties for each value:
var i, count, intervals = {};
count = 20;
for (i = 0; i < count; i++) {
intervals["interval_" + i] = i;
}
//intervals.interval_0 === 0
//intervals.interval_19 === 19)
Link: http://jsfiddle.net/willslab/EBjx7/2/
for (i=0; i<=20; i++){
window["interval_" + i.toString()] = i;
}
Javascript variables can be created by:
a variable declaration, e.g. var x;
assigning a value to an undeclared variable, e.g. y = 'foo';
an identifier in a formal parameter list, e.g. function bar(x, y, z);
using eval, e.g. eval( 'var x = 4');
If all else fails and you want say 5 variables, you can do:
var s = [];
var i = 5;
while (i--) {
s[i] = 'a' + i;
}
eval('var ' + s.join(',') + ';');
alert(a0); // shows undefined
If a0 wasn't defined, the last step would throw a reference error.
Of course the issue you now have is how to access them. If they are created as global variables, you can use:
globalObj['a' + i];
where globalObj is usually window, however there is no equivalent for accessing function variables since you can't access their variable object.
So the usual solution is to put things into arrays or objects where you can iterate over the properties to find things you don't know the name of.

Categories