为什么$ .each()不能与在jquery中具有字符串索引的数组一起使用? [英] why does $.each() not work with arrays that have a string index in jquery?

查看:48
本文介绍了为什么$ .each()不能与在jquery中具有字符串索引的数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

版本a:

var x = [];
x['abc'] = 'd';
x['xyz'] = 'abbb';
$.each(x, function(i, el) {
  console.error(el);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

不起作用.控制台中无输出,请参见此处:

does not work. No output in console see here:

如何使版本可行?

推荐答案

来自文档

具有length属性的数组和类似数组的对象(例如函数的arguments对象)通过从0到length-1的数字索引进行迭代.其他对象通过其命名属性进行迭代.

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.

由于x是一个数组,因此仅考虑其数字属性,而不考虑其命名属性.由于没有任何这些内容,因此不会打印任何内容.

Since x is an array, only its numeric properties are considered, not its named properties. Since it doesn't have any of these, nothing is printed.

您可以通过使用对象而不是数组来使其工作.

You make it work by using an object instead of an array.

var x = {};
x['abc'] = 'd';
x['xyz'] = 'abbb';
$.each(x, function(i, el) {
  console.error(el);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于为什么$ .each()不能与在jquery中具有字符串索引的数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆