简体   繁体   中英

add property to a string

Who can help me understand following code

 var str = 'test1' str.len = 4 var strlen1 = str.len console.log('strlen1 = ', strlen1) // strlen1 = undefined var strlen2 = str.len = 4 console.log('strlen2 = ', strlen2) // strlen2 = 4

Why it got this output? Thank you

If you want to add a property to a Sting object you can do this :

 String.prototype.len = null; var str = new String('test1'); str.len = 4 var strlen1 = str.len console.log('strlen1 = ', strlen1) // strlen1 = 4

And when you write

 var str = "test1"; var strlen2 = str.len = 4 console.log('strlen2 = ', strlen2) // strlen2 = 4 console.log('str.len = ', str.len) // strlen2 = undefined

str.len is still undefined

str.len = 4 str is a String so you can't set properties to it.

var strlen2 = str.len = 4 strlen2 is a normal variable that equals 4. here str.len still undefined

You would be able to do that as below code

 var x = 'this is string'; var data = {} data.len = x.length; console.log(data.len)

As str is a string literal, str.len = 4 is basically rendered as

var temp = new String(str);
temp.len = 4;
temp = null

As you can see any update applied were temporary and are not available after that line. Hence, as str.len is undefined, with var strlen1 = str.len , you assign undefined to strlen1

var strlen2 = str.len = 4 is basically rendered as

var strlen2 = 4;
str.len = 4;

So as you can see there are 2 different assignment rather than 4 being assigned to str.len and then str.len assigned to strlen2

If you want to the first condition to work, make str a String object. Try following

 var str = new String('test1') str.len = 4 var strlen1 = str.len console.log('strlen1 = ', strlen1) // will paint 4

You can see, by testing that:

var  str = 'test1'
str.len = 4
console.log(str.len) // Undefined

That being said, you realize you can't add properties to a string. You probably want to use an object instead.

And btw, do you really need to add that '.len' there? Can't you use the string.length ?

 var z=undefined=4 console.log(z) //4

Your expression str.len will give undefined, You can not set a property to a string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM