数组显示零长度,而each()没有值 [英] Array displays zero length and no value with each()

查看:103
本文介绍了数组显示零长度,而each()没有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PHP的了解要比对JQuery的了解和对数组的那种了解更为熟悉.我已经阅读了论坛上有关该主题的几乎所有帖子,但无法使其正常工作.

I am more familiar with PHP than with JQuery and kind of stuck on arrays. I have read just about all the posts on the forum on this subject but can't get it to work.

我有一个我相信是数组的东西. 在PHP中看起来像这样的东西

I have what I believe to be an array. Something that would look like this in php

myArr = ['option-4' => '3','option-1' => '8', 'option-3' => '0' ];

在JQuery中,我可以使用命令来检索值

In JQuery I can retrieve the values by use of the command

var x = myArr['option-1'];

这一切都很好,但是我需要做的是将这些值做成字符串.因此,我需要遍历元素并将元素的值添加到字符串中.问题是循环.

This all works fine but what I need to do is make a string of the values. So I need to loop through the elements and add the value of the element to the string. The problem is the loop.

当我检查数组的长度时

alert("Elements in array "+myArr.length);

它总是返回零.

当我尝试类似的东西

$.each(myArr , function(i, val) { 
  alert(myArr[i]); 
});

什么都没显示.

我显然缺少一些东西,我的PHP知识一定是在阻止东西. 谁能帮忙吗?

I am missing something obviously, my PHP knowledge must be blocking things. Can anyone please help?

推荐答案

这不是有效的JavaScript数组.您要使用一个对象:

That is not a valid JavaScript array. You want to use an object:

var myArr = {'option-4': '3', 'option-1': '8', 'option-3': '0' };

然后您可以在其中使用for ..遍历所有键:

You can then iterate over all keys using a for .. in:

for (var key in myArr) {
    alert(myArr[key]);
}

这等效于PHP中的关联数组.请注意,您需要使用显式键来访问元素,而不能使用索引,例如myArr[0].

This is equivalent to a associative array in PHP. Note that you need to use the explicit key to access an element, you cannot use an index, eg myArr[0].

这篇关于数组显示零长度,而each()没有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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