Geo*_*ard 3 javascript jquery prototypejs
我是Prototype的新手,但我总是使用jQuery.我有一个网站,我需要使用jQuery和Prototype.我遇到以下代码问题:
var x = [];
console.log(x);
for (var l in x)
{
console.log(l);
}
Run Code Online (Sandbox Code Playgroud)
运行此代码,x包含以下内容:
each
eachSlice
all
any
collect
detect
findAll
select
grep
include
member
inGroupsOf
inject
invoke
max
min
partition
pluck
reject
sortBy
toArray
entries
zip
size
inspect
find
_reverse
_each
clear
first
last
compact
flatten
without
uniq
intersect
clone
预期结果(无原型):
There are no child objects
Prototype为什么会这样做,以及如何阻止它?
谢谢
你不应该使用for...in数组,这正是原因.
for...in循环遍历对象的所有属性.这包括其属性(在本例中为数组索引)和添加到的属性prototype.
对于数组,只需使用普通for循环.
var x = [];
console.log(x);
for(var i = 0, len = x.length; i<len; i++){
console.log(i, x[i]);
}
Run Code Online (Sandbox Code Playgroud)
注意:我这样做var i = 0, len = x.length是因为它只length从数组中获取一次,而不是每次迭代.它可能会更快.
你不for..in应该使用数组,你应该使用for( i=0; i<length; i++).但除此之外:
for( l in x) {
if( x.hasOwnProperty(l)) {
// l is a property of your object
}
}
Run Code Online (Sandbox Code Playgroud)
这基本上忽略了循环的原型链.
| 归档时间: |
|
| 查看次数: |
216 次 |
| 最近记录: |