Adding dynamically to an empty string - javascript

I am trying to assign each character in a nonempty string to an empty string (making a copy). Here is my code:
x = "example";
y = "";
for (var i = 0; i < x.length; i++) {
y.charAt(i) = x.charAt(i);
}
alert(y);
However, I get the following error in the console:
ReferenceError: invalid assignment left-hand side
y.charAt(i) = x.charAt(i);
I thought it was possible to grow a non-empty string dynamically (hope i'm using the correct terminology). Any help is appreciated!

The "".charAt(0) in an empty string is not defined. Indeed, "a".charAt(0) is "a".
Why don't you concatenate?
x = "example";
y = "";
//Simplest way:
y += x;
//With characters:
for (var i = 0; i < x.length; i++) {
y += x.charAt(i);
}

charAt(x) returns a string containing a character at the position x of the string this, but does not return a link to that position, thus, it is not equal to C's [] notation which returns a link to a byte where the character is located.
So, the charAt(x)= assignment is not valid as well as "a"="b" isn't, too.
Anyway, you can't do "".charAt(x) no matter what is x, because the string is empty.
Anyway, you can't even do "a".charAt(0)="b", because of the reason described in the first paragraph.
So, the only way to change some character in a string is str[x], which works in most browsers. But you still can't ""[0]", so you should first create a string with the same length as the string you are copying, or use concatenation.

It is possible. This is the right way to go:
x = "example";
y = "";
for (var i = 0; i < x.length; i++) {
y += x.charAt(i);
}
Your approach is not correct, since the charAt(i) method returns the (read-only) value of the char at position i.
Instead, an assignment operator, such as =, stores the value on the right side of the op = into the variable on the left side.
In this case y += x.charAt(i) is equal to y = y + x.charAt(i).
e.g.:
1st iteration:
x = "example";
y = ""
i = 0
x.charAt(i) == x.charAt(0) == "e"
y += x.charAt(i) -> y = y + x.charAt(i) -> y = y + x.charAt(0) -> y = y + "e" -> y = "" + "e" = e
2nd iteration:
x = "example";
y = "e"
i = 1
x.charAt(i) == x.charAt(1) == "x"
y += x.charAt(i) -> y = y + x.charAt(i) -> y = y + x.charAt(1) -> y = y + "x" -> y = "e" + "x"
and so on...
At each step, the char at position i of of the string x is appended to the string y and in the end x === y.

Related

JavaScript Regex return the last occurrence of y between x while ignoring double x's second occurrence

Okay so the title must be a head scratcher, but here is the full string:
y = "_target"
x = "_"
string A = "prefix_param_name_id_set_selected_param_name_index__target_"
string B = "prefix_param_name_id_set_selected_param_name_index_target_"
regex looks for "y"
"y" will always be the value between the last occurrence of "x"
if the last occurrence of "x" is preceded with double "x" then regex assumes the second part of double "x" is part of "y"
so returning "y" where at one instance "y" may be "_target" and at another "y" may be "target"
This is where I am at:
var str = "prefix_param_name_id_set_selected_param_name_index__target_";
alert(str.match(/\(([^)]*)\)[^(]*$/)[1]);
returns "target"; it should be "_target".
UPDATE:
Please note that "y" is a variable and is unknown. str is known, but the regex does not know what "y" is, only that it is found between at the last occurrence of "x"
You need to use x and y to create the regular expression
var y = "_target";
var x = "_";
var regexp = new RegExp("(?<=" + x + ")(" + y + ")(?=" + x + ")", "g");
var input = "prefix_param_name_id_set_selected_param_name_index__target_";
var matches = input.match(regexp);
matches outputs
["_target"]
Explanation
Use (?<=" + x + ") to check if y follows x
(" + y + ") captures y
(?=_) checks if x follows y as well.
Demo
var y = "_target";
var x = "_";
var regexp = new RegExp("(?<=" + x + ")(" + y + ")(?=" + x + ")", "g");
var input = "prefix_param_name_id_set_selected_param_name_index__target_";
var matches = input.match(regexp);
console.log(matches);

Node.js code being skipped (for)

I cannot see what's happening here, can someone enlighten me?
Why am I not entering the FOR?
Code:
console.log('l:269');
var smallestPrice = itemPriceAll; // start with max
console.log('itemNames.length, itemPriceall: ' + itemNames.length + ' ' + itemPriceAll);
for (var y; y < itemNames.length; y++) {
console.log('Are you fucking kidding me?');
console.log('l:272, itemPrice: ' + itemPrice[y] + 'houseEdge: ' + (itemPriceAll * houseEdge));
if (itemPrice[y] >= (itemPriceAll * houseEdge)) {
console.log('l:274');
if (itemPrice[y] < smallestPrice) {
smallestPrice = itemPrice[y];
keeping = itemId[y];
}
}
}
console.log('l:284');
Output:
l:269
itemNames.length, itemPriceall 23 97
l:284
In your for loop, your condition is y < itemNames.length, but the initial value of y is undefined. Thus, the condition is falsy. If you want to do a numeric comparison, you should initialize y to a numerical value.
I'd suggest var y = 0.
for(var y = 0; y < itemNames.length; y++)
was it; I expected y to be empty and numeric.
Thanks to https://stackoverflow.com/users/4265939/neilsimp1

Check if an array element/item is undefined

How do I add to z only if y exists without adding a zero instead?
var x=[-1,2,44,6];
var y=[33,2,1]; //a shorter array where y[3] does not exist
var z=[];
var i=x.length;
while(i--){
z[i]=x[i]+y[i];
}
When I know that all the x's exist but i do not know if there is a y for each x.
Also the problem may include more arrays of varying undetermined sizes (not just x and y, say t, u, v, w named arrays that may or may not have same lengths)
How would I loop through adding all arrays together without changing the loop, creating NaN or adding any zeros?
Can this be done inline?
You just need a if condition to check if the lengths of the array are equal.
if(x.length == y.length) {
var i = x.length;
while(i--)
z[i]=x[i]+y[i];
}
while (i--) {
z[i] = ((i > y.length - 1)? x[i] : x[i] + y[i]);
}
var x=[-1,2,44,6];
var y=[33,2,1]; //a shorter array where y[3] does not exist
var z=[];
var i=Math.max(y.length, x.length);
while(i--){
if (typeof y[i] !== 'undefined' && x[i] !== 'undefined') {
z[i]=x[i]+y[i];
}
}
This works best
var y=[];
var x=[1];
var z=(x[0]+(y[0]?y[0]:null)||undefined);
y has no existing values. x has a value we know exists. I can safely add x to z and safely add null to z if y does not exist. For whatever reason if everything were to go null then I end up with z undefined.

Javascript concatenate strings in array

Why does the following code not work? Can't figure it out.
var string = "";
for (var x; x < numbersArray.length; x++)
string += numbersArray[x];
alert(string);
string is empty at the end.
x is undefined, which is not less than any number.
Therefore, your terminating condition is always false.
You probably want to start at 0.
var string = "";
for (var x=0; x < numbersArray.length; x++)
string += numbersArray[x];
console.log(string);
Just make sure to initialize your x.

Colon operator ":" before function call (javascript)

I was looking at the source to a website and I saw this strange href attribute in a link and I can't figure out what it's doing. It doesn't look like valid javascript. I thought maybe the colon operator here was being used as a way to access the function property popDocWin in the object javascript but when I tried to emulate that syntax on a test function it wouldn't work.
Exterior Adjustable
javascript: is a psuedo-protocol meaning "run the code following this." You can use it (in a browser context) anywhere a URL is valid. In this case, clicking the link "follows" the link, and the act of following the link runs the JavaScript rather than going anywhere. (This is also how bookmarklets work.) So the javascript: part of that isn't JavaScript, just the part after it.
However, something that looks like that is valid JavaScript: If it weren't in a URL, it would create a labelled statement. The primary use of labelled statements in JavaScript is breaking outer loops from within inner ones, like this:
var x, y;
outer: for (x = 0; x < 5; ++x) {
for (y = 0; y < 5; ++y) {
if (x === 2 && y === 3) {
break outer;
}
snippet.show("x = " + x + ", y = " + y);
}
}
Output:
x = 0, y = 0
x = 0, y = 1
x = 0, y = 2
x = 1, y = 0
Note how the x loop was terminated from within the y loop.
var snippet = {
show: function(msg) {
document.body.insertAdjacentHTML("beforeend", "<p>" + msg + "</p>");
}
};
var x, y;
outer: for (x = 0; x < 3; ++x) {
for (y = 0; y < 3; ++y) {
if (x === 1 && y === 1) {
break outer;
}
snippet.show("x = " + x + ", y = " + y);
}
}
The colon is not before the function call, its after the word javascript!
It is telling your browser it should execute the javasript code after the colon.
Well, href isn't a place where your browser would expect javascript code, so javascript: tells the browser that it should treat whatever is after it as javascript.

Categories

Resources