gpt4 book ai didi

javascript - JQuery:无法通过 $.each 循环动态数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:31 24 4
gpt4 key购买 nike

为什么不能通过 $.each() 循环动态数组?

var array = [];
array['one'] = 'two';
$.each(array, function( key, value )
{
//not get in loop
alert(value);
});

最佳答案

对于数组,$.each() 仅循环遍历编号索引。如果你想遍历命名属性,你必须使用一个对象。

var obj = {};
obj['one'] = 'two';
$.each(obj, function( key, value )
{
console.log(key, value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这在 documentation 中有解释:

Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

关于javascript - JQuery:无法通过 $.each 循环动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com