简体   繁体   中英

Unexpected Javascript for-loop behavior inside Chrome

So I am getting incredible weird java script behavior inside a chrome tab. The page is behind a login so I can't post it but can someone explain exactly what is happening???

for(var z in ""){ console.log(z) }
contains
//undefined

hmm...

var key = ""

for(var i in key){ console.log(i) }
contains
//undefined
Object.getOwnPropertyNames(key)
//["length"]
Object.getOwnPropertySymbols(key)
//[]
window[key]
//undefined

At first I thought this was one of those JS behaviors and was ready to submit it to JSWTF but the behavior runs properly in another chrome tab:

for(var i in ""){ console.log('ran',i) }
//undefined

How did a value get assigned to a blank string? Where is it? What is the for loop doing?

edit: The same page in firefox returns expected behavior in console. I have not tested other browsers

You have an ES6 shim on the original page which adds the function contains() to the String prototype. You can do this yourself by doing something like:

String.prototype.contains = 
    function(e) {
        return this.indexOf(e) > -1;
    };

The ES6 function ultimately standardized on is includes() , so you'll probably see that function name change in the future when a developer updates the shim.

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