下面是一段工作代码。 “= true”部分让我感到困惑。这就是我认为正在发生的事情。
1- 创建空数组。
2-获取选定的列表项(目标)并循环。
3-如果目标列表项的类属性不在数组中,则输入 if block 。
4-添加目标列表项的类属性并添加
到数组。
我的理解是javascript使用“push”而jquery使用“add” 将项目插入数组中。下面的代码没有使用push或add。
var foo = [];
$($targets).each(function(i) {
if (!foo[$(this).attr('class')]) {
foo[$(this).attr('class')] = true;
}
});
最佳答案
代码有缺陷,如果你想使用字符串作为键,你应该使用对象而不是数组:
var foo = {};
然后它检查对象中的键是否为假,尽管您可能需要使用 in
运算符检查严格存在:
$targets.each(function() {
var klass = this.className; // cache, no need for jQuery
// if `foo` doesn't have the key `klass` then add it
if (! (klass in foo)) foo[klass] = true;
});
关于javascript - 这段代码是否将类属性添加到 foo 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149987/