有人可以解释seen[item]
的工作原理吗?
var a = ["a","a","a","b","b","c","D","D","e",6,6,7,8,9,"a",'b','a',"c","","","",""];
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for(var i = 0; i < len; i++) {
var item = a[i];
if(seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out;
}
var e = uniq_fast(a);
console.log(e);
每次都会返回undefined
:
var a = [1,1,1,1,1,2,2,3,4,4,4,4,4,5,"a",'b','a',"c"];
for(var i = 0; i < a.length; i++) {
var seen = {};
var item = a[i];
var x = seen[item];
console.log(x);
}
答案 0 :(得分:1)
我已经在代码中添加了注释,您还可以在循环之前检查google Developer工具(或其他等效的浏览器)设置的断点,并逐步查看每个变量的值。
var a = ["a","a","a","b","b","c","D","D","e",6,6,7,8,9,"a",'b','a',"c","","","",""];
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
// if i == 0;
for(var i = 0; i < len; i++) {
var item = a[i]; // item is "a" because that's first item in array
if(seen[item] !== 1) {
seen[item] = 1; // seen is {"a": 1} it's the same as seen['a'] = 1
out[j++] = item;
}
}
return out;
}
在第二个代码中:
var a = ["a","a","a","b","b","c","D","D","e",6,6,7,8,9,"a",'b','a',"c","","","",""];
for(var i = 0; i < a.length; i++) {
var seen = {}; // you have empty object
var item = a[i]; // item is "a"
console.log(seen[item]); // this is undefined because seen["a"] is empty,
// you never adding anything to seen
}
答案 1 :(得分:0)
从本质上讲,不超过
object['a'] = object.a