问题
for (let x of a) does not work in IE11. Can I replace it by for (let x in a) ?
for (let key in a) {
s += key + ": " + a[key];
s += "<br />";
}
for (let key of a) {
s += key + ": " + a[key];
s += "<br />";
}
回答1:
for...of
is not supported in IE11 yet.
You can use for..in
to iterate over as it has the support from IE6.
If you just want to add the key
and value
, you can use Object.keys
and build the string that is needed.
let f = '';
let s = '';
let a = {
firstName: 'Hello',
lastName: 'JS',
address: 'ecma'
};
for(let key in a) {
s += key + ": " + a[key];
s += "<br />";
}
Object.keys(a).forEach(function(key) {
f += key + ": " + a[key];
f += "<br />";
});
document.querySelector('.for-in').innerHTML = f;
document.querySelector('.object-keys').innerHTML = s;
.for-in {
border: 1px solid green;
min-height: 20px;
padding: 20px;
}
.object-keys {
margin-top: 20px;
border: 1px solid red;
min-height: 20px;
padding: 20px;
}
<div class="for-in">
</div>
<div class="object-keys">
</div>
回答2:
IE11 doesn't support for..of
. Here's the compatibility table from MDN:
Another idiomatic option for this type of string building is via Array.prototype.reduce:
var string = Object.keys(a).reduce(function(acc, key) {
return acc + key + ': ' + a[key] + '<br />';
}, '');
来源:https://stackoverflow.com/questions/46458493/for-loop-in-javascript