z***@163.com
z***@163.com
  • 发布:2017-05-05 18:36
  • 更新:2017-05-07 17:32
  • 阅读:1196

【报Bug】for in 遍历数组 如果 数组重写 Array.prototype.findIndex 会多遍历一次

分类:HBuilder

详细问题描述
[内容]
for in 遍历数组 如果 数组重写 Array.prototype.findIndex 会多遍历一次

重现步骤
[步骤]
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.findIndex called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;

for (var i = 0; i < length; i++) {  
  value = list[i];  
  if (predicate.call(thisArg, value, i, list)) {  
    return i;  
  }  
}  
return -1;  

};
}

        var myArray = new Array(1,2,3,4,5);  
        for(var i in myArray)  
        {  
            console.log(i);  
        }  

[结果]
0 1 2 3 4 findIndex
[期望]
0 1 2 3 4
运行环境
[系统版本]
[浏览器版本]
[IDE版本]
[mui版本]

附件
[代码片段]
[安装包]

联系方式
[QQ] 136177789
[电话] 13810880391

2017-05-05 18:36 负责人:无 分享
已邀请:
NewsNing

NewsNing - 天行键

这个不是Bug,是你在Array的原型链上拓展了一个方法,然后在实例化Array后,for in 会把这个拓展的方法打印出来。
你不妨用forEach来遍历

            Array.prototype.myFindIndex = Array.prototype.myFindIndex || function(value){  
                return this.indexOf(value)  
            }  

            var arr = new Array(1,2,3,4,5)  
            for(var i in arr){  
                console.log(i + ' ' +typeof i)  
            }  

            arr.forEach(function(item){  
                console.log(item + ' ' +typeof item)  
            })  

console控制台显示

0 string  
1 string  
2 string  
3 string  
4 string  
myFindIndex string  
1 number  
2 number  
3 number  
4 number  
5 number
z***@163.com

z***@163.com (作者)

那么 我如果实例化 原型了, 是不是 所有的 for in 都会有问题, 你们的 mui.picker.min.js 里面也有用到 了for in的地方 不是也出错了么?

z***@163.com

z***@163.com (作者)

如果是这样,我就不能对Array 进行任意扩展了。

该问题目前已经被锁定, 无法添加新回复