[我正在尝试使下面的代码与IE11兼容,但我陷入了for / of循环行(第10行)。
// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
我相信mutationList是一个可迭代的nodeList(但是我可能错了)。对此,我该如何将for(let mutation of mutationsList) {
转换为传统的for循环?对于只懂基本JavaScript的人,您也可以将for(let mutation of mutationsList) {
转换为更简单的用语吗?
for...of
循环使用for...of
枚举Symbol.iterator
上存在的迭代器。这意味着迭代器的行为将完全被传统的Symbol.iterator
所规避。也就是说,在许多情况下,您正在处理可以使用整数索引枚举的数组或类似数组的对象。
对于这些简单的情况,它们大约翻译为iterable protocol:
for loop
大致相当于:
like so
这是ES6,您需要ES5:
for(let x of [1,2,3]) {
console.log(x)
}
翻译
for (var _i = 0, _arr = [1, 2, 3]; _i < _arr.length; _i++) {
var x = _arr[_i];
console.log(x);
}