JS arrays - advanced assignment [duplicate] - javascript

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?

Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation

As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)

Related

shortcut symbol for converting toString [duplicate]

This question already has answers here:
What's the best way to convert a number to a string in JavaScript?
(25 answers)
Closed 1 year ago.
As you know, if I want to the get numeric value of a variable (e.g. $event) I'd do:
<ax-text-box (valueChange)='documentSearchItem.fromPrice=(+$event)'></ax-text-box>
I add a + to do that.
Is there a simple way like this, to get the string value of a variable ?
p.s. I don't want to use a method. I want to be able to use it in HTML templates.
let v = 2 // whatever value
let s = v.toString()
Lots of ways. A short one without methods is using template strings:
let inputNum = 222;
let newString = `${inputNum}`;
console.log(typeof(newString));

Javascript string update doesn't change the string itself [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 1 year ago.
I have following simple javascript code:
s="hello"
s[0]="X"
console.log(s[0])
The output is h, but I have updated it as X, I would ask why I got such result, thanks.
Strings in JavaScript are primitives, which means they are immutable, ie. you are not able to change them. If you were running your code in strict mode then this would throw an error.
If you wanted to modify this string you would need to effectively create a copy of it, and then assign that to the s variable eg.
s = "X" + s.substring(1)

Why is √ is not allowed as a objectName/stringName/functionName/NumberName? [duplicate]

This question already has answers here:
What characters are valid for JavaScript variable names?
(12 answers)
Closed 7 years ago.
I am coding a scientific calculator and I need some help:
function √(in){
return Math.sqrt();
}
// throws an error
var √ = function(in){
return Math.sqrt();
}
// also throws an error
var √ = "sqrt";
√randomSqNum = 100,
√random = {sqrt:4,cubert:8},
√sqNum = ["0","1","4","9","16","25"],
√null = null,
√undefined = undefined;
They all throw an error!
Please explain why they throw an error.
Also, Is there a way around this?
In Javascript, variable names must begin with a letter, _ or $. More information here:
http://www.w3schools.com/js/js_variables.asp
JavaScript follows annex 31 of the unicode standard regarding identifier names.
I assume you are using U+221A as character. As you can see from the linked page, it can neither be used at the beginning of an identifier nor within it:
(likely because it is not even a letter).
Compare that to π, which is a letter and which can be used in an identifier name.
Also, Is there a way around this?
No. However, you can always try to find letters that look similar.
You cannot use it directly as a name, but you can use it as key.
var f={}
f["√"] = Math.sqrt
alert(f["√"](5))
In such way you can define +-*/ and many other funcions.
f["+"] = function(a){
return a.reduce(function(p,v){
return p+v
},0)
}
And when you have a parsed statement tree in form {o:fn,a:[s1,...,sn]} where fn is function name and s1,...,sn are subtrees or values, then you can simply get the result:
function calc(st){
return (typeof st == 'object')?f[st.o].apply(null,st.a.map(calc)):st
}

Using String to get JSON Property [duplicate]

This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']

javascript RegExp pattern change after used with test() method [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 9 years ago.
I have this simple pattern that validate Time - 24 Hours Mode -
var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g;
If i execute this pattern with .test() method twice i get two different values
Like This
CODE
console.log(patt.test('01:09')); // true
console.log(patt.test('01:09')); // false
i have notice that if i do the following i get the same result :
var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g;
console.log(patt.test('01:09')); // true
var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g;
console.log(patt.test('01:09'));//true
Question
i'll re-initiate the patt object as a work around in my case but i'm very curious to know what happens
Also i notice that patt object doesn't change after using it with test() Method
jsFiddle for those how want to prove something
Remove the global flag. Currently it's searching at the end of your input string for the second time, where it won't find the pattern again. See docs for the lastIndex property.

Categories