+ 1
Assign and use javascript property and keyword as a variable
Suppose, a = "aaa" l = length a.length //gives 3 a.l //gives undefined but, c = console.log c(a) //gives aaa How can I do this for .length property also?
5 Réponses
+ 2
You can destructure the length property:
var a = "aaa"
var { length: l } = a;
console.log(l); // 3
But the value is not dynamically linked:
a += "aa";
console.log(l); // 3
You need to refresh its value:
({ length: l } = a;
console.log(l); // 5
...
Anyway, you could access dynamically and simply by doing:
var a = "aaa", b = "bbbbb";
var l = "length";
console.log(a[l]); // 3
console.log(b[l]); // 5
a += b;
console.log(a[l]); // 8
Obviously, you could also define a getter on the String prototype as an alias of the original length property, but it's widely unadvised to alter builtin prototype...
+ 1
You can do :
const l = a.length
+ 1
Med Amine Fh but I have lot of strings to use .length..
So, I want to do this to reduce code size.
+ 1
Create a function that returns or console log the length like so :
function len(x){
//console.log(x.length)
return x.length
}
and you can store the returned value like so :
const lengthA = len(a)